Cross-Lingual Transfer and Alignment › Building It: Code Implementation

Michael BrenndoerferNovember 26, 202616 min read
Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 186Cross-Lingual Transfer and Alignment › Building It: Code Implementation
Reading section 8 of 11 · Building It: Code Implementation · 16 minSection 8 of 11 · 16 min

Section 8 of 11 · 16 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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]
CollapseExpand
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 1/31/\sqrt{3} to 1/21/\sqrt{2}. 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Six-by-six heatmap with two bright translation groups. Cellwise noise yields some bright cells clipped at one and some dark cross-group cells clipped at zero.
Perturbed cosine scores for English, French, and German versions of two propositions. Translations form two bright blocks. Cellwise noise and clipping to the range from zero to one create small variations within each block.

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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 τ\tau, the matched loss per row is log⁡(1+3e−1/τ)\log(1+3e^{-1/\tau}). 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 log⁡(3+e1/τ)\log(3+e^{1/\tau}). At τ=0.07\tau=0.07, the two losses are about 1.9×10−61.9\times10^{-6} and 14.2914.29 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]
CollapseExpand
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]
CollapseExpand
The matched curve stays below the rotated control at every temperature. The curves are farthest apart at the low-temperature end.
InfoNCE loss for four generated parallel pairs after adding fixed noise and renormalizing their vectors. The matched loss stays below the rotated control from temperature 0.02 to 1.0.

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Bars measure accuracy drops from English. German has the largest drop at 0.75, followed by masked French at 0.58 and French at 0.42.
Accuracy drops from English of about 0.42 for French, 0.75 for German, and 0.58 for masked French. Relative to unmasked French, the mask widens the gap by about 0.17.
VisualizationOut [20]
CollapseExpand
English scores 1.00, French 0.58, German 0.25, and masked French 0.42. German falls below the uniform-guessing line at 0.33.
On the generated test pairs, accuracy is 1.00 for English, 0.58 for French, 0.25 for German, and 0.42 for masked French. The dashed line marks uniform guessing at about 0.33.

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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 ddbd d_b weights. Their biases contribute another db+dd_b+d parameters in total. The initial update is measured on the sampled batch. This module illustrates the residual bottleneck operation.

At hidden width d=768d=768, one adapter has 2ddb+(db+d)=1,537db+7682dd_b+(d_b+d)=1{,}537d_b+768 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]
CollapseExpand
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_layers
VisualizationOut [25]
CollapseExpand
On a logarithmic parameter axis, both adapter budgets rise with width. The budget for twelve adapters is twelve times the budget for one. The dashed 84.9-million frozen-block matrix baseline sits above both curves.
Both axes are logarithmic. Across the tested widths, one adapter grows from 25,360 to 394,240 parameters. The twelve-layer budget is twelve times the single-adapter count at each width. The dashed line counts 84.9 million attention and feed-forward matrix weights in twelve width-768 blocks, excluding biases, normalization, embeddings, and heads.

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 C is 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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy