Many-to-Many and Low-Resource Translation › Code Implementation

Michael BrenndoerferNovember 25, 202611 min read
Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 193Many-to-Many and Low-Resource Translation › Code Implementation
Reading section 8 of 11 · Code Implementation · 11 minSection 8 of 11 · 11 min

Section 8 of 11 · 11 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

An optional NLLB example shows how source and target language codes are supplied. The executable notebook trains the synthetic translation model on CPU, examines a mixture-of-experts router, and plots the results.

Setup

Run the full notebook from the repository with the book’s plotting helper available. The setup cell imports the scientific stack and seeds PyTorch, Python’s random module, and NumPy. If you run just the worked example without the helper, its setup supplies a minimal plot style. The notebook reports one seeded run.

PythonIn [8]
CollapseExpand
import math
import os
import random
import sys

import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

# make the book style helpers importable when building from the repo root
for _p in ("apps/web/content/notebooks", "../apps/web/content/notebooks"):
    if os.path.isdir(_p) and _p not in sys.path:
        sys.path.append(_p)

try:
    from book_plot_style import (
        PALETTE,
        label_bars,
        polish_axes,
        seed_book_plots,
        use_book_style,
    )

    seed_book_plots()
    _BOOK_STYLE = True
except Exception as _e:
    print(f"book_plot_style unavailable ({_e}); using a minimal fallback.")
    _BOOK_STYLE = False
    PALETTE = {
        "primary": "#1f77b4",
        "teal": "#2ca02c",
        "rose": "#d62728",
    }

    def use_book_style():
        plt.rcParams.update(
            {
                "figure.dpi": 110,
                "axes.spines.top": False,
                "axes.spines.right": False,
            }
        )

    def polish_axes(ax):
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        return ax

    def label_bars(ax, bars, labels=None):
        ax.bar_label(bars, labels=labels, padding=3)


torch.manual_seed(0)
random.seed(0)
np.random.seed(0)
device = torch.device("cpu")
torch.set_num_threads(1)
print(f"device = {device}, book style = {_BOOK_STYLE}")

A real many-to-many model

This optional example uses the dense NLLB-200 distilled 600M checkpoint. The earlier sparse-routing results describe the separate 54.5B research model. If you already have the 600M tokenizer and weights on disk, point checkpoint at that local directory and run the following three cells in order. The notebook skips them during automatic execution. For each input, src_lang sets the source language code in the tokenized sequence. The decoder receives the target language code as its first generated token after the decoder-start token through forced_bos_token_id. The Transformers NLLB documentation uses convert_tokens_to_ids to obtain the target ID.

PythonIn [14]
CollapseExpand
from pathlib import Path

import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

checkpoint = Path("/path/to/nllb-200-distilled-600M")
if not checkpoint.is_dir():
    raise FileNotFoundError(f"Expected a local NLLB checkpoint at {checkpoint}")

Load the local tokenizer with the source code, then load the local model weights.

PythonIn [16]
CollapseExpand
source_language = "eng_Latn"
tokenizer = AutoTokenizer.from_pretrained(
    checkpoint,
    src_lang=source_language,
    local_files_only=True,
)
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint, local_files_only=True)
model.eval()

Supply a target code for each generation call.

PythonIn [18]
CollapseExpand
text = "The committee approved the new policy after a long debate."
inputs = tokenizer(text, return_tensors="pt", truncation=True)
target_languages = ["fra_Latn", "deu_Latn", "spa_Latn", "swh_Latn", "zho_Hans"]
with torch.inference_mode():
    for target_language in target_languages:
        target_token_id = tokenizer.convert_tokens_to_ids(target_language)
        if target_token_id is None or target_token_id == tokenizer.unk_token_id:
            raise ValueError(f"Unknown target language code: {target_language}")
        translated = model.generate(
            **inputs,
            forced_bos_token_id=target_token_id,
            max_new_tokens=64,
            num_beams=4,
        )
        print(
            target_language,
            tokenizer.batch_decode(translated, skip_special_tokens=True)[0],
        )

The checkpoint weights stay fixed as the target language changes. The snippet uses local files, and the notebook build runs the synthetic example below.

A tiny model with zero-shot directions

The synthetic task gives us six training directions and six held-out directions. Each held-out direction lacks a supervised table of its own. Two stored tables can still solve the constructed task by chaining the source-to-English and English-to-target mappings. The notebook compares two explicit decoding passes through English with one direct pass. A correct direct output leaves open what internal representation the model used.

PythonIn [9]
CollapseExpand
LANGS = ["en", "fr", "de", "es"]
LANG2IDX = {l: i for i, l in enumerate(LANGS)}
V = 20
K = 6
PAD, BOS, EOS = 0, 1, 2
TOK_OFFSET = 3
VOCAB = TOK_OFFSET + len(LANGS) * V

torch.manual_seed(0)
perm = torch.stack([torch.randperm(V) for _ in LANGS]).to(device)


def to_tokens(concepts, lang_idx):
    surface = perm[lang_idx].gather(1, concepts)
    return TOK_OFFSET + lang_idx.unsqueeze(1) * V + surface


TRAIN_DIRS = [
    ("en", "fr"),
    ("en", "de"),
    ("en", "es"),
    ("fr", "en"),
    ("de", "en"),
    ("es", "en"),
]
HELD_DIRS = [
    ("fr", "de"),
    ("de", "fr"),
    ("fr", "es"),
    ("es", "fr"),
    ("de", "es"),
    ("es", "de"),
]


def make_batch(dirs, batch_size):
    idx = torch.randint(0, len(dirs), (batch_size,), device=device)
    src_idx = torch.tensor(
        [LANG2IDX[dirs[i][0]] for i in idx.tolist()], device=device
    )
    tgt_idx = torch.tensor(
        [LANG2IDX[dirs[i][1]] for i in idx.tolist()], device=device
    )
    concepts = torch.randint(0, V, (batch_size, K), device=device)
    src = to_tokens(concepts, src_idx)
    tgt = to_tokens(concepts, tgt_idx)
    return src, src_idx, tgt, tgt_idx


print("vocabulary size:", VOCAB)
print("training directions:", TRAIN_DIRS)
print("held-out directions:", HELD_DIRS)

The model is a small transformer encoder-decoder with a language embedding added to each token. Source and target language IDs condition their respective embeddings, and the decoder attends to the encoder states with standard Transformer cross-attention. The causal mask blocks each decoder position from attending to later target positions. The synthetic token IDs also identify the language, because each language has its own ID range. Across directions, the model uses the same encoder and decoder weights.

PythonIn [10]
CollapseExpand
class ToyMT(nn.Module):
    def __init__(self, d=64, n_heads=4, n_layers=2, ff=128):
        super().__init__()
        self.src_emb = nn.Embedding(VOCAB, d, padding_idx=PAD)
        self.tgt_emb = nn.Embedding(VOCAB, d, padding_idx=PAD)
        self.lang_emb = nn.Embedding(len(LANGS), d)
        self.pos = nn.Parameter(torch.randn(1, K + 2, d) * 0.02)
        enc_layer = nn.TransformerEncoderLayer(
            d, n_heads, ff, batch_first=True, activation="gelu", dropout=0.0
        )
        self.encoder = nn.TransformerEncoder(enc_layer, n_layers)
        dec_layer = nn.TransformerDecoderLayer(
            d, n_heads, ff, batch_first=True, activation="gelu", dropout=0.0
        )
        self.decoder = nn.TransformerDecoder(dec_layer, n_layers)
        self.head = nn.Linear(d, VOCAB)

    def forward(self, src, src_lang, tgt_in, tgt_lang):
        s = self.src_emb(src) + self.lang_emb(src_lang).unsqueeze(1)
        s = s + self.pos[:, : s.size(1)]
        t = self.tgt_emb(tgt_in) + self.lang_emb(tgt_lang).unsqueeze(1)
        t = t + self.pos[:, : t.size(1)]
        tgt_mask = torch.triu(
            torch.ones(t.size(1), t.size(1), device=src.device), diagonal=1
        ).bool()
        memory = self.encoder(s)
        out = self.decoder(t, memory, tgt_mask=tgt_mask)
        return self.head(out)


@torch.no_grad()
def greedy_decode(model, src, src_lang, tgt_lang, max_len=K):
    model.eval()
    B = src.size(0)
    s = model.src_emb(src) + model.lang_emb(src_lang).unsqueeze(1)
    s = s + model.pos[:, : s.size(1)]
    memory = model.encoder(s)
    out = torch.full((B, 1), BOS, device=src.device)
    for _ in range(max_len):
        t = model.tgt_emb(out) + model.lang_emb(tgt_lang).unsqueeze(1)
        t = t + model.pos[:, : t.size(1)]
        mask = torch.triu(
            torch.ones(t.size(1), t.size(1), device=src.device), diagonal=1
        ).bool()
        dec = model.decoder(t, memory, tgt_mask=mask)
        logits = model.head(dec[:, -1])
        nxt = logits.argmax(-1, keepdim=True)
        out = torch.cat([out, nxt], dim=1)
    return out[:, 1:]


toy = ToyMT().to(device)
print("parameter count:", sum(p.numel() for p in toy.parameters()))
PythonIn [11]
CollapseExpand
opt = torch.optim.Adam(toy.parameters(), lr=1e-3)
losses = []

for step in range(1, 2001):
    toy.train()
    src, src_idx, tgt, tgt_idx = make_batch(TRAIN_DIRS, 128)
    tgt_in = torch.cat([torch.full((128, 1), BOS, device=device), tgt], dim=1)
    tgt_out = torch.cat([tgt, torch.full((128, 1), EOS, device=device)], dim=1)
    logits = toy(src, src_idx, tgt_in, tgt_idx)
    loss = F.cross_entropy(logits.reshape(-1, VOCAB), tgt_out.reshape(-1))
    opt.zero_grad()
    loss.backward()
    opt.step()
    losses.append(loss.item())
    if step % 250 == 0:
        print(f"step {step:4d}  loss {loss.item():.4f}")
ConsoleOut [11]
CollapseExpand
step  250  loss 0.1801
step  500  loss 0.0086
step  750  loss 0.0034
step 1000  loss 0.0017
step 1250  loss 0.0012
step 1500  loss 0.0009
step 1750  loss 0.0006
step 2000  loss 0.0026

The loss measures next-token prediction given the correct earlier target tokens, including prediction of the end-of-sequence token. The evaluation instead generates six tokens greedily, feeding back its own guesses. It scores a sequence as correct only when all six predicted tokens match the reference. A single wrong token fails the whole sequence. This gives a strict test of whether the model translates a held-out direction successfully and leaves open how it represents the mapping.

PythonIn [12]
CollapseExpand
def count_exact(predictions, references):
    return int((predictions == references).all(dim=1).sum().item())


def evaluate_direction(model, src_name, tgt_name, n=300, pivot_name=None):
    src_idx = torch.full((n,), LANG2IDX[src_name], device=device)
    tgt_idx = torch.full((n,), LANG2IDX[tgt_name], device=device)
    concepts = torch.randint(0, V, (n, K), device=device)
    src = to_tokens(concepts, src_idx)
    tgt = to_tokens(concepts, tgt_idx)

    direct = greedy_decode(model, src, src_idx, tgt_idx)
    direct_exact = count_exact(direct, tgt)
    first_target_id = TOK_OFFSET + LANG2IDX[tgt_name] * V
    in_target_range = (direct >= first_target_id) & (
        direct < first_target_id + V
    )
    target_id_rows = int(in_target_range.all(dim=1).sum().item())

    pivot_exact = None
    if pivot_name is not None:
        pivot_idx = torch.full((n,), LANG2IDX[pivot_name], device=device)
        intermediate = greedy_decode(model, src, src_idx, pivot_idx)
        via_pivot = greedy_decode(model, intermediate, pivot_idx, tgt_idx)
        pivot_exact = count_exact(via_pivot, tgt)

    return direct_exact, target_id_rows, pivot_exact


n_eval = 300
train_acc = {
    f"{s}->{t}": evaluate_direction(toy, s, t, n=n_eval)[0] / n_eval
    for s, t in TRAIN_DIRS
}
held_results = {
    f"{s}->{t}": evaluate_direction(toy, s, t, n=n_eval, pivot_name="en")
    for s, t in HELD_DIRS
}
held_acc = {
    direction: direct_exact / n_eval
    for direction, (direct_exact, _, _) in held_results.items()
}

print("Trained directions:")
for direction, accuracy in train_acc.items():
    print(f"  {direction:8s} {accuracy:.3f}")
print("Zero-shot directions:")
for direction, accuracy in held_acc.items():
    print(f"  {direction:8s} {accuracy:.3f}")

print(f"Matched held-out evaluation (counts out of {n_eval})")
print("Direction  Direct exact  Direct target-ID rows  Via English exact")
for direction, (direct_exact, target_rows, pivot_exact) in held_results.items():
    print(
        f"{direction.replace('->', '→'):9s} {direct_exact:12d}"
        f" {target_rows:22d} {pivot_exact:18d}"
    )
ConsoleOut [12]
CollapseExpand
Trained directions:
  en->fr   0.993
  en->de   0.997
  en->es   0.997
  fr->en   0.960
  de->en   1.000
  es->en   1.000
Zero-shot directions:
  fr->de   0.000
  de->fr   0.000
  fr->es   0.000
  es->fr   0.000
  de->es   0.000
  es->de   0.000
Matched held-out evaluation (counts out of 300)
Direction  Direct exact  Direct target-ID rows  Via English exact
fr→de                0                      0                292
de→fr                0                      0                295
fr→es                0                      0                283
es→fr                0                      0                299
de→es                0                      0                297
es→de                0                      0                300

With one CPU thread and the locked PyTorch 2.13.0 environment, the trained directions scored between 288 and 300 exact matches out of 300. Every direct held-out direction scored zero. The greedy decoder chooses from the full vocabulary. It uses a target-language embedding and places no vocabulary mask on the output. The target-ID column counts rows with all six tokens in the requested language’s range. Those rows can still contain wrong concept tokens. The English pivot translates each held-out input twice, using the same model first to generate English tokens and then to generate the target tokens. Its exact-match counts use the same sampled inputs and references as direct decoding. A blind baseline that knows the target language and guesses each of its 20 concept tokens uniformly and independently has exact-match probability (1/20)6≈1.5625×10−8(1/20)^6 \approx 1.5625 \times 10^{-8}. Across 300 examples per direction it expects fewer than one correct sequence.

Mixture-of-experts

The translation toy uses dense feed-forward blocks. The following top-kk example shows how a router selects and combines expert outputs. For clarity, it computes all expert outputs before gathering the selected ones. This demonstrates the gate and the auxiliary loss. A sparse implementation would dispatch inputs to the selected experts to avoid the extra expert computation, which is the whole point of the sparse design in a real system.

PythonIn [13]
CollapseExpand
class TopKMoE(nn.Module):
    def __init__(self, d=64, num_experts=8, k=2, hidden=128):
        super().__init__()
        self.k = k
        self.num_experts = num_experts
        self.router = nn.Linear(d, num_experts)
        self.experts = nn.ModuleList(
            [
                nn.Sequential(
                    nn.Linear(d, hidden), nn.GELU(), nn.Linear(hidden, d)
                )
                for _ in range(num_experts)
            ]
        )

    def forward(self, x, return_aux=False):
        B, T, d = x.shape
        flat = x.reshape(B * T, d)
        logits = self.router(flat)
        topk = logits.topk(self.k, dim=-1)
        weights = F.softmax(topk.values, dim=-1)
        expert_outs = torch.stack(
            [e(flat) for e in self.experts], dim=1
        )  # (N, E, d)
        gathered = torch.gather(
            expert_outs, 1, topk.indices.unsqueeze(-1).expand(-1, -1, d)
        )
        out = (gathered * weights.unsqueeze(-1)).sum(dim=1).reshape(B, T, d)

        if not return_aux:
            return out

        probs = F.softmax(logits, dim=-1)
        one_hot = F.one_hot(topk.indices, self.num_experts).float()
        f = one_hot.sum(dim=(0, 1)) / (B * T * self.k)
        P = probs.mean(dim=0)
        aux = self.num_experts * (f * P).sum()
        return out, aux, f, topk.indices


moe = TopKMoE(d=64, num_experts=8, k=2).to(device)
x = torch.randn(512, 8, 64, device=device) * 0.5
out, aux, f, indices = moe(x, return_aux=True)
print(f"output shape: {out.shape}")
print(f"auxiliary load-balancing loss: {aux.item():.4f}")
print("assignment shares per expert:", [round(v, 4) for v in f.tolist()])
ConsoleOut [13]
CollapseExpand
output shape: torch.Size([512, 8, 64])
auxiliary load-balancing loss: 1.0098
assignment shares per expert: [0.1514, 0.0883, 0.1543, 0.1622, 0.1045, 0.1311, 0.1012, 0.1071]

The assignment counts sum to 2×512×82 \times 512 \times 8 because both selected experts are counted for each token. Dividing by that total gives shares that sum to one before rounding. The displayed four-decimal values sum to 1.0001. The example reports the unweighted auxiliary term for a randomly initialized router. In training, you could add a weighted copy of this term to the task loss and track whether expert usage becomes more balanced.

Plotting the results

VisualizationOut [14]
CollapseExpand
Bar chart comparing exact-match accuracy on trained and held-out zero-shot translation directions.
Six-token exact-match accuracy on newly sampled sequences. The first six bars show trained directions and the next six show held-out directions. Independent guessing from the 20 valid target tokens gives an exact-match probability of about 1.56 × 10⁻⁸, too small to distinguish from zero on this scale.
VisualizationOut [15]
CollapseExpand
Bar chart of assignment shares across eight experts with a uniform reference line.
Share of all top-2 assignments going to each of eight experts before training. The dashed line marks the uniform assignment share of 1/8.

The dashed line gives a reference for comparing the experts' assignment counts. The router in this plot has received no training updates. To measure the effect of the auxiliary loss, you would need to compare trained routers with and without the term under the same conditions.

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