MNLP-L06: Contextual Embeddings

In short

A static embedding gives train one vector whether it is a vehicle, a verb or a train of thought. A contextual model gives every occurrence its own vector. BERT made this standard: a Transformer encoder pre-trained to fill in masked words, then fine-tuned on a real task.

mBERT is BERT trained on 104 Wikipedias with one shared vocabulary and nothing cross-lingual in its loss, yet a model fine-tuned on English works in German or Hindi (zero-shot cross-lingual transfer). Shared wordpieces help but are not the main cause; similar structure and model depth matter more, and no single factor explains it. When one input mixes two languages, mBERT and XLM-R both do much worse.

Exam statements: the masking rule, what mBERT’s training lacks, the sampling exponent, and what does and does not drive transfer. Exact figures are on the cheat sheet.

One vector per word is not enough

Static embeddings. So far a word representation has been a word embedding: one row per word type in a table (see MNLP-L05 - Static Embeddings). You can train it directly, as Word2Vec does with Negative Sampling over a small window, or get it as a by-product: train a deep network on a real task (a text classifier, a translation system) and keep its input embedding layer. Either way the result is static: the same vector in every sentence.

Three trains

  • He took the train to Munich. (a vehicle)
  • She had to train for her next match. (a verb: to practise)
  • He interrupted her train of thought. (a sequence)

where is the embedding lookup. Three senses, two parts of speech, one vector.

In the by-product route the deep network did read the whole sentence, and its hidden layers computed exactly the context that tells the three trains apart. Keeping only the input layer throws that away.

Contextual embeddings keep it. In a deep network (stacked RNN layers, say, or a Transformer), look at the column of hidden states above one word. At the bottom is the static vector for train; each layer up mixes in more of the sentence. Any of these states can serve as “the embedding of train in this sentence”, and they differ from sentence to sentence.

Which one is useful depends on the training. With an output at every position (tagging, next-word prediction), each top-layer state is pushed to stay about its own word. With all top states combined (pooled) into one vector for a sentence classifier, the top layer is pushed to be about the sentence, and the word’s own contribution can wash out.

The contextual representation trade-off

Strike the right balance between

  • integrating sufficient context to distinguish different occurrences of the same word, and
  • not capturing too much context, where the word’s own contribution to the representation becomes unclear.

Three ways to manage it:

  1. Choose the right layer(s). Lower layers are closer to the word, higher ones closer to the sentence. Pick or combine layers to suit the task.
  2. Choose the right training task(s). The objective decides what the hidden states encode (per-position outputs against one pooled output, as above).
  3. Tighten the connections between layers, for example with residual connections: , where is the state at layer and the layer’s transformation. The word’s own information is carried upward unchanged next to whatever context the layer adds. (The formula is the standard definition, added here.)

Pre-train on a big generic task, fine-tune on the real one

Contextual models are used in two phases: a big network first learns general language from a task with practically unlimited data, then a small task head is put on top and the combination is trained on the real task. In symbols: is the contextual model (C for contextual) with parameters , is the task head with its own parameters , and is the two combined, whose parameters are the union of both sets.

Pre-training and fine-tuning

Pre-training. Take a model that can model wide contexts (LSTM, Transformer, CNN). Train it on a general task for which (very) large amounts of data exist, such as word prediction in language modelling, updating .

Fine-tuning. Choose the real task of interest (question answering, part-of-speech tagging) and a model suited to it. Combine the two into and train it on , updating and maybe also .

“Maybe also ” is the important switch. If only is trained, the pre-trained model is a frozen feature extractor. If is updated too, that is full fine-tuning, BERT’s default. Partial versions, where some lower layers stay frozen, come back in the transfer experiments below.

Which network plays ? Most current contextual models are built from Transformer layers (self-attention), in three shapes:

  • Encoder-decoder: the encoder builds a representation of the input, the decoder generates the output the task needs. This is the original Transformer (Vaswani et al. 2017), used for translation, summarisation and question answering.
  • Encoder-only: predicts its own input after it has been scrambled by some noise function; in its purest form an auto-encoder. BERT is the prominent example.
  • Decoder-only: a classical next-word-prediction language model. Encoder-decoder tasks can be framed in it by putting input and output into one sequence. All current LLMs are decoder-only.

BERT: an encoder trained to fill in blanks

BERT (Bidirectional Encoder Representations from Transformers, Devlin et al. 2019) is the encoder half of the Transformer. Every position attends to every other position, to its left and to its right: that is what “bidirectional” means, unlike a left-to-right RNN or a decoder.

It is pre-trained on missing-word prediction, which is self-supervised: the labels are the words themselves, so any amount of raw text can be used, relevant to a downstream task or not. It is then fine-tuned on the actual task, which is supervised and works even with little task data.

There are two pre-training tasks: masked language modelling (MLM: predict hidden tokens) and next sentence prediction (NSP: does segment B follow segment A?).

The input: three embeddings added up

The input is [CLS], the tokens of segment A, [SEP], the tokens of segment B, [SEP]. Each position’s input vector is the sum of three learned embeddings:

where is the embedding of the WordPiece token at position , is or depending on which segment the token belongs to, and is the position embedding.

[CLS] my dog is cute [SEP] he likes play ##ing [SEP]

Everything up to and including the first [SEP] gets , the rest . WordPiece splits playing into play ##ing; ## marks a word-internal piece. If dog is selected for masking, its token embedding becomes .

Masked language modelling: 15%, then 80/10/10

BERT masking rule

Tokens are selected for masking with probability 0.15. A selected token is replaced

  • 80% of the time by [MASK],
  • 10% of the time by a random word,
  • 10% of the time by the original word (left unchanged).

The loss is computed only for the selected positions, regardless of whether the input there shows [MASK], a random word or the original word.

Why not always [MASK]? Because [MASK] never occurs at fine-tuning time. A model that only ever predicted at [MASK] positions could learn to build good representations only there. With random and unchanged tokens mixed in, it cannot tell which positions will be scored, so it has to represent every token well. (This rationale is Devlin et al.’s.)

So the loss covers only the selected 15%, and within those it covers the random and unchanged positions as well as the [MASK] ones. In BERT the masks are drawn once, during pre-processing, and reused in every epoch (static masking; XLM-R below changes this).

Algorithm: BERT MLM masking and loss
──────────────────────────────────────────
Input: tokens x_1..x_n, vocabulary V,
       p_mask = 0.15
S ← ∅;  x̃ ← copy of x
// S = positions that will be scored
for i = 1..n:
    if x_i is [CLS] or [SEP]: continue
    with probability p_mask:
        S ← S ∪ {i}
        r ← uniform(0,1)
        if r < 0.8:   x̃_i ← [MASK]
        elif r < 0.9: x̃_i ← random token
        else:         x̃_i ← x_i
        // unchanged, but still scored
T_1..T_n ← BERT(x̃)
// W = output projection onto V
loss ← − Σ_{i∈S} log softmax(W T_i)[x_i]
// predict the ORIGINAL token, only at S

[CLS] and next sentence prediction

The class embedding [CLS]

  • not tied to a specific word, and never masked;
  • not meant to learn a context-specific word representation;
  • captures a general representation of the entire input sequence;
  • its loss is computed with respect to a classification task.

In pre-training that task is NSP. Each input holds two segments A and B. 50% of the time B really follows A in the document (IsNext); 50% of the time B is a random segment from the corpus (NotNext). A classifier on , the final-layer output at [CLS], predicts the label. In practice A and B are stretches of running text, much longer than single sentences.

BERT was pre-trained on BookCorpus plus English Wikipedia, in two sizes, base and large. BERT-base has 12 attention heads and BERT-large 16 (Devlin et al.), although the lecture’s table gives 16 for both, so a statement taken from that table will likely be keyed with 16 (other dimensions on the cheat sheet).

Fine-tuning, entailment and SQuAD spans

To fine-tune:

  1. add a small task-specific model, randomly initialised;
  2. for tasks that need word representations (tagging, span extraction), connect it to the top-layer token outputs ;
  3. for classification tasks (sentiment, entailment), connect it to the [CLS] output ;
  4. train on the task data, with or without updating BERT’s own parameters.

Fine-tuning is short: small batches (16 or 32 sequences) and 2 to 4 epochs, because the encoder already starts out good and long training on little data would overfit. (In current terms, supervised fine-tuning of an encoder.)

Natural language inference (NLI), or entailment

Given a premise and a hypothesis, the premise can entail the hypothesis, contradict it, or be in no relationship (neutral) to it. A 3-way classification task.

A soccer game with multiple males playing entails Some men are playing a sport. In BERT the premise is segment A, the hypothesis segment B, and the label is predicted from . SNLI and MultiNLI are large English NLI datasets. For NER (named entity recognition, tagging names of people, places and organisations) the input is a single sentence, and the head sits on the .

SQuAD (a reading-comprehension benchmark) gives a question and a paragraph; the answer is a span of the paragraph, given by its start and end position. Nothing is generated: At what pressure is water heated? is answered by pointing at high pressure in the paragraph.

Span prediction

Fine-tuning learns one start vector and one end vector , both in ; these are the only new parameters. Each paragraph position is scored by an inner product, normalised with a softmax: The predicted span maximises subject to .

where is BERT’s final-layer output at token , the hidden size, and rules out spans that end before they start.

Subwords meet masking

BERT works on subword pieces, which matters twice: for how words are split, and for which pieces get masked.

WordPiece

BERT and mBERT split words with WordPiece (Schuster and Nakajima 2012). It is very similar to BPE and predates it as an NLP segmentation method. Like BPE, and unlike Unigram LM, it works bottom-up: start from characters and merge pairs. Every non-initial character starts with a ## prefix (hug is h ##u ##g), and merged non-initial pieces keep it. See MNLP-L04 - Subword Segmentation for BPE and Unigram LM, and Tokenization.

The difference from BPE is the merge criterion. BPE merges the most frequent pair. WordPiece merges the pair whose parts occur together most often relative to how often they occur at all.

WordPiece pair score

where is how often symbol is immediately followed by , and , are the symbols’ own frequencies. A pair scores high when its parts occur together more often than their frequencies would suggest. Training merges the highest-scoring pair, adds it to the vocabulary, and repeats until the vocabulary has the target size.

One training step

Word counts: hug 10, pug 5, pun 12, bun 4, hugs 5, so the words start as h ##u ##g, p ##u ##g, p ##u ##n, b ##u ##n, h ##u ##g ##s. Symbol counts: ##u 36, ##g 20, p 17, ##n 16, h 15, ##s 5, b 4.

The most frequent pair, ##u ##g (20), scores ; every pair containing the very common ##u scores the same . ##g ##s occurs only 5 times but scores , because ##s only ever follows ##g. WordPiece merges ##g ##s; BPE would merge ##u ##g.

At inference WordPiece does not replay the merges the way BPE does. It runs greedy longest match against the final vocabulary, which can give a different segmentation. Its unknown handling is also the harshest: a word containing a character it cannot match becomes [UNK] as a whole, where BPE and Unigram LM fall back to characters or bytes.

Algorithm: WordPiece inference
(greedy longest match, per word)
──────────────────────────────────────────
Input: word w, vocabulary V
pieces ← [];  start ← 1
while start ≤ |w|:
    end ← |w|;  found ← none
    // try the LONGEST candidate first
    while end ≥ start:
        cand ← w[start..end]
        // non-initial pieces carry ##
        if start > 1: cand ← "##" + cand
        if cand ∈ V: found ← cand; break
        end ← end − 1
    // the WHOLE word becomes [UNK]
    if found = none: return [UNK]
    append found to pieces
    start ← end + 1
return pieces
BPEWordPieceUnigram LM
Directionbottom-up mergesbottom-up mergestop-down pruning
Criterionpair frequencycount ratiocorpus likelihood loss
Inferencereplay mergesgreedy longest matchViterbi or sampling
Unknown wordcharacter/byte fallbackwhole word [UNK]character fallback
Typical modelsGPT, RoBERTa, XLMBERT, mBERTT5, XLM-R

Easy pieces, and whole-word masking

Some words are harder to predict than others: in The developers [MASK] the property, guessing the verb is hard, while guessing the would be easy. Subword pieces differ in the same way, in any subword scheme. This example uses BPE’s notation, where @@ marks a piece that continues into the next one (WordPiece would write view ##ed):

  • The deve@@ lop@@ ers [MASK] ed the proper@@ ty . hides the stem of viewed: still hard, which verb?
  • The deve@@ lop@@ ers view@@ [MASK] the proper@@ ty . hides only the suffix: given view@@ and a past-tense context, ed is nearly certain.

Pieces that mostly carry morphology (tense, number, case) are easier to predict than pieces that carry the root or stem. So under per-token random masking, many masked positions are suffixes or word-internal pieces the model can complete from the visible rest of the word. It earns loss signal there without learning much.

Whole-word masking

Instead of masking tokens independently, always mask all subword tokens that belong to the same word. The masking rate stays unchanged (still about 15% of tokens).

The deve@@ lop@@ ers view@@ ed the proper@@ ty . becomes The deve@@ lop@@ ers [MASK] [MASK] the proper@@ ty .

The effect: with the same model, data and masking rate, BERT-Large improves on SQuAD and on MultiNLI, in both its cased and lowercased (uncased) versions. The only change is that the model can no longer cheat by completing a word from its own visible pieces.

mBERT: BERT on 104 Wikipedias, and nothing more

mBERT (multilingual BERT)

  • Released on GitHub in 2018, with no paper.
  • Exactly the same architecture and loss as BERT (MLM + NSP): no cross-lingual loss, nothing language-specific. That means no parallel data (at least not intentionally), no language-ID embedding, no language-specific parameters such as adapters, and no alignment loss rewarding translation equivalents for being close.
  • Trained on 104 languages: the concatenated Wikipedias.
  • NSP pairs are always within the same language, and there is no mixing of languages inside a sequence (a batch can contain several languages).
  • One shared subword vocabulary for all languages (WordPiece; BPE or Unigram LM would work similarly well).

Nothing in the objective says that Hund and dog mean the same thing. The languages share only the parameters and the subword vocabulary, so every cross-lingual ability mBERT shows has to come from those two. Most of what follows asks which.

Sampling languages with a smoothing exponent

Wikipedia sizes vary enormously, and the joined corpus is extremely skewed: English alone is larger than dozens of smaller languages combined. Sampling training data in proportion to size would let a few big languages dominate, so mBERT samples languages from a smoothed distribution:

Weighted language sampling

where is the probability of drawing training data from language , the size of language ‘s data (in characters, tokens, etc.), the exponent that sets how strongly raw sizes count, and the sum over all languages makes the probabilities add up to 1.

  • : sampling in proportion to raw size; English and a few other large Wikipedias dominate training.
  • : every , so sampling is uniform; tiny Wikipedias are oversampled so much that the model would mostly memorise them.
  • (mBERT’s choice): up-weights low-resource languages and down-weights high-resource ones, a compromise.

Why it works: with is concave, so it shrinks large values more than small ones. The size ratio between two languages, , becomes . Every language keeps its rank; the gaps get smaller.

English 1000, Swahili 10

  • : , .
  • : and , so and . Swahili gets about 3.9 times its raw share; English still gets 96%. The 100:1 ratio has become :1.
  • : . Each unit of Swahili text is now drawn 100 times as often as each unit of English ( against ): the memorisation problem.

The same knob is often written as a temperature , with (MNLP-L07 - Crosslingual NLP uses this form). is proportional sampling, and raising the temperature flattens the distribution toward uniform. Lowering and raising are the same move.

One shared vocabulary, and who pays for it

mBERT has one vocabulary of about 120k entries for all 104 languages, against 30k for English BERT. The architecture is identical, so mBERT’s larger parameter count comes entirely from the bigger embedding matrix.

  • Chinese characters, Japanese kanji and Korean hanja are split into single characters before WordPiece is applied.
  • The sampling smoothing also applies to the subword frequencies used to build the vocabulary, so small languages get more entries than their raw size would give them.
  • Even so, the shared vocabulary still favours high-resource languages and Latin script, and low-resource and morphologically rich languages are split into many more pieces per word (higher fertility, see fertility in L04).
  • An uncased mBERT lowercases and strips accents, which damages languages that depend on diacritics. (Examples added here: Spanish papá “dad” collapses into papa “potato”, and Vietnamese loses its tone marks.)

Zero-shot cross-lingual transfer: does mBERT generalise across languages?

Zero-shot cross-lingual transfer

Fine-tune on task data in language A only, then evaluate on the same task in language B, with no task data in B at all. In a table of fine-tuning language against evaluation language, the diagonal is ordinary in-language performance and every off-diagonal cell is zero-shot.

Pires et al. (2019) ran this on NER and POS tagging across 16 languages. Performance off the diagonal is decent: in NER, a model fine-tuned on English tags Dutch entities reasonably well without a single Dutch training example. Zero-shot stays below in-language performance. POS scores off the diagonal are higher than NER’s, though the two use different measures (accuracy against F1). In POS, closely related languages transfer best (Spanish and Italian). Transfer is also asymmetric: in NER, English to Dutch is clearly better than Dutch to English. So mBERT generalises beyond its fine-tuning language. The question is how.

Different scripts: transfer survives

If transfer came from shared wordpieces, languages written in different scripts should barely transfer, since they share almost no pieces. They do transfer.

Hindi and Urdu are essentially one spoken language written in two unrelated scripts (Devanagari and Perso-Arabic), which makes them the cleanest test of “same grammar, no shared script” (background added here). POS tagging transfers well between them in both directions. English to Bulgarian (Latin to Cyrillic) also transfers well. Pairs involving Japanese drop sharply, possibly because of larger typological differences, as Pires et al. suggest (Japanese puts the verb last and uses postpositions).

Vocabulary overlap: mBERT is flat, English BERT is not

Pires et al. then measured overlap directly, using only the wordpieces inside labelled named entities:

Entity wordpiece overlap (Jaccard similarity)

where is the set of wordpieces in named entities of the fine-tuning data () in language , and the same for the evaluation data () in language . It is 0 for disjoint sets and 1 for identical ones.

Plotting zero-shot NER F1 against this overlap, one point per language pair, gives two different pictures:

  • English BERT (monolingual, applied to other languages) scores near zero at low overlap and rises roughly linearly with it. It can only transfer through strings that literally occur in both languages: names, loanwords.
  • mBERT is roughly flat: decent F1 across the whole range, already at overlap near zero.

So whatever mBERT transfers is not surface string matching. It has a representation shared across languages below the level of the wordpieces.

Typology: similar structure transfers better

WALS, the World Atlas of Language Structures, is a database of structural features of languages (word order, tone, number of cases and so on), compiled from reference grammars. Coverage is wide but sparse: no language has every feature filled in. In NLP each language becomes a vector of its feature values, so two languages’ structural similarity can be compared along dimensions such as word order or number of cases.

Pires et al. grouped languages by word order and averaged POS transfer:

  • Subject-verb-object order: from an SVO language, SVO targets are far better than SOV (verb-final) targets such as Japanese or Hindi. From an SOV language the two are almost equal.
  • Adjective-noun order: transfer is again better within the same order, with a much smaller effect.
  • Number of shared WALS features: zero-shot accuracy rises as two languages share more features, for both mBERT and English BERT, with mBERT far above English BERT throughout. Individual pairs vary a lot around the trend.

Translation retrieval: language-neutral in the middle

Do mBERT’s sentence representations line up across languages, and in which layer?

Translation retrieval with a mean difference vector (Pires et al.)

  • Take a sample of translation pairs (from WMT16, a machine-translation benchmark).
  • For each layer , represent a sentence by the average of its hidden states, excluding [CLS] and [SEP]: , .
  • Compute one average difference vector for the language pair:
  • “Translate” each English sentence by shifting it, , and find its nearest German neighbour by distance (Euclidean distance, not cosine similarity). It is a hit when that neighbour is the true translation.

For English-German, English-Russian and Urdu-Hindi the accuracy follows the same inverted U: low in layer 1, peaking in the middle-upper layers (6 to 8 of 12), then falling in the last layers. English-Russian (Latin against Cyrillic) starts lowest and catches up by the peak.

The reading: lower layers are close to the surface tokens, which differ between languages. Middle layers are the most language-neutral: a single constant shift maps one language onto the other. The top layers are shaped by predicting a word in this language, and become language-specific again. So accuracy does not keep rising up to the top layer: “choose the right layer”, measured.

Zero-shot mBERT against task-specific systems (Wu and Dredze)

Wu and Dredze (2019) tested zero-shot transfer from English fine-tuning on five tasks: document classification (MLDoc), NLI (on XNLI), NER, POS tagging and dependency parsing, over 39 languages in total.

MLDoc sorts news documents into four classes. Zero-shot, mBERT comes within a fraction of a point of the best system, which was trained with parallel text, without ever seeing a translation. Going zero-shot still costs a lot against in-language training, most of all for Japanese.

XNLI is a crowd-sourced English NLI test and dev set translated into 14 languages (15 in total), so a premise can be paired with its hypothesis in any of the 15 languages. On XNLI:

  • Translate-train beats zero-shot: machine-translating the English training set into each target language and fine-tuning on that (pseudo-supervision) gives mBERT a clearly better average than fine-tuning on English alone.
  • Zero-shot mBERT narrowly beats X-LSTM, an older LSTM system that was pre-trained with cross-lingual signal (bitext or a bilingual dictionary). It loses to the two stronger systems with cross-lingual signal: Artetxe and Schwenk (parallel data) and XLM with MLM+TLM.
  • It also loses to XLM trained with MLM alone, which, like mBERT, uses no parallel data. XLM (Lample and Conneau 2019, covered in MNLP-L07 - Crosslingual NLP) is a cross-lingual BERT-style model whose full version adds translation language modelling (TLM), an objective on parallel sentence pairs. Its MLM-only variant drops that. XLM-R, below, is a different and later model. One caveat on these comparisons: the X-LSTM and XLM results chose their model on the target-language dev set, which mBERT did not.
  • mBERT’s weakest languages are low-resource and distant ones: Swahili, Thai, Urdu, Hindi, Turkish.

NER: zero-shot mBERT beats a dedicated cross-lingual NER system (Xie et al.) by several points on average. Chinese collapses (a plausible reason, not given in the source: a different script and a very different typology).

POS: zero-shot mBERT does not match Kim et al.’s low-resource cross-lingual tagger, which also gets a few hundred target-language sentences (320). For POS, adding a little target-language data beats zero-shot mBERT on average.

Freezing layers during fine-tuning

Wu and Dredze then fine-tuned on English with every layer up to and including layer frozen, for = 0, 3, 6 or 9, where layer 0 is the embedding layer: so freezes only the embeddings. They compared these with fine-tuning all layers, and with “Feat”: mBERT not fine-tuned at all, only the task head trained (the feature-extractor setting).

  • Feat is below the best fine-tuned setting on average on every task, so fine-tuning is necessary. The loss is largest on MLDoc and smallest on POS.
  • Freezing the lowest layers helps or is neutral, compared with fine-tuning everything. The best level is layer 0 or 3 for NER, 3 for POS, and 6 for MLDoc and XNLI. Fine-tuning only on English would otherwise pull the lower layers toward English; frozen, they keep the multilingual representation from pre-training.
  • Freezing up to layer 9 hurts NER (most), POS and XNLI, but not MLDoc: for most tasks the upper layers need to adapt.

Vocabulary sharing: correlation, task by task

Finally, for each target language Wu and Dredze measured the share of its test wordpieces that also occur in the English training data, counted once per wordpiece type (type level) or weighted by frequency (token level). Correlating that share with zero-shot scores across languages:

  • NER: an almost perfect correlation. It is the most lexical task, and named entities are often copied verbatim across languages (though there are only five languages).
  • XNLI: no correlation at type level, and only a weak, non-significant one at token level. Sentence-level inference does not ride on shared wordpieces.
  • MLDoc, POS, parsing: in between. Low-overlap languages score lowest, with a wide spread.

Correlation is not cause: languages that share many wordpieces with English also tend to be structurally close to English. The next experiments separate the two.

Isolating the causes (K et al.)

K et al. (2020; K is the first author’s surname) trained their own bilingual BERT models (B-BERT) on English plus one other language, so they could switch individual factors off.

Removing all subword overlap: fake English

Fake English is English with every Unicode character shifted by a large constant, into a range no other language uses. Words, grammar, word order and frequencies stay identical; only the characters change, so the vocabulary it shares with the other language is exactly zero.

Train B-BERT on fake English plus Spanish, Hindi or Russian, fine-tune on (fake) English XNLI, test on the other language: removing all subword overlap costs little, at most about a point and a half. The cleanest case is a B-BERT trained on English and fake English, two copies of one language with disjoint alphabets: fine-tuned on fake English, it does almost as well on real English. Shared wordpieces are not what makes multilingual BERT multilingual.

Scrambling word order

If not vocabulary, perhaps structure. K et al. randomly permuted a fraction of the words during pre-training, with no permutation during fine-tuning. The more words permuted, the larger the drop. It is a significant drop, but transfer is not eliminated: even with every word permuted, accuracy stays well above chance. Of Spanish, Hindi and Russian, Hindi suffers most. (A possible reason, not from the source: Hindi is verb-final, the furthest of the three from English word order.)

Depth

Of the architecture factors K et al. varied, depth had the largest impact. Keeping the parameter count roughly constant, they went from 1 to 24 layers. In-language accuracy (on fake English) saturates quickly, by about 6 layers. Zero-shot accuracy (on Russian) keeps rising with depth. So the gap between the two shrinks: deeper networks learn more language-independent representations, and depth buys cross-lingual transfer more than in-language performance.

Two languages in one input

So far “cross-lingual” meant: fine-tune on English, test on monolingual Spanish or Russian inputs. What if the task itself is multilingual, with the premise in one language and the hypothesis in another?

K et al. tested B-BERT on XNLI with one side in fake English and the other in the target language. Both monolingual conditions work. Mixed pairs fall below both, for all three languages, and a fake-English hypothesis with a target-language premise does better than the reverse. Hindi has the lowest mixed scores, but its monolingual score is also the lowest, so this does not show that mixing hurts Hindi most: measured as a drop from each language’s own score, all three lose a similar amount.

This is the surprising result. In a truly language-neutral space, an English premise and a Spanish hypothesis would be as easy to compare as two English sentences. They are not: the models are good at doing the same task in another language, and poor at relating two languages inside one input.

Within a language, across languages (Rajaee and Monz)

Rajaee and Monz (2024) scaled this up: mBERT fine-tuned on English NLI (the zero-shot setting) and evaluated on XNLI for every combination of premise language and hypothesis language among the 15.

Within and across

  • Within for language : premise and hypothesis both in .
  • Across for language : the average over all pairs where one side is in and the other in a different language: where is the accuracy with premise language and hypothesis language , and .

(Formula reconstructed here; it reproduces the reported averages.)

Across is below within for every language, often by a wide margin, and English, the fine-tuning language, has the highest within score. Patterns in the full matrix:

  • For any hypothesis language, a premise in the same language is best.
  • An English hypothesis helps: a foreign premise with an English hypothesis does better on average than an English premise with a foreign hypothesis. For some premise languages (German, Urdu, Hindi, Swahili, Thai) an English hypothesis even beats a hypothesis in the premise’s own language.
  • A Swahili or Thai hypothesis does badly with any foreign premise. Swahili is barely above chance (33% for three balanced classes), and Thai is only a little better.
  • Related languages pair well: Russian with Bulgarian, Spanish with French, Hindi with Urdu.

The heuristics hypothesis

Hypothesis (Rajaee and Monz)

Transfer of heuristics can contribute to cross-lingual generalisation.

The idea builds on Rajaee et al. (2022), who counted word overlap between premise and hypothesis in SNLI. When every hypothesis word appears in the premise, the label is almost always entailment; as overlap falls, entailment becomes the minority. A model can learn the shortcut “high overlap means entailment”.

How this would explain the across drop is an interpretation, not an established result. Within any one language the shortcut still works, so it transfers from English to Spanish. When premise and hypothesis are in different languages, overlap is near zero by construction, so the shortcut says “not entailment” even for true entailments.

XLM-R: scaling mBERT up

The most prominent extension of mBERT is XLM-R (XLM-RoBERTa, Conneau et al. 2020), a RoBERTa-style extension of mBERT. All four of its changes come under that heading:

  • Drop NSP, MLM only: next sentence prediction contributes little and sometimes hurts.
  • Dynamic masking instead of static.
  • More training data: CC-100, filtered CommonCrawl web text in 100 languages, about two orders of magnitude more monolingual data than mBERT’s Wikipedia.
  • A larger shared vocabulary: 250k entries, double mBERT’s, built with Unigram LM (SentencePiece), giving better fertility (fewer pieces per word) at the cost of a bigger embedding matrix.

(Background, not from the lecture: RoBERTa is BERT retrained with a tuned recipe, which already dropped NSP, used dynamic masking, more data and a larger vocabulary. The CC-100 corpus and the Unigram LM vocabulary are specific to XLM-R.)

Static and dynamic masking

  • Static masking is applied at the data level, as part of pre-processing: each sequence is masked once, and the same masked copy is reused in every epoch.
  • Dynamic masking masks multiple iterations over the same input differently: a fresh mask each time the sequence is fed to the model.

With static masking, a token not selected during pre-processing is never a prediction target, however many epochs you run. Dynamic masking turns every pass into new training signal at no extra data cost.

mBERTXLM-R
ObjectiveMLM + NSPMLM only
Maskingstaticdynamic
DataWikipedia, 104 languagesCC-100, 100 languages
Vocabulary120k WordPiece250k Unigram LM
Cross-lingual signalnonenone

Better within, not uniformly better across

Rajaee and Monz ran the within/across evaluation for both models, on XNLI and on cross-lingual question answering (XSQuAD: SQuAD-style QA where the question and the context paragraph can be in different languages).

  • Within a language, XLM-R beats mBERT on both tasks, on average and in almost every language (English QA is a tie).
  • Across languages on XNLI, XLM-R also beats mBERT, and its within-across gap is a little smaller.
  • Across languages on QA, XLM-R is worse than mBERT on average, although it is clearly better within. Its within-across gap on QA is far larger than mBERT’s. Thai shows the split most clearly: XLM-R lifts Thai within-language QA enormously, while its across score barely moves.

mBERT degrades smoothly: an English question works with every context, a Thai question with almost none. XLM-R is “own language, or English question”: strong when question and context share a language or the question is English, collapsed almost everywhere else.

The conclusion: more data and a bigger vocabulary made each language better on its own, and did not make the model better at relating two languages inside one input.

What drives mBERT’s cross-lingual transfer?

Conclusions

  • Shared (sub)word vocabulary does play a role, but it is not the main cause of transfer (cross-script transfer, the flat overlap curve, fake English).
  • Structure (grammar, word order) matters. Randomly permuting words hurts performance significantly, but does not entirely eliminate transfer.
  • Model architecture matters. Deeper networks can learn more language-independent representations.
  • Bottom line: no single factor explains transfer (or the lack of it).

What is missing to improve transfer is left as an open question. One candidate is what mBERT’s training lacks: parallel data and an alignment loss that pulls translation equivalents together, typically a contrastive objective (a pointer added here; MNLP-L07 - Crosslingual NLP takes it up). The mixed-language results show why it would be needed.

What to be able to answer

  • Static against contextual embeddings; the context trade-off and its three remedies.
  • Feature extractor against full fine-tuning; the three Transformer families.
  • BERT: input sum, 15% and 80/10/10, which positions are scored, [CLS] and NSP, where heads attach, SQuAD spans.
  • WordPiece against BPE; why whole-word masking helps at the same rate.
  • mBERT: what its training has and lacks; for given or ; the vocabulary’s biases.
  • Zero-shot transfer: what scripts, entity overlap, typology, layers, freezing and the fake-English, permutation and depth experiments show.
  • Within against across; the heuristics hypothesis; XLM-R’s changes and where it beats mBERT.

Model answers are in the exam questions below.

Exam questions

Flashcards