Many-to-Many and Low-Resource Translation
Learn how many-to-many translation models share parameters across dozens of languages, with language tags, zero-shot directions, capacity, and sparse experts.
Language AI HandbookAll chapters Many-to-Many and Low-Resource Translation
Start with one checkpoint per ordered translation direction, such as Spanish to French. For two hundred languages that design calls for 39,800 checkpoints if you cover every non-identity direction. You can share a data pipeline or release process across those checkpoints, but you still have to track which directions each one serves.
A many-to-many model uses one set of parameters for several directions. Sharing can improve translation for some directions and introduces interference when updates that help one direction hurt another. One way to add expert capacity is to keep more feed-forward weights and select a subset for each token. The chapter also explores what happens when you ask a model to translate a direction it never saw during training.
The neural machine translation material in Machine Translation and Speech Translation introduces the encoder and decoder used here. The pretraining chapter in Multilingual Language Models and Cross-Lingual Transfer discusses balancing data across languages. This chapter focuses on language tags, zero-shot translation, capacity, and sparse experts.
The N×N Problem
Start with a simple arithmetic fact. With languages, there are ordered translation directions. For , that is 90. For , it is 9,900. For , it is 39,800. Here each of the source languages has possible targets, and French to German counts separately from German to French. The chart shows one curve for ordered directions and a second for bidirectional language pairs, which are half as numerous. If you deploy a separate checkpoint for each direction, this also gives the checkpoint count. A bilingual checkpoint that handles both directions changes the deployment count.
The arithmetic is easy to state but hard to feel. The figure below plots the direction count against the number of languages on log-log axes, so the curves approach slope two as the language count grows. The bidirectional-checkpoint curve stays a factor of two below the ordered-direction curve.
PythonIn [2]Expand
import numpy as np
languages = np.array([2, 5, 10, 25, 50, 100, 200, 400], dtype=float)
ordered_directions = languages * (languages - 1)
bilingual_checkpoints = ordered_directions / 2.0
ratio_10_to_200 = ordered_directions[6] / ordered_directions[2]VisualizationOut [3]Expand

The vertical gap between the two lines is the saving from bidirectional checkpoints, and it is constant. For large inventories, serving twice as many languages raises the line by about a factor of four.
The quadratic growth is what makes the problem painful. Doubling the number of supported languages roughly quadruples the number of ordered directions. Going from ten languages to two hundred multiplies the language count by twenty and the direction count by more than four hundred. A separate checkpoint and pipeline for each direction then means maintaining tens of thousands of artifacts. The natural response is to ask how much of the work can be shared.
Parallel data availability varies by direction. In a 103-language study, Arivazhagan et al. report a gap of nearly five orders of magnitude between the best- and least-resourced languages in their corpus. Shared training improved some low-resource directions relative to bilingual baselines in their experiments. The result depends on the direction and the sampling recipe.
Language coverage tells you which languages a model accepts as input or can be asked to produce. Quality can still vary by direction. Check the directions you plan to serve with data from those directions.
Pivot translation gives you a two-stage baseline for an unseen pair. For example, translate the source into English, then translate that output into the target language. The two decoding passes run in sequence. Because the second model receives the first model’s output, a mistranslation in the first stage can carry through. A many-to-many model can also decode directly into the target language.
Use pivot translation as a quality baseline for each unseen direction. Compare direct and pivot output on the same inputs and measure serving cost under the same workload. A direct model may use one decoding pass where the pivot uses two.
Pivot translation uses a third language between source and target. In a text-to-text pipeline, the output of the first hop becomes the input to the second.
Multilingual Neural Machine Translation
Multilingual NMT models can share an encoder, a decoder, and a tokenizer across languages, as in Johnson et al.’s system. Some designs share most parameters and add language-specific layers, as in Fan et al.’s experiments. A language tag is a token that identifies the input language or specifies the requested output language. The same source string can be translated into different languages, so a model needs a way to tell which output is wanted.
Sharing parameters is what lets one model serve several directions. The encoder learns a common way to represent sentences, and the decoder learns a common way to generate them. When one language lacks data, the shared weights still carry information from languages that have plenty. The cost of sharing is interference: the same weights must serve structures that may have little in common, and gradients from one language can disturb another. The rest of this chapter is largely about managing that tension.
In Google's multilingual NMT experiments, Johnson et al. prepended a token for the requested target language to the source sequence, such as <2es> for Spanish. The shared encoder read the tag along with the source tokens, and the shared decoder conditioned on the resulting encoder states. Some source-to-target directions absent from direct training could be translated this way, a result known as zero-shot translation.
Language tags
The tag’s position and the language it identifies are separate choices:
- Source-language tag on the encoder. Prepend the source language tag to the encoder input.
- Target-language tag on the encoder. Prepend the requested target language tag to the encoder input.
- Target-language tag on the decoder. Supply the requested target language in the decoder input.
- Forced first generated token. Use generation controls to force the target-language tag after the decoder-start token.
Johnson et al.’s encoder-side prefix identifies the requested target. A decoder prefix supplies a token as part of the decoder input, while forcing the first generated token constrains the token chosen at generation time.
The NLLB example below sets the source-language tag in the tokenizer with src_lang. It then uses forced_bos_token_id to force the decoder’s first generated token after decoder start to be the target-language tag. M2M-100 also conditions on source and target language identifiers. Follow the source and target conventions in the instructions for the checkpoint you run.
| Design | Encoder input | Decoder input | Language information supplied |
|---|---|---|---|
| Source tag on encoder | [fr] Bonjour | Guten Tag | Source language supplied to the encoder |
| Target tag on encoder | [de] Bonjour | Guten Tag | Requested target language supplied to the encoder |
| Target tag on decoder | Bonjour | [de] Guten Tag | Requested target language supplied to the decoder |
| Source tag on encoder and target tag on decoder | [fr] Bonjour | [de] Guten Tag | The encoder receives the source language and the decoder receives the target language |
A shared subword vocabulary lets identical subword units reuse the same token ID and embedding. Languages can also share encoder and decoder weights when their token inventories are disjoint. See Part V: Subword Tokenization for subword segmentation. With the model and sentence held fixed, a tokenizer that splits the text into more pieces gives the model more positions to process. A fixed vocabulary has a limited number of slots, so adding a unit for one group uses a slot that could have gone to another.
Zero-shot translation
Zero-shot translation evaluates a source-to-target direction that never appeared in direct training. Suppose you train on en→fr, en→de, fr→en, and de→en. You can then ask the model for fr→de and check the result. In Johnson et al.’s experiments, the model directly translated Portuguese to Spanish without Portuguese–Spanish training bitext.
A shared encoder and decoder can process a source and target combination that training never presented together. Johnson et al. visualized multilingual sentence representations that sometimes clustered by meaning, alongside clusters that reflected translation direction. The architecture gives the model a way to attempt an unseen direction.
The decoder can still produce output in the wrong language. A training mixture with many into-English examples gives the model extensive practice generating English. Measure target-language adherence separately from whether the translation preserves the source meaning.
Zero-shot directions need their own evaluation. Here are comparisons you can run with the same test sentences and decoding settings.
| Training condition | Evaluation check |
|---|---|
| Source and target seen in other directions | Compare the direct zero-shot output with a two-stage pivot baseline |
| High-resource source and target | Measure both directions to check for asymmetric quality |
| Low-resource target | Measure target-language adherence and meaning preservation separately |
| Target seen only as source | Check whether any training targets use the requested output language |
| Language tags are dropped | Compare a tag ablation with the fully tagged model |
You can test language-tag dropout, round-trip consistency, or balanced sampling against a baseline with the same training budget. Each changes a different part of the recipe. If direct bitext is available, compare a system trained on it with the zero-shot and pivot systems. M2M-100 supported 9,900 ordered translation directions across 100 languages and used training bitext for 2,200 directions. The NLLB project also mined parallel data for low-resource languages.
Plan the evaluation before deciding which directions to serve. Measure translation quality and target-language adherence on the directions that never appeared in training.
Compare zero-shot output with a pivot baseline and, where data permits, with a bilingual model. Report the results by ordered direction.
The Capacity Bottleneck
When you keep model size fixed and add languages, more directions share the same parameter budget. Multilingual training can improve some directions and hurt others. In one 103-language study, changing the sampling temperature altered the trade-off between low-resource transfer and high-resource regression. The term curse of multilinguality describes the degradation that can occur as language coverage grows under a fixed capacity budget.
Capacity, the data mixture, and optimization all matter. Two ways to think about the trade-off are:
- Parameter dilution describes the pressure of serving more directions with the same parameters. Which directions lose quality depends on the data and training recipe.
- Interference: languages with different scripts, syntax, and morphology share the same learned weights, and the gradients from one language can push the weights in a direction that hurts another.
Measure transfer and interference against bilingual baselines. The multilingual model can improve one group of directions while degrading another, and changing how often it sees each direction can shift that balance.
You can increase model capacity by widening the dense layers or by adding experts. A wider dense layer generally performs more arithmetic per token. A sparse layer can hold a larger bank of expert weights while evaluating only the selected experts for each token.
Mixture-of-Experts Translation
A mixture-of-experts (MoE) layer replaces a dense feed-forward network with a set of expert feed-forward networks. A router scores the experts separately for each token, then selects a small subset of them. In this top- example, the router uses a learned affine map.
where:
- is one token representation of width .
- is the number of experts. The router uses weights and bias .
- contains one router logit per expert. Its -th entry is .
- contains the indices of the largest logits, with .
The feed-forward block is a natural place to add experts because its inputs are token states processed independently. The Switch Transformer, for example, keeps the existing attention sublayer and replaces the ordinary feed-forward sublayer with routed experts.
Once the router has picked the experts, this gate normalizes their logits into weights and combines their outputs.
where:
- is the gate for selected expert . The denominator sums over selected indices , so the selected gates sum to one.
- is expert 's output, and is their weighted sum.
For example, if the router selects exactly two experts and their logits are equal, each receives half the weight. The expert arithmetic per token scales with in a sparse implementation, while stored expert weights scale with for equal-width experts. Holding and expert width fixed lets you add experts without increasing the selected-expert arithmetic. Scoring the experts and dispatching their inputs add work of their own, so per-token expert arithmetic alone cannot determine serving latency.
Load balancing
A router can send most tokens to a small set of experts, leaving other experts with few assignments. In a sparsely executed MoE, a token that sends no accepted assignment to an expert contributes no task gradient to that expert’s weights through that path. Assignments can change on later batches. Switch Transformer adds a load-balancing term to the task loss. Switch picks one expert and weights its output by that expert’s probability from the full router softmax. The selected-only softmax above would give a single selected expert weight one. The top- example below uses the same auxiliary expression with shares of all selected assignments.
where:
- is the fraction of selected assignments going to expert before any capacity limit. With tokens and selected experts per token, the denominator is , so . For Switch's top-1 case, each token makes one assignment.
- is the mean probability for expert across the batch, computed from the softmax over all router logits for each token.
- weights the auxiliary term relative to the task loss.
On a gradient update, the hard assignment shares act as fixed weights. Increasing is more costly for an expert with a large assignment share. Under uniform routing and router probabilities, , giving and . This is a normalization reference. For example, with two experts and three tokens assigning softmax probabilities , , and , the top-1 assignment shares are . The unweighted loss is about , below the uniform reference. Monitor actual expert loads alongside the loss.
The sweep below tests how the auxiliary loss responds as one router becomes more concentrated. It scales a fixed per-expert logit bias while holding the seeded token-level logit noise fixed. For each scale it records the top-1 assignment shares and the mean router probabilities, then evaluates the auxiliary expression above. The monotonic trend is a result for this controlled sweep. The two-expert example above gives a loss below the uniform reference.
PythonIn [4]Expand
import numpy as np
_bal_rng = np.random.default_rng(0)
NUM_EXPERTS = 8
NUM_TOKENS = 4096
ALPHA = 0.1
# fixed per-expert logit offset; scaling it concentrates the router
router_bias = _bal_rng.normal(size=NUM_EXPERTS)
token_logit_noise = _bal_rng.normal(size=(NUM_TOKENS, NUM_EXPERTS))
sweep_scales = np.linspace(0.0, 4.0, 41)
aux_losses = []
busiest_shares = []
for _t in sweep_scales:
logits = _t * router_bias[None, :] + token_logit_noise
probs = np.exp(logits - logits.max(axis=1, keepdims=True))
probs /= probs.sum(axis=1, keepdims=True)
chosen = logits.argmax(axis=1)
counts = np.bincount(chosen, minlength=NUM_EXPERTS)
f = counts / NUM_TOKENS
P = probs.mean(axis=0)
aux_losses.append(ALPHA * NUM_EXPERTS * float((f * P).sum()))
busiest_shares.append(float(f.max()))
aux_losses = np.array(aux_losses)
busiest_shares = np.array(busiest_shares)
uniform_share = 1.0 / NUM_EXPERTSVisualizationOut [5]Expand

The smallest busiest-expert share in this sweep is about 13.1%, slightly above the 12.5% reference. The auxiliary loss there is close to . At the other end the busiest share is about 83.5% and the loss is about 0.462. The loss alone does not identify which experts got the assignments.
For fixed hard shares and positive , this inner product assigns a larger coefficient to for experts with higher hard shares. The example above gives before multiplying by even though the assignments are skewed. Inspect per-expert assignment counts alongside the auxiliary loss to see where the tokens went.
The original Shazeer et al. MoE paper experimented with machine translation and language modeling. The GShard paper reports a roughly 600-billion-parameter model in a translation experiment from 100 source languages into English. The NLLB-200 54.5B model routes each token to up to two of 128 experts per MoE layer. The NLLB technical report compares its FLOPs with those of a 3.3B dense model. The full parameter count matters for checkpoint storage, while the FLOP estimate describes the operations evaluated for a given input.
Expert specialization
Do experts specialize by language? BASE Layers reported associations between token routing and local syntactic context in a language model. The NLLB technical report found that related languages tended to use similar expert sets in some early encoder and late decoder layers on FLORES dev. That is evidence about routing distributions in those layers.
Training and serving costs
Three practical costs matter alongside the FLOP count.
- Memory. Storing the full expert bank includes experts that may be inactive for a given token. At two bytes per weight, NLLB-200’s 54.5 billion weights require approximately 109 GB of raw storage before activations and other overhead.
- All-to-all communication. One expert-parallel layout sends token representations to devices that hold the selected experts and brings the outputs back. When comparing two layouts, measure this traffic alongside computation.
- Load balancing. If a router sends too many assignments to one expert, a fixed buffer can overflow while other experts have unused slots. Check assignment counts, dropped assignments, and the balance term together.
When an expert has a fixed buffer, assignments exceeding that buffer may be skipped. A capacity rule can start from the number of assignments each expert would receive under a uniform split.
where:
- is the number of assignments the expert can accept for this routing batch.
- is a capacity multiplier relative to the uniform load.
- is the number of tokens in the routing batch, and is the number of experts picked per token.
- is the number of experts, and the ceiling rounds up to an integer buffer size.
With top-1 routing, the uniform load is . With top-2 routing and one shared buffer per expert, each token can contribute two assignments, so the corresponding load is . If an assignment is skipped, that expert contributes no output or expert gradient for that assignment. A token can still pass through a residual connection or receive another selected expert’s output. A larger buffer can reduce dropped assignments and can use extra memory or pad the computation with idle slots.
To measure the effect of the capacity rule, draw one seeded vector of aggregate expert counts. The total equals two assignments per token, while the draw models counts across experts without recording which two experts a token uses. The simulation compares each count with . For fixed counts, which assignments drop can depend on their order, while the total follows from the counts and the buffer size.
PythonIn [6]Expand
import numpy as np
_cap_rng = np.random.default_rng(1)
CAP_EXPERTS = 8
CAP_TOKENS = 1024
CAP_K = 2
# a deliberately skewed router preference over experts
expert_preference = np.array([0.30, 0.22, 0.16, 0.11, 0.08, 0.06, 0.04, 0.03])
assignments_total = CAP_TOKENS * CAP_K
assignment_counts = _cap_rng.multinomial(assignments_total, expert_preference)
capacity_gammas = np.linspace(0.5, 2.5, 41)
dropped_fraction = []
for _g in capacity_gammas:
capacity = int(np.ceil(_g * assignments_total / CAP_EXPERTS))
kept = np.minimum(assignment_counts, capacity).sum()
dropped_fraction.append(1.0 - kept / assignments_total)
dropped_fraction = np.array(dropped_fraction)
uniform_gamma = 1.0VisualizationOut [7]Expand

At the uniform-split buffer, some expert counts exceed capacity and about 29.5% of assignments are dropped. In this synthetic draw, is the first value on the tested grid that accepts every assignment. Measure representative batches with the actual dispatch implementation to choose headroom for a target drop rate.
Low-Resource Strategies
Transfer learning starts from a model trained on a better-resourced direction and continues training on limited bitext for the new direction. Zoph et al. initialized an Uzbek-to-English model from a French-to-English parent. When you have several possible parent models, compare them on the same low-resource development set.
Back-translation turns target-side monolingual text into synthetic parallel training examples. To train A→B, use a B→A model to turn B text into synthetic A, then pair that synthetic A with the original B. Hoang et al. iterated this process in both directions, retraining a model on the new pairs before using it to generate inputs for the other direction. The reported gains varied by language pair. Edunov et al. studied ways to generate synthetic source text and scaled back-translation to much larger monolingual corpora.
Pivot translation gives you a baseline using the two directions already available. Compare it with direct zero-shot translation on the same test sentences. When direct data becomes available, include a supervised system in the comparison.
Data mining finds candidate parallel sentences in web crawls. The parallel data mining chapter in Machine Translation and Speech Translation describes the procedure. The NLLB team used multilingual sentence embeddings to recover additional parallel examples for low-resource languages.
Cross-lingual pretraining can give a translation model a starting point before it sees parallel data. mBART pretrains a multilingual encoder-decoder on a denoising objective. Its authors reported gains over random initialization on some low-resource translation tasks.
Worked Example
Let’s build a synthetic task with four languages: English, French, German, and Spanish. A sentence contains six entries drawn from the same inventory of 20 concepts. Each language maps concepts to tokens using a fixed permutation. To construct the correct target, invert the source permutation and apply the target permutation.
We train on English-to-{French, German, Spanish} and {French, German, Spanish}-to-English. We hold out the six directions among French, German, and Spanish: fr→de, de→fr, fr→es, es→fr, de→es, and es→de. This toy resembles one part of the OPUS-100 setup. In that benchmark, all training pairs included English and pairs between other languages were available for zero-shot tests.
The toy uses one encoder and one decoder across directions and adds language embeddings to token embeddings. The token ID ranges also differ by language. The fixed permutations define a learnable mapping for each supervised direction. Held-out exact-match accuracy measures whether the model gives the correct output for unseen source and target combinations.
Code Implementation
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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]Expand
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 . 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- 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]Expand
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]Expand
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 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]Expand

VisualizationOut [15]Expand

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.
Limitations and Impact
Evaluation is one limitation. Human translations can express the same meaning with different words or word order, as the original BLEU paper illustrates. A single reference can miss valid alternatives, and a small test set gives you fewer cases to diagnose. The next chapter takes up translation evaluation in more detail.
The second limitation is the data mixture. A many-to-many system trains on several directional tasks with different amounts of data. In the Arivazhagan et al. experiments, sampling temperature changed the balance of quality gains and losses across resource groups. Inspect those groups and the individual directions when you compare training recipes.
The third limitation is the uneven quality of zero-shot directions. In Table 1 of Zhang et al., the French-to-German baseline examples include a copy of the French source and an output that mixes French and English. Measure target-language adherence and meaning preservation separately, and compare failures with a pivot or direct system. Direct bitext, back-translation, and data mining give you alternatives to test where you can obtain the necessary data.
The fourth limitation is the cost of MoE. Count the entire checkpoint when estimating storage and profile dispatch and collection traffic on the devices you plan to serve from. FLOPs give you one input to that comparison.
Evaluate directions individually before offering them in one service. For a low-resource direction, inspect whether the model uses the requested language and whether translations preserve the source meaning on examples from the intended use.
A single multilingual checkpoint can reduce the number of artifacts to serve from to one when the alternative is a separate checkpoint for every ordered direction. The NLLB study illustrates how a sparse multilingual model can cover roughly 200 languages.
Summary
A many-to-many model can replace several bilingual checkpoints with a multilingual system that shares parameters and can use language tags to specify the requested output. The hypothetical fr→de direction illustrates what to test after training on en↔fr and en↔de. Compare the direct output with a pivot baseline and check whether it uses the requested language.
Capacity is one constraint. A fixed-size model shares its parameters across directions, and the effects of sharing vary with the direction and training recipe. Mixture-of-experts routing adds stored expert capacity while limiting the number of experts evaluated per token. It also introduces memory, communication, and load-balancing costs. The next chapter covers how to evaluate whether a translation system serves the languages and directions its readers need.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about many-to-many translation, language tags, zero-shot directions, capacity, and mixture-of-experts routing.
Many-to-Many and Low-Resource Translation
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!