Cross-Lingual Transfer and Alignment › Building It: Code Implementation
Language AI HandbookAll chapters The notebook uses a lexicon, a few sentence templates, and a small classifier. It computes cosine similarities and InfoNCE on the generated sentences, transfers the classifier from English to French and German, then checks the shape and parameter count of a bottleneck adapter. Everything runs on the CPU without downloading a model or a dataset. The point is not to reproduce a state-of-the-art result but to make the moving parts visible, so that each component of the transfer pipeline can be inspected on its own.
We give translation equivalents a common coordinate. For example, dog, chien, and Hund activate the same entry in the vector. We give not, pas, and nicht a shared negation coordinate. The lexicon omits the verb because the fixture uses that same action in every sentence.
PythonIn [5]Expand
import re
from itertools import product
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
ANIMALS = [
("The cat", "Le chat", "Die Katze"),
("The dog", "Le chien", "Der Hund"),
("The rabbit", "Le lapin", "Das Kaninchen"),
("The fox", "Le renard", "Der Fuchs"),
]
PLACES = [
("the kitchen", "la cuisine", "der Küche"),
("the garage", "le garage", "der Garage"),
("the garden", "le jardin", "dem Garten"),
("the studio", "le studio", "dem Studio"),
]
NEGATION = ("not", "pas", "nicht")
LANGUAGES = ("English", "French", "German")
LEXICON = [*ANIMALS, *PLACES, NEGATION]
token_to_feature = {
form.casefold().split()[-1]: i
for i, forms in enumerate(LEXICON)
for form in forms
}
def encode(sentences, *, keep_negation=True):
"""Normalize the active lexicon features in each input sentence."""
vectors = np.zeros((len(sentences), len(LEXICON)))
for row, sentence in enumerate(sentences):
for word in re.findall(r"\w+", sentence.casefold()):
feature = token_to_feature.get(word)
if feature is not None:
vectors[row, feature] = 1.0
if not keep_negation:
vectors[:, -1] = 0.0
return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
def sentence(animal_id, place_id, language_id, *, negated=False):
animal = ANIMALS[animal_id][language_id]
place = PLACES[place_id][language_id]
verbs = ("does not sleep in", "ne dort pas dans", "schläft nicht in")
if not negated:
verbs = ("sleeps in", "dort dans", "schläft in")
return f"{animal} {verbs[language_id]} {place}."The encoder produces a vector with one coordinate per animal, place, and negation. Every fixture sentence names one animal and one place, so its vector has nonzero norm even if we hide negation. In a negated sentence, removing the negation bit before normalization raises the two retained entries from to . The lexicon makes the encoder inputs easy to inspect. Free text would need proper tokenization, handling for unknown words, and a learned encoder or a much broader feature model.
Cross-lingual sentence similarity
Take translations of one proposition and translations of a second, with different animals and locations. Because the vectors have unit norm, their dot product is cosine similarity. The matrix includes both matching and nonmatching pairs, so we can see whether high similarity picks out the translations.
PythonIn [6]Expand
demo_examples = [("A", sentence(0, 0, i)) for i in range(len(LANGUAGES))] + [
("B", sentence(1, 1, i)) for i in range(len(LANGUAGES))
]
demo_vectors = encode([text for _, text in demo_examples])
demo_sim = demo_vectors @ demo_vectors.T
# Perturb the displayed score cells and clip them to the color scale.
# This noise is applied to the scores; the encoder vectors are unchanged.
_sim_rng = np.random.default_rng(SEED)
demo_sim = demo_sim + _sim_rng.normal(0.0, 0.04, size=demo_sim.shape)
demo_sim = np.clip(demo_sim, 0.0, 1.0)
np.fill_diagonal(demo_sim, 1.0)
languages_short = ["EN", "FR", "DE"]
demo_ticks = [
f"{languages_short[i % len(LANGUAGES)]} {scenario}"
for i, (scenario, _) in enumerate(demo_examples)
]ConsoleOut [7]Expand
EN A The cat sleeps in the kitchen. FR A Le chat dort dans la cuisine. DE A Die Katze schläft in der Küche. EN B The dog sleeps in the garage. FR B Le chien dort dans le garage. DE B Der Hund schläft in der Garage.
The A sentences all put the cat in the kitchen. The B sentences put the dog in the garage. Within a group, translations share both active coordinates. Across the two groups they share neither.
VisualizationOut [8]Expand

The two bright blocks distinguish propositions across language boundaries. Before adding noise, translations of different propositions share no features and have a cosine similarity of zero. In the seeded example, the perturbed scores across both dark blocks range from about -0.08 to 0.09 before clipping. The largest positive score is in the lower-left block because the two directions get independent noise draws. Clipping sends negative scores to zero and any matched scores above one to one. The classifier below uses the encoded vectors directly.
Information-theoretic alignment: InfoNCE
InfoNCE treats each row of the similarity matrix as a classification problem. The correct column is the matching translation. Subtracting the row maximum keeps the exponentials bounded and gives the same log-softmax as the original logits.
PythonIn [9]Expand
def info_nce(anchor, target, temperature=0.07):
"""Row-wise InfoNCE with matched pairs on the diagonal."""
logits = anchor @ target.T / temperature
shifted = logits - logits.max(axis=1, keepdims=True)
log_normalizer = np.log(np.exp(shifted).sum(axis=1))
return float(np.mean(log_normalizer - shifted.diagonal()))We split by animal and place combination, holding back one combination per animal for evaluation. Each animal and each place still occurs individually in training. For InfoNCE, encode one English and one French translation of each held-out proposition, in matching row order. Rolling the French rows by one position makes every positive label point to the wrong proposition while leaving the candidate set fixed.
PythonIn [10]Expand
all_scenarios = list(product(range(len(ANIMALS)), range(len(PLACES))))
train_scenarios = [
(animal, place) for animal, place in all_scenarios if animal != place
]
test_scenarios = [
(animal, place) for animal, place in all_scenarios if animal == place
]
en_parallel = [sentence(animal, place, 0) for animal, place in test_scenarios]
fr_parallel = [sentence(animal, place, 1) for animal, place in test_scenarios]
en_parallel_emb = encode(en_parallel)
fr_parallel_emb = encode(fr_parallel)
aligned_loss = info_nce(en_parallel_emb, fr_parallel_emb)
broken_loss = info_nce(en_parallel_emb, np.roll(fr_parallel_emb, 1, axis=0))ConsoleOut [11]Expand
Parallel pairs: 4 InfoNCE on matched pairs: 0.000002 InfoNCE after rotating: 14.286 Difference: 14.286 nats
Each row of the noiseless fixture contains one similarity of 1 and three similarities of 0. At temperature , the matched loss per row is . Rotating the French rows moves the similarity of 1 off the diagonal, so the designated positive has a logit of zero and the loss becomes . At , the two losses are about and nats.
Temperature controls how sharply the loss separates matched translations from the rest of the batch. For the sweep we add a fixed noise draw to both sets of embeddings, renormalize, and recompute the matched and rotated losses at each temperature.
PythonIn [12]Expand
temperature_values = np.array([0.02, 0.04, 0.07, 0.1, 0.2, 0.5, 1.0])
_noise_rng = np.random.default_rng(SEED)
en_parallel_emb = en_parallel_emb + _noise_rng.normal(
0.0, 0.05, size=en_parallel_emb.shape
)
fr_parallel_emb = fr_parallel_emb + _noise_rng.normal(
0.0, 0.05, size=fr_parallel_emb.shape
)
en_parallel_emb = en_parallel_emb / np.linalg.norm(
en_parallel_emb, axis=1, keepdims=True
)
fr_parallel_emb = fr_parallel_emb / np.linalg.norm(
fr_parallel_emb, axis=1, keepdims=True
)
matched_temperature_losses = np.array(
[
info_nce(en_parallel_emb, fr_parallel_emb, temperature=temperature)
for temperature in temperature_values
]
)
rotated_temperature_losses = np.array(
[
info_nce(
en_parallel_emb,
np.roll(fr_parallel_emb, 1, axis=0),
temperature=temperature,
)
for temperature in temperature_values
]
)VisualizationOut [13]Expand

The fixed noisy sweep retains lower loss for matched rows at each plotted temperature. At low temperatures the penalty grows sharply when rotation puts the largest similarity in a column that the loss treats as a distractor.
Zero-shot NLI transfer
For each premise, construct one hypothesis of each class. Repeat the premise for entailment, negate it for contradiction, and swap in another location for neutral. For neutral, assume the original sentence leaves open whether the animal also sleeps elsewhere. The 12 training scenarios give 36 English training pairs. The four held-out scenarios give 12 test pairs per language, with the same labels and class counts in English, French, and German.
PythonIn [14]Expand
def make_nli_pairs(scenarios, language_id):
pairs = []
for animal, place in scenarios:
premise = sentence(animal, place, language_id)
negated = sentence(animal, place, language_id, negated=True)
other_place = (place + 1) % len(PLACES)
if other_place == animal:
# Keep held-out propositions out of training hypotheses too.
other_place = (other_place + 1) % len(PLACES)
alternative = sentence(animal, other_place, language_id)
pairs.extend(
[
(premise, premise, "entailment"),
(premise, negated, "contradiction"),
(premise, alternative, "neutral"),
]
)
return pairs
def encode_nli_pairs(pairs, *, keep_negation=True, noise_std=0.0, rng=None):
premises, hypotheses, labels = zip(*pairs)
p = encode(premises, keep_negation=keep_negation)
h = encode(hypotheses, keep_negation=keep_negation)
if noise_std > 0.0 and rng is not None:
# Simulate imperfect cross-lingual alignment for non-source languages.
p = p + rng.normal(0.0, noise_std, size=p.shape)
h = h + rng.normal(0.0, noise_std, size=h.shape)
features = np.concatenate([p, h, np.abs(p - h)], axis=1)
return features, np.array(labels)Fit the classifier on English rows. Evaluate the English, French, and German versions of the held-out scenarios. Then repeat the French evaluation after discarding the negation coordinate before normalization. The affirmative and negated hypotheses become identical before the French noise is applied. Normalizing the masked vector also rescales the coordinates it retains. The masked and unmasked French evaluations use the same noise draw.
PythonIn [15]Expand
X_train, y_train = encode_nli_pairs(make_nli_pairs(train_scenarios, 0))
clf = LogisticRegression(max_iter=1000, C=1.0)
clf.fit(X_train, y_train)
test_pairs = [make_nli_pairs(test_scenarios, i) for i in range(len(LANGUAGES))]
language_noise = {0: 0.0, 1: 0.35, 2: 0.55}
test_data = [
encode_nli_pairs(
pairs,
noise_std=language_noise[i],
rng=np.random.default_rng(SEED + i),
)
for i, pairs in enumerate(test_pairs)
]
accuracies = [
accuracy_score(labels, clf.predict(features))
for features, labels in test_data
]
X_fr_masked, y_fr = encode_nli_pairs(
test_pairs[1],
keep_negation=False,
noise_std=language_noise[1],
rng=np.random.default_rng(SEED + 1),
)
fr_masked_acc = accuracy_score(y_fr, clf.predict(X_fr_masked))
chance = 1 / len(clf.classes_)
accuracy_labels = [*LANGUAGES, "French\n(negation masked)"]
accuracy_values = [*accuracies, fr_masked_acc]ConsoleOut [16]Expand
Training feature matrix: (36, 27) English 12 held-out pairs, accuracy 1.000 French 12 held-out pairs, accuracy 0.583 German 12 held-out pairs, accuracy 0.250 French accuracy with negation masked: 0.417
Without added noise, translations of a test example give identical features and predictions. The reported run adds Gaussian noise to French and German embeddings. The model gets 12 of 12 English pairs, 7 of 12 French pairs, and 3 of 12 German pairs right. When negation is masked in French, the affirmative and negated hypotheses have identical features before noise. After noise is added, the model assigns the same prediction to the matching entailment and contradiction in three of the four scenarios. The location feature is still present. With the same noise in the two French conditions, masking negation lowers accuracy from 7 of 12 to 5 of 12.
The aggregate drop tells us how many fewer examples the classifier gets right. To find which decisions changed, compare correctness on the same French test rows before and after masking. Reuse the fitted classifier and group the four possible transitions by the gold natural language inference label.
PythonIn [17]Expand
french_inputs, french_gold = test_data[1]
assert np.array_equal(french_gold, y_fr)
before_correct = clf.predict(french_inputs) == french_gold
after_correct = clf.predict(X_fr_masked) == french_gold
print(
f"{'Gold label':<15} {'Right both':>10} {'Right to wrong':>14}"
f" {'Wrong to right':>14} {'Wrong both':>10}"
)
for gold_label in clf.classes_:
in_class = french_gold == gold_label
right_both = np.count_nonzero(in_class & before_correct & after_correct)
lost = np.count_nonzero(in_class & before_correct & ~after_correct)
gained = np.count_nonzero(in_class & ~before_correct & after_correct)
wrong_both = np.count_nonzero(in_class & ~before_correct & ~after_correct)
print(
f"{gold_label:<15} {right_both:>10} {lost:>14} {gained:>14} {wrong_both:>10}"
)ConsoleOut [17]Expand
Gold label Right both Right to wrong Wrong to right Wrong both contradiction 1 2 0 1 entailment 0 0 0 4 neutral 4 0 0 0
Count the right-to-wrong and wrong-to-right columns to explain the change in accuracy. Of the four French contradiction pairs, two go from right to wrong and none go from wrong to right. All four neutral pairs stay correct, and all four entailment pairs stay wrong. The two lost decisions account for the drop from 7 out of 12 to 5 out of 12. This measures the effect of masking and renormalizing the features for these paired inputs.
The absolute accuracies are useful, but the transfer gap is the diagnostic quantity. The same English-trained classifier and the same held-out examples produce the gaps below. The gaps are about 0.42 for French, 0.75 for German, and 0.58 for masked French.
PythonIn [18]Expand
gap_labels = [*LANGUAGES[1:], "French masked"]
gap_values = [accuracies[0] - accuracies[i] for i in range(1, len(accuracies))]
gap_values.append(accuracies[0] - fr_masked_acc)
gap_values = [g for g in gap_values]VisualizationOut [19]Expand

VisualizationOut [20]Expand

This paired test measures the effect of masking negation before normalization. The mask also rescales the retained entries of a negated sentence, which changes the hypothesis block and can change the absolute-difference block. With the same French examples and noise draw, the full intervention lowers accuracy from about 0.58 to 0.42. In a benchmark experiment, alignment would come from a learned encoder, and the size of the difference would depend on the model and test set.
A minimal bottleneck adapter
A bottleneck adapter projects each token's hidden state down, applies a nonlinearity, and projects back to the original width. A residual adds the result to the input. We use one adapter per layer for the parameter estimate and keep the example separate from the classifier so we can inspect the module without training a transformer.
PythonIn [21]Expand
import torch
import torch.nn as nn
class BottleneckAdapter(nn.Module):
"""Add a learned bottleneck transformation to the input."""
def __init__(self, hidden_size=768, bottleneck=64):
super().__init__()
self.down = nn.Linear(hidden_size, bottleneck)
self.up = nn.Linear(bottleneck, hidden_size)
self.act = nn.GELU()
# A small up-projection keeps the initial residual update small.
nn.init.normal_(self.up.weight, std=1e-2)
nn.init.zeros_(self.up.bias)
def forward(self, x):
return x + self.up(self.act(self.down(x)))PythonIn [22]Expand
hidden_size = 768
bottleneck = 64
n_layers = 12
adapter = BottleneckAdapter(hidden_size=hidden_size, bottleneck=bottleneck)
hidden = torch.randn(4, 12, hidden_size)
with torch.inference_mode():
out = adapter(hidden)
per_adapter = sum(p.numel() for p in adapter.parameters())
budget = per_adapter * n_layers
mean_perturbation = (out - hidden).abs().mean().item()ConsoleOut [23]Expand
Adapter parameters: 99,136 12-layer adapter budget: 1,189,632 Input shape: (4, 12, 768) Output shape: (4, 12, 768) Mean absolute update: 0.02212
Both projections act on the last dimension, preserving the batch and token dimensions. Each projection contributes weights. Their biases contribute another parameters in total. The initial update is measured on the sampled batch. This module illustrates the residual bottleneck operation.
At hidden width , one adapter has parameters. Each extra bottleneck unit adds 1,537 parameters. Twelve layers with one adapter each use twelve times that count. The parameter savings relative to the block matrix weights get smaller as the bottleneck grows.
PythonIn [24]Expand
bottleneck_widths = np.array([16, 32, 64, 128, 256])
adapter_parameter_counts = (
2 * hidden_size * bottleneck_widths + bottleneck_widths + hidden_size
)
adapter_layer_budgets = adapter_parameter_counts * n_layers
# Matrix weights only, with four attention projections and an FFN of width 4d.
attention_weights = 4 * hidden_size**2
ffn_width = 4 * hidden_size
ffn_weights = 2 * hidden_size * ffn_width
base_block_weight_budget = (attention_weights + ffn_weights) * n_layersVisualizationOut [25]Expand

Key Parameters
- InfoNCE temperature scales every logit before the softmax. Lower temperatures sharpen probabilities when scores differ. They can also reduce the gradient when the positive already dominates. Inspect the ranking and the loss together.
- Logistic regression
Cis the inverse regularization strength. Hold it fixed in this comparison. Using French development labels to choose it changes the target-supervision protocol and should be reported. - Hidden width and bottleneck width determine the projection shapes. Larger bottleneck widths increase the number of trainable weights at fixed hidden width.
- Adapter placement determines how many copies of the module to budget for. The example assumes one module in each of 12 layers, giving a twelve-layer budget that is exactly twelve times a single adapter's parameter count.
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!