Skip to content
ImagineWorld

Cross-Lingual and Multilingual Language Modeling

node_idnode-book_mastering-transformers_chapter-13-cross-lingual-and-multilingual-language-modeling
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleCross-Lingual and Multilingual Language Modeling
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — Cross-Lingual and Multilingual Language Modeling

Section titled “Chapter 13 — Cross-Lingual and Multilingual Language Modeling”

Up to this point, you have learned a lot about transformer-based architectures, from encoder-only models to decoder-only models and from efficient transformers to long-context transformers. You also learned about semantic text representation based on a Siamese network. However, we discussed all these models in terms of monolingual problems. We assumed that these models just understand a single language and are not capable of having a general understanding of text, regardless of the language itself. In fact, some of these models have multilingual variants: multilingual bidirectional encoder representations from transformers (mBERT), multilingual text-to-text transfer transformer (mT5), and multilingual bidirectional and auto-regressive transformer (mBART), to name but a few. On the other hand, some models are specifically designed for multilingual purposes and are trained with cross-lingual objectives. For example, cross-lingual language model (XLM) is such a method, and this will be described in detail in this chapter.

In this chapter, the concept of knowledge sharing between languages will be presented, and the impact of byte-pair encoding (BPE) on the tokenization part will also be covered in order to achieve better input. Cross-lingual sentence similarity using the Cross-Lingual Natural Language Inference (XNLI) corpus will be detailed. Tasks such as cross-lingual classification and the utilization of cross-lingual sentence representation for training on one language and testing on another one will be presented by giving concrete examples of real-life problems in natural language processing (NLP), such as multilingual intent classification.

Massive multilingual translation is also another important part of this chapter. Multilingual models, such as mBART and M2M100, can perform translation tasks in a massive number of languages as well.

In short, you will learn the following topics in this chapter:

  • Translation language modeling and cross-lingual knowledge sharing
  • XLM and mBERT
  • Cross-lingual similarity tasks
  • Cross-lingual classification
  • Cross-lingual zero-shot learning
  • Massive multilingual translation

The code for this chapter is found in the repo at https://github.com/PacktPublishing/Mastering-Transformers-Second-Edition, which is in the GitHub repository for this book. We will be using Jupyter Notebook to run our coding exercises that require Python 3.6.0+, and the following packages will need to be installed:

  • tensorflow
  • pytorch
  • transformers >=4.00
  • datasets
  • sentence-transformers
  • umap-learn
  • openpyxl

Translation language modeling and cross-lingual knowledge sharing

Section titled “Translation language modeling and cross-lingual knowledge sharing”

So far, you have learned about masked language modeling (MLM) as a cloze task. However, language modeling using neural networks is divided into three categories based on the approach itself and its practical usage, as follows:

  • MLM
  • Causal language modeling (CLM)
  • Translation language modeling (TLM)

It is also important to note that there are other pretraining approaches, such as next-sentence prediction (NSP) and sentence order prediction (SOP), but we only consider token-based language modeling. These three are the main approaches that are used in the literature. MLM, which is described and detailed in previous chapters, is a very close concept to a cloze task in language learning.

CLM is defined by predicting the next token, which is followed by some previous tokens. For example, if you see the following context, you can easily predict the next token:

<s> Transformers changed the natural language …

As you see, only the last token is masked, and the previous tokens are given to the model to predict the last one. This token would be processing, and if the context with this token is given to you again, you might end it with an “</s>” token. In order to have good training in this approach, it is required not to mask the first token because the model would have just a sentence start token to make a sentence out of it. This sentence can be anything! Here’s an example:

<s> …

What would you predict from this? It can be literally anything. To obtain better training and better results, it is required to give at least the first token, such as this:

<s> Transformers …

The model is required to predict change; after giving it Transformers changed…, it is required to predict the, and so on. This approach is very similar to N-grams and long-short-term memory (LSTM)-based approaches because it is left-to-right modeling based on the probability P(wn|wn-1, wn-2,…,w0), where wn is the token to be predicted, and the rest represents the tokens before it. The token with the maximum probability is the predicted one.

These are the objectives used for monolingual models. So, what can be done for cross-lingual models? The answer is TLM, which is very similar to MLM, with a few changes. Instead of giving a sentence from a single language, a sentence pair is given to a model in different languages, separated by a special token. The model is required to predict the masked tokens, which are randomly masked in any of these languages.

The following sentence pair is an example of such a task:

Figure 13.1 – Cross-lingual relation example between Turkish and English

Given these two masked sentences, the model is required to predict the missing tokens. In this task, on some occasions, the model has access to the tokens (for example, doğal and language, respectively, in the sentence pair in Figure 13*.1*) that are missing from one of the languages in the pair.

As another example, you can see the same pair in the Persian and Turkish sentences. In the second sentence, the değiştirdiler token can be attended by multiple tokens (one is masked) in the first sentence. In the following example, the word تغییر is missing, but the meaning of değiştirdiler is تغییر دادند:

Figure 13.2 – Cross-lingual relation example between Persian and Turkish

Accordingly, a model can learn the mapping between these meanings. Just as with a translation model, our TLM must also learn these complexities between languages because machine translation (MT) is more than a token-to-token mapping.

So far, we learned how cross-lingual models can learn via translation language modeling. In the next part, two of the well-known models in this field will be explained further.

In this section, we will delve into the explanation of two models: mBERT and XLM. The rationale behind choosing these models lies in their representation as the foremost examples of multilingual models; mBERT is a multilingual model trained on a different corpus of various languages using MLM modeling. It can operate separately for many languages. On the other hand, XLM is trained on different corpora using MLM, CLM, and TLM language modeling, and it can solve cross-lingual tasks. For instance, it can measure the similarity of the sentences in two different languages by mapping them in a common vector space, which is not possible with mBERT.

You are familiar with the BERT autoencoder model from Chapter 3, and how to train it using MLM on a specified corpus. Imagine a case where a wide and huge corpus is provided not from a single language but from 104 languages instead. Training on such a corpus would result in a multilingual version of BERT. However, training using such a wide variety of languages would increase the model size, and this is inevitable in the case of BERT. The vocabulary size would be increased, and accordingly, the size of the embedding layer would be larger because of more vocabulary.

Compared to a monolingual pretrained BERT, this new version is capable of handling multiple languages inside a single model. However, the downside of this kind of modeling is that this model is not capable of mapping between languages. This means that the model, in the pretraining phase, does not learn anything about these mappings between the semantic meanings of the tokens from different languages. In order to provide cross-lingual mapping and understanding for this model, it is necessary to train it on some of the cross-lingual supervised tasks, such as those available in the XNLI dataset.

Using this model is as easy as working with the models you have used in the previous chapters (see https://huggingface.co/bert-base-multilingual-uncased for more details). Here’s the code you’ll need to get started:

from transformers import pipeline
unmasker = pipeline('fill-mask', model='bert-base-
multilingual-uncased')
sentences = [
"Transformers changed the [MASK] language processing",
"Transformerlar [MASK] dil işlemeyi değiştirdiler",
"ترنسفرمرها پردازش زبان [MASK] را تغییر دادند"
]
for sentence in sentences:
print(sentence)
print(unmasker(sentence)[0]["sequence"])
print("="*50)

The output will then be presented, as shown in the following code snippet:

Transformers changed the [MASK] language processing
transformers changed the english language processing
==================================================
Transformerlar [MASK] dil işlemeyi değiştirdiler
transformerlar bu dil islemeyi degistirdiler
==================================================
ترنسفرمرها پردازش زبان [MASK] را تغییر دادند
ترنسفرمرها پردازش زبانی را تغییر دادند
==================================================

As you can see, it can perform fill-mask for various languages.

The cross-lingual pretraining of language models, such as that shown with an XLM approach, is based on three different pretraining objectives. MLM, CLM, and TLM are used to pretrain the XLM model. The sequential order of this pretraining is performed using a shared BPE tokenizer between all languages. The reason that tokens are shared is that the shared tokens provide fewer tokens in the case of languages that have similar tokens or subwords, and, on the other hand, these tokens can provide shared semantics in the pretraining process. For example, some tokens have remarkably similar writing and meaning across many languages, and accordingly, these tokens are shared by BPE for all. In addition, some tokens that are spelled the same in different languages can have different meanings—for example, “was” is shared in German and English contexts. Luckily, self-attention mechanisms help us to disambiguate the meaning of “was” using the surrounding context.

Another major improvement of this cross-lingual modeling is that it is also pretrained on CLM, which makes it more reasonable for inferences where sentence prediction or completion is required. In other words, this model has an understanding of the languages and is capable of completing sentences, predicting missing tokens, and predicting missing tokens by using other language sources.

The following diagram shows the overall structure of cross-lingual modeling. You can read more at https://arxiv.org/pdf/1901.07291.pdf:

Figure 13.3 – MLM and TLM pretraining for cross-lingual modeling

A newer version of the XLM model was also released: XLM-R, which has minor changes in the training and corpus used. XLM-R is identical to the XLM model but is trained on more languages and a much bigger corpus. The CommonCrawl and Wikipedia corpus are aggregated, and the XLM-R is trained for MLM on this. However, the XNLI dataset is also used for TLM. The following diagram shows the amount of data used by XLM-R pretraining:

Figure 13.4 – Amount of data in gigabytes (GB) (log-scale)

There are many upsides and downsides when adding new languages for training data; for example, adding new languages may not always improve the overall model of natural language inference (NLI). The XNLI dataset is usually used for multilingual and cross-lingual NLI. From previous chapters, we have seen the Multi-Genre NLI (MNLI) dataset for English; the XNLI dataset is almost identical to it but has more languages, and it also has sentence pairs. However, training only on this task is not enough, and it will not cover TLM pretraining. For TLM pretraining, much broader datasets, such as the parallel corpus of OPUS (short for Open Source Parallel Corpus), are used. This dataset contains subtitles from different languages, which are aligned and cleaned, with the translations provided by many software sources such as Ubuntu.

The following screenshot shows OPUS (https://opus.nlpl.eu/trac/) and its components for searching and getting information about the dataset:

Figure 13.5 – An overview of OPUS

The steps for using cross-lingual models are described here:

  1. Simple changes to the previous code can show you how XLM-R performs mask filling. First, you must change the model
    unmasker = pipeline('fill-mask', model='xlm-roberta-base')
  2. Afterward, you need to change the mask token from [MASK] to <mask>, which is a special token for XLM-R (or simply call tokenizer.mask_token). Here’s the code to
    sentences = [
    "Transformers changed the <mask> language processing",
    "Transformerlar <mask> dil işlemeyi değiştirdiler",
    "ترنسفرمرها پردازش زبان <mask" را تغییر دادند
    ]
  3. Then, you can run the same code
    for sentence in sentences:
    print(sentence)
    print(unmasker(sentence)[0]["sequence"])
    print("="*50)
  4. The results
    Transformers changed the <mask> language processing
    Transformers changed the human language processing
    ==================================================
    Transformerlar <mask> dil işlemeyi değiştirdiler
    Transformerlar, dil işlemeyi değiştirdiler
    ================================================== ترنسفرمرها پردازش زبان [MASK] را تغییر دادند
    ترنسفرمرها پردازش زبانی را تغییر دادند
    ==================================================
  5. However, as you can see from the Turkish and Persian examples, the model still made mistakes; for example, in the Persian text, it just added ی, and in the Turkish version, it added,. For the English sentence, it added human, which is not what was expected. The sentences are not wrong, but they are not what we expected. However, this time, we have a cross-lingual model that is trained using TLM, so let’s use it by concatenating two sentences and giving the model some extra hints. Here
    print(unmasker("Transformers changed the natural language processing. </s> Transformerlar <mask> dil işlemeyi değiştirdiler.")[0]["sequence"])
  6. The results will be shown
    Transformers changed the natural language processing. Transformerlar doğal dil işlemeyi değiştirdiler.
  7. That’s it! The model has now made the right choice. Let’s play with it a bit more and see how
    print(unmasker("Earth is a great place to live in. </s> زمین جای خوبی برای <mask> کردن است.")[0]["sequence"])
    Here is the result:
    Earth is a great place to live in. زمین جای خوبی برای زندگی کردن است.

Well done! So far, you have learned about multilingual and cross-lingual models such as mBERT and XLM. In the next section, you will learn how to use such models for multilingual text similarity. You will also see some use cases, such as multilingual plagiarism detection.

Cross-lingual models are capable of representing text in a unified form, where sentences are taken from different languages but those with close meaning are mapped to similar vectors in vector space. XLM-R, as was detailed in the previous section, is one of the successful models in this scope. Now, let’s look at some applications of this.

In the following example, you will see how it is possible to use a cross-lingual language model pre-trained on the XNLI dataset to find similar texts from different languages. A use-case scenario is where a plagiarism detection system is required for this task. We will use sentences from the Azerbaijani language and see whether XLM-R finds similar sentences from English—if there are any. The sentences from both languages are identical. Here are the steps to take:

  1. First, you need to load a model for this task
    from sentence_transformers import SentenceTransformer, util
    model = SentenceTransformer("stsb-xlm-r-multilingual")
  2. Afterward, we assume that we have sentences ready in the form of two separate lists, as illustrated in the following
    azeri_sentences = ['Pişik çöldə oturur',
    'Bir adam gitara çalır',
    'Mən makaron sevirəm',
    'Yeni film möhtəşəmdir',
    'Pişik bağda oynayır',
    'Bir qadın televizora baxır',
    'Yeni film çox möhtəşəmdir',
    'Pizzanı sevirsən?']
    english_sentences = ['The cat sits outside',
    'A man is playing guitar',
    'I love pasta',
    'The new movie is awesome',
    'The cat plays in the garden',
    'A woman watches TV',
    'The new movie is so great',
    'Do you like pizza?']
  3. The next step is to represent these sentences in vector space by using the XLM-R model. You can do this by simply using the encode function of the model
    azeri_representation = model.encode(azeri_sentences)
    english_representation = model.encode(english_sentences)
  4. In the final step, we will search for semantically similar sentences of the first language against the other language’s representations
    results = []
    for azeri_sentence, query in zip(azeri_sentences,
    azeri_representation):
    id_, score = util.semantic_search(
    query,english_representation)[0][0].values()
    results.append({
    "azeri": azeri_sentence,
    "english": english_sentences[id_],
    "score": round(score, 4)
    })
  5. In order to see a clear form of these results, you can use a pandas DataFrame,
    import pandas as pd
    pd.DataFrame(results)
    You will see the results with their matching score as follows:

Figure 13.6 – Plagiarism detection results (XLM-R)

The model made mistakes in one case (row number 4) if we accept the maximum scored sentence to be paraphrased or translated, but it is useful to have a threshold and accept values higher than it. We will show more comprehensive experimentation in the following sections.

On the other hand, alternative bi-encoders are available, too. Such approaches provide a pair encoding of two sentences and classify the result to train the model. In such cases, language-agnostic bert sentence embedding (LaBSE) may be a good choice, too, and it is available in the sentence-transformers library and in TensorFlow Hub, too. LaBSE is a dual encoder based on transformers, which is similar to Sentence-BERT, where two encoders that have the same parameters are combined with a loss function based on the dual similarity of two sentences.

Using the same example, you can change the model to LaBSE in a very simple way and rerun the previous code (Step 1), as follows:

model = SentenceTransformer("LaBSE")

The results are shown in the following screenshot:

Figure 13.7 – Plagiarism detection results (LaBSE)

As you see, LaBSE performs better in this case, and the result in row number 4 is correct this time. LaBSE authors claim that it works very well in finding translations of sentences, but it is not so good at finding sentences that are not completely identical. For this purpose, it is a very useful tool for finding plagiarism in cases where a translation is used to steal intellectual material. However, there are many other factors that change the results, too—for example, the resource size for the pre-trained model in each language and the nature of the language pairs is also important. For a reasonable comparison, we need a more comprehensive experiment, and we should consider many factors.

Visualizing cross-lingual textual similarity

Section titled “Visualizing cross-lingual textual similarity”

Now, we will measure and visualize the degree of textual similarity between two sentences, one of which is a translation of the other. Tatoeba is a free collection of such sentences and translations, and it is part of the XTREME benchmark. The community aims to obtain high-quality sentence translation with the support of many participants. We’ll now take the following steps:

  1. We will take Russian and English sentences out of this collection. Make sure the following libraries are installed before you
    !pip install sentence_transformers datasets transformers umap-learn
  2. Load the sentence pairs
    from datasets import load_dataset
    import pandas as pd
    data=load_dataset("xtreme","tatoeba.rus",
    split="validation")
    pd.DataFrame(data)[["source_sentence","target_sentence"]]
  3. Let’s look at the output:

Figure 13.8 – Russian–English sentence pairs

  1. First, we will take the first K=30 sentence pairs for visualization, and later, we will run an experiment for the entire set. Now, we will encode them with the sentence transformers that we already used for the previous example. Here is the execution of
    from sentence_transformers import SentenceTransformer
    model = SentenceTransformer("stsb-xlm-r-multilingual")
    K=30
    q=data["source_sentence"][:K] + data["target_sentence"][:K]
    emb=model.encode(q)
    len(emb), len(emb[0])
    Output: (60, 768)
  2. We now have 60 vectors of length 768. We will reduce the dimensionality to 2 by using uniform manifold approximation and projection (UMAP), which we have already encountered in previous chapters. We visualized sentences that are translations of each other, marking them with the same color and code. We also drew a dashed line between them to make the link more obvious. The code is illustrated in the
    import matplotlib.pyplot as plt
    import numpy as np
    import umap
    import pylab
    X= umap.UMAP(n_components=2, random_state=42).fit_transform(emb)
    idx= np.arange(len(emb))
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.set_facecolor('whitesmoke')
    cm = pylab.get_cmap("prism")
    colors = list(cm(1.0*i/K) for i in range(K))
    for i in idx:
    if i<K:
    ax.annotate("RUS-"+str(i), # text
    (X[i,0], X[i,1]), # coordinates
    c=colors[i]) # color
    ax.plot((X[i,0],X[i+K,0]),(X[i,1],X[i+K,1]),"k:")
    else:
    ax.annotate("EN-"+str(i%K),
    (X[i,0], X[i,1]),
    c=colors[i%K])
  3. Here is the output of the preceding code:

Figure 13.9 – An overview of Russian–English sentence similarity visualization

As we expected, most sentence pairs are located close to each other. Inevitably, certain pairs (such as id 12) insist on not being close.

  1. For a comprehensive analysis, let’s now measure the entire dataset. We encode all of the source and target sentences—1K
    source_emb=model.encode(data["source_sentence"])
    target_emb=model.encode(data["target_sentence"])
  2. We calculate the cosine similarity between all pairs, save them in the sims variable, and plot a histogram
    from scipy import spatial
    sims=[ 1 - spatial.distance.cosine(s,t) \
    for s,t in zip(source_emb, target_emb)]
    plt.hist(sims, bins=100, range=(0.8,1))
    plt.show()
  3. Here is the output:

Figure 13.10 – Similarity histogram for the English and Russian sentence pairs

  1. As can be seen, the scores are very close to 1. This is what we expect from a good cross-lingual model. The mean and standard deviation of all similarity measurements also support the cross-lingual model performance,
    >>> np.mean(sims), np.std(sims)
    (0.946, 0.082)
  2. You can run the same code yourself for languages other than Russian. As you run it with French (fra), Tamil (tam), and so on, you will get the following resulting table. The table indicates that in your experiment, you will see that the model works well in many languages but fails in others, such as Afrikaans or Tamil:
    LanguageCodeMeanStd
    Frenchfra0.940.087
    Afrikaansafr0.790.18
    Arabicara0.940.08
    Koreankor0.920.11
    Tamiltam0.770.19

Table 13.1 – Cross-lingual model performance for other languages

In this section, we applied cross-lingual models to measure similarity between different languages. In the next section, we’ll make use of cross-lingual models in a supervised way.

So far, you have learned that cross-lingual models are capable of understanding different languages in semantic vector space where similar sentences, regardless of their language, are close in terms of vector distance. However, how it is possible to use this capability in use cases where we have few samples available?

For example, you are trying to develop an intent classification for a chatbot in which there are few samples or no samples available for the second language; however, for the first language—let’s say English—you do have enough samples. In such cases, it is possible to freeze the cross-lingual model itself and just train a classifier for the task. A trained classifier can be tested on a second language instead of the language it is trained on.

In this section, you will learn how to train a cross-lingual model in English for text classification and test it in other languages. We have selected a very low-resource language known as Khmer, which is spoken by 16 million people in Cambodia, Thailand, and Vietnam. It has few resources on the internet, and it is hard to find good datasets with which to train your model. However, we have access to a good Internet Movie Database (IMDb) sentiment dataset of movie reviews for sentiment analysis. We will use that dataset to find out how our model performs in a language on which it is not trained.

The following diagram nicely depicts the kind of flow we will follow. The model is trained with training data on the left, and this model is applied to the test sets on the right. Please notice that MT and sentence-encoder mappings play a significant role in the flow:

Figure 13.11 – Flow of cross-lingual classification

The required steps to load and train a model for cross-lingual testing are outlined here:

  1. The first step is to load the dataset
    from datasets import load_dataset
    sms_spam = load_dataset("imdb")
  2. You need to shuffle the dataset to shuffle the samples before using them,
    imdb = imdb.shuffle()
  3. The next step is to make a good test split out of this dataset, which is in the Khmer language. In order to do so, you can use a translation service such as Google Translate. First, you should save this dataset in Excel format
    imdb_x = [x for x in imdb['train'][:1000]['text']]
    labels = [x for x in imdb['train'][:1000]['label']]
    import pandas as pd
    pd.DataFrame(imdb_x,
    columns=["text"]).to_excel(
    "imdb.xlsx",
    index=None)
  4. Afterward, you can upload it to Google Translate and get the Khmer translation of this dataset (https://translate.google.com/?sl=en&tl=km&op=docs), as illustrated in the following screenshot:

Figure 13.12 – Google document translator

  1. After selecting and uploading the document, you will obtain the translated version in Khmer, which you can copy and paste into an Excel file. It is also required to be saved in Excel format again. The result is an Excel document that is a translation of the original spam/ham English dataset. You can read it using pandas by running the
    pd.read_excel("KHMER.xlsx")
    The following results will be seen:

Figure 13.13 – IMDB dataset in KHMER language

  1. However, we only need to obtain text, so you should use the
    imdb_khmer = list(pd.read_excel("KHMER.xlsx").text)
  2. Now that you have text for both languages and the labels, you can split the train and test validations
    from sklearn.model_selection import train_test_split
    train_x, test_x, train_y, test_y, khmer_train, khmer_test = \
    train_test_split(imdb_x, labels, imdb_khmer,
    test_size = 0.2, random_state = 1)
  3. The next step is to provide the representation of these sentences using the XLM-R cross-lingual model. First, you should load the model
    from sentence_transformers import SentenceTransformer
    model = SentenceTransformer("stsb-xlm-r-multilingual")
  4. Now, you can obtain
    encoded_train = model.encode(train_x)
    encoded_test = model.encode(test_x)
    encoded_khmer_test = model.encode(khmer_test)
  5. However, you should not forget to convert the labels into the NumPy format because TensorFlow and Keras only deal with NumPy arrays when using the fit function of the Keras models. Here’s how to
    import numpy as np
    train_y = np.array(train_y)
    test_y = np.array(test_y)
  6. Now that everything is ready, let’s make a very simple model for classifying
    import tensorflow as tf
    input_ = tf.keras.layers.Input((768,))
    classification = tf.keras.layers.Dense(
    1, activation="sigmoid")(input_)
    classification_model = \
    tf.keras.Model(input_, classification)
    classification_model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(),
    optimizer="Adam",
    metrics=["accuracy", "Precision", "Recall"])
  7. You can fit your model using the
    classification_model.fit(
    x = encoded_train,
    y = train_y,
    validation_data=(encoded_test, test_y),
    epochs = 10)
  8. The results for 20 epochs of training are shown here:

Figure 13.14 – Training results on the English version of the IMDb dataset

  1. As you have seen, we used an English test set to see the model performance across epochs, and it is reported in the final epoch
    val_loss: 0.5226
    val_accuracy: 0.7150
    val_precision: 0.7600
    val_recall: 0.6972
  2. Now, we have trained our model and tested it on English; let’s test it on the Khmer test set, as our model had not seen any of the samples in either English or Khmer. Here’s the code to
    classification_model.evaluate(x = encoded_khmer_test,
    y = test_y)
    Here are the results:
    loss: 0.5949
    accuracy: 0.7250
    precision: 0.7014
    recall: 0.8623

So far, you have learned how it is possible to leverage the capabilities of cross-lingual models in low-resource languages. It makes a huge impact and difference when you can use such a capability in cases where there are very few samples or no samples on which to train the model. In the next section, you will learn how it is possible to use zero-shot learning where there are no samples available, even for high-resource languages such as English.

In the previous sections, you learned how to perform zero-shot text classification using monolingual models. Using XLM-R for multilingual and cross-lingual zero-shot classification is identical to the approach and code used previously, so we will use mT5 here.

mT5, which is a massively multilingual pretrained language model, is based on the encoder-decoder architecture of Transformers and is also identical to T5. T5 is pretrained on English and mT5 is trained on 101 languages from Multilingual Common Crawl (mC4).

The fine-tuned version of mT5 on the XNLI dataset is available from the Hugging Face repository (https://huggingface.co/alan-turing-institute/mt5-large-finetuned-mnli-xtreme-xnli).

The T5 model and its variant, mT5, are completely text-to-text models, which means they will produce text for any task given, even if the task is classification or NLI. So, in the case of inferring this model, extra steps are required. We’ll take the following steps:

  1. The first step is to load the model and the tokenizer
    from torch.nn.functional import softmax
    from transformers import(
    MT5ForConditionalGeneration, MT5Tokenizer)
    model_name = "alan-turing-institute/mt5-large-finetuned-mnli-xtreme-xnli"
    tokenizer = MT5Tokenizer.from_pretrained(model_name)
    model = MT5ForConditionalGeneration\
    .from_pretrained(model_name)
  2. In the next step, let’s provide samples to be used in zero-shot classification—a sentence and
    sequence_to_classify = \
    "Wen arden Sie bei der nächsten Wahl wählen? "
    candidate_labels = ["spor", "ekonomi", "politika"]
    hypothesis_template = "Dieses Beispiel ist {}."
    As you can see, the sequence itself is in German (“Who will you vote for in the next election?”) but the labels are written in Turkish (“spor”, “ekonomi”, “politika”). hypothesis_template says: “this example is…” in German.
  3. The next step is to set the label identifiers (IDs) of the entailment, CONTRADICTS, and NEUTRAL, which will be used later when inferring the generated results. Here’s the code you’ll need to
    ENTAILS_LABEL = "_0"
    NEUTRAL_LABEL = "_1"
    CONTRADICTS_LABEL = "_2"
    label_inds = tokenizer.convert_tokens_to_ids([
    ENTAILS_LABEL,
    NEUTRAL_LABEL,
    CONTRADICTS_LABEL])
  4. As you’ll recall, the T5 model uses prefixes to know which task it is supposed to perform. The following function provides the XNLI prefix, along with the premise and hypothesis in the
    def process_nli(premise, hypothesis):
    return f'xnli: premise: {premise} hypothesis: {hypothesis}'
  5. In the next step, for each label, a sentence will be generated, as illustrated in the following
    pairs =[(sequence_to_classify,\
    hypothesis_template.format(label)) for label in
    candidate_labels]
    seqs = [process_nli(premise=premise,
    hypothesis=hypothesis)
    for premise, hypothesis in pairs]
  6. You can see the resulting sequences by printing them
    print(seqs)
    ['xnli: premise: Wen werden Sie bei der nächsten Wahl wählen? hypothesis: Dieses Beispiel ist spor.',
    'xnli: premise: Wen werden Sie bei der nächsten Wahl wählen? hypothesis: Dieses Beispiel ist ekonomi.',
    'xnli: premise: Wen werden Sie bei der nächsten Wahl wählen? hypothesis: Dieses Beispiel ist politika.']
    These sequences simply say that the task is XNLI-coded by xnli:; the premise sentence is “Who will you vote for in the next election?” (in German), and the hypothesis is “this example is politics”, “this example is a sport” or “this example is economy”.
  7. In the next step, you can tokenize the sequences and give them to the model to generate the text according
    inputs = tokenizer.batch_encode_plus(seqs,
    return_tensors="pt", padding=True)
    out = model.generate(**inputs, output_scores=True,
    return_dict_in_generate=True,num_beams=1)
  8. The generated text actually gives scores for each token in the vocabulary, and what we are looking for is the entailment, contradiction, and neutral scores. You can get their score using their token IDs
    scores = out.scores[0]
    scores = scores[:, label_inds]
  9. You can see these scores by
    print(scores)
    tensor([[-0.9851, 2.2550, -0.0783],
    [-5.1690, -0.7202, -2.5855],
    [ 2.7442, 3.6727, 0.7169]])
  10. The neutral score is not required for our purpose, and we only need contradiction compared to entailment. So, you can use the following code to obtain these
    entailment_ind = 0
    contradiction_ind = 2
    entail_vs_contra_scores = scores[:, [entailment_ind,
    contradiction_ind]]
  11. Now that you have these scores for each sequence of the samples, you can apply a softmax layer to them to obtain the probabilities
    entail_vs_contra_probas = softmax(entail_vs_contra_scores,
    dim=1)
  12. To see these probabilities, you can
    print(entail_vs_contra_probas)
    tensor([[0.2877, 0.7123],
    [0.0702, 0.9298],
    [0.8836, 0.1164]])
  13. Now, you can compare the entailment probability of these three samples by selecting them and applying a softmax layer over them
    entail_scores = scores[:, entailment_ind]
    entail_probas = softmax(entail_scores, dim=0)
  14. To see the values, use print
    print(entail_probas)
    tensor([2.3438e-02, 3.5716e-04, 9.7620e-01])
  15. The result means the highest probability belongs to the third sequence. In order to see it in a better shape, use the
    print(dict(zip(candidate_labels, entail_probas.tolist())))
    {'ekonomi': 0.0003571564157027751,
    'politika': 0.9762046933174133,
    'spor': 0.023438096046447754}

The whole process can be summarized as follows: each label is given to the model with the premise, and the model generates scores for each token in the vocabulary. We use these scores to find out how much the entailment token scores over the contradiction.

Speaking of cross-lingual models and models that can perform well on multilingual data, one of the tasks that are always important in this field is translation. However, different approaches exist for translation; some approaches suggest having different models for each language pair, whereas others suggest using a single model for all of the language pairs.

M2M100 is one of the most important models in this field and can translate 9,900 directions in 100 languages. Using this model and performing translation tasks is simple with the help of the transformers library:

from transformers import (
M2M100ForConditionalGeneration, M2M100Tokenizer)
model = M2M100ForConditionalGeneration.from_pretrained(
"facebook/m2m100_1.2B")
tokenizer = M2M100Tokenizer.from_pretrained(
"facebook/m2m100_1.2B")

Before giving the input to the model, you need to also set the source language of the text as well:

text_turkish = "ne olacak bu insanlik hali?"
tokenizer.src_lang = "tr"
encoded_text = tokenizer(text_turkish, return_tensors="pt")

To generate the output, the language id of the target language should be passed to the model as well, as it will guide the model to generate the translation in the given language:

generated_tokens = model.generate(**encoded_text,
forced_bos_token_id=tokenizer.get_lang_id("fa"))
text_persian = tokenizer.batch_decode(generated_tokens,
skip_special_tokens=True)

Now, you can see the translated output in Persian:

print(text_persian[0])
این وضعیت بشری چه خواهد بود؟

You can use any of the 101 languages supported by the model for source and destination text. So far, you have learned how massive machine translation models work. In the next part, you will learn more about the fundamental limitations of multilingual models.

Despite the potential of multilingual and cross-lingual models in NLP, their effectiveness is limited in smaller language models such as BERT. This has been the focus of many studies. For example, the mBERT model doesn’t perform as well as monolingual models in various tasks, which is why the latter is still commonly used, particularly in classification tasks. On the other hand, recent developments in larger language models have largely addressed the limitations of multilingual models and improved their capacity. This improvement is attributed to an increase in parameters, expanded training datasets, and advanced training methods, such as reinforcement learning. Consequently, there’s been a rise in successful multilingual models such as mT5, Bloomz, Bactrian-x, and Aya-101. These models are open source and, thus, accessible.

Studies in the field indicate that multilingual models suffer from the so-called curse of multilingualism as they seek to appropriately represent all languages. Adding new languages to a multilingual model improves its performance up to a certain point. However, it is also seen that adding more after this point degrades performance, which may be due to shared vocabulary. Compared to monolingual models, multilingual models are significantly more limited in terms of the parameter budget. They need to allocate their vocabulary to each of more than 100 languages.

The existing performance differences between mono- and multilingual models can be attributed to the capability of the designated tokenizer. The study How Good is Your Tokenizer? On the Monolingual Performance of Multilingual Language Models (2021) by Rust et al. (https://arxiv.org/abs/2012.15613) showed that when a dedicated language-specific tokenizer (rather than a general-purpose one, e.g., a shared multilingual tokenizer) is attached to a multilingual model, it improves in performance for that language.

Some other findings indicate that it is not currently possible to represent all the world’s languages in a single model due to an imbalance in the distribution of resources for different languages. As a solution, low-resource languages can be oversampled, while high-resource languages can be undersampled. Another observation is that knowledge transfer between two languages can be more efficient if those languages are close. If they are distant languages, this transfer may have little effect. This observation may explain why we got worse results for Afrikaans and Tamil languages in the previous cross-lingual sentence-pair experiment part.

However, there is a lot of work on this subject, and these limitations may be overcome at any time. As of writing this article, the team of XML-R recently proposed two new models—namely, XLM-R XL and XLM-R XXL—that outperform the original XLM-R model by 1.8% and 2.4% average accuracies, respectively, on XNLI.

Fine-tuning the performance of multilingual models

Section titled “Fine-tuning the performance of multilingual models”

Now, let’s check whether the fine-tuned performance of the multilingual models is actually worse than that of the monolingual models. As an example, let’s recall the example of Turkish text classification with seven classes in Chapter 5. In that experiment, we fine-tuned a Turkish-specific monolingual model and achieved a good result. We will repeat the same experiment, keeping everything as-is but replacing the Turkish monolingual model with the mBERT and XLM-R models, respectively. Here’s how we’ll do this:

  1. Let’s recall the codes in that example again. We fine-tuned the “dbmdz/bert-base-turkish-uncased” model
    from transformers import BertTokenizerFast
    tokenizer = BertTokenizerFast.from_pretrained(
    "dbmdz/bert-base-turkish-uncased")
    from transformers import BertForSequenceClassification
    model = BertForSequenceClassification.from_pretrained(\
    "dbmdz/bert-base-turkish-uncased",
    num_labels=NUM_LABELS,
    id2label=id2label,
    label2id=label2id)
    With the monolingual model, we got the following performance values:

Figure 13.15 – Monolingual text classification performance (from Chapter 5)

  1. To fine-tune using mBERT, we need to replace the preceding model instantiation lines only. Now, we will use the “bert-base-multilingual-uncased” multilingual model. We instantiate it
    from transformers import(
    BertForSequenceClassification, AutoTokenizer)
    tokenizer = AutoTokenizer.from_pretrained(
    "bert-base-multilingual-uncased")
    model = BertForSequenceClassification.from_pretrained(
    "bert-base-multilingual-uncased",
    num_labels=NUM_LABELS,
    id2label=id2label,
    label2id=label2id)
  2. There is not much difference in coding. When we run the experiment keeping all other parameters and settings the same, we get the following performance values:

Figure 13.16 – mBERT fine-tuned performance

Hmm! The multilingual model underperforms compared with its monolingual counterpart by roughly 2.2% for all metrics.

  1. Let’s fine-tune the “xlm-roberta-base” XLM-R model for the same problem. We’ll execute the XLM-R model initialization code
    from transformers import (
    AutoTokenizer, XLMRobertaForSequenceClassification)
    tokenizer = AutoTokenizer.from_pretrained(
    "xlm-roberta-base")
    model = XLMRobertaForSequenceClassification\
    .from_pretrained("xlm-roberta-base",
    num_labels=NUM_LABELS,
    id2label=id2label,label2id=label2id)
  2. Again, we keep all other settings exactly the same. We get the following performance values from the XML-R model:

Figure 13.17 – XLM-R fine-tuned performance

Not bad! The XLM model did give comparable results. The obtained results are quite close to the monolingual model, with a roughly 1.0% difference. Therefore, although monolingual results can be better than multilingual models in certain tasks, we can achieve promising results with multilingual models. Think of it this way: we may not want to train a whole monolingual model for a 1% improvement in performance that lasts 10 days or more. Such small performance differences may be negligible for us.

In this chapter, you learned about multilingual and cross-lingual language model pretraining and the difference between monolingual and multilingual pretraining. CLM and TLM were also covered, and you gained knowledge about them. You learned how it is possible to use cross-lingual models on various use cases, such as semantic search, plagiarism, and zero-shot text classification. You also learned how it is possible to train using a dataset from a language and test the model on a completely different language using cross-lingual models. Fine-tuning the performance of multilingual models was evaluated, and we concluded that some multilingual models could be a substitute for monolingual models, remarkably keeping performance loss to a minimum. We also took a look at the models that can translate at a massive scale; M2M100, for example, can translate in 9,900 directions in 100 languages, and we learned how to use this model.

In the next chapter, you will learn how to deploy transformer models for real problems and train them for production at an industrial scale.

  • Conneau, A., Lample, G., Rinott, R., Williams, A., Bowman, S. R., Schwenk, H. and Stoyanov, V. (2018). XNLI: Evaluating cross-lingual sentence representations. arXiv preprint arXiv:1809.05053.
  • Xue, L., Constant, N., Roberts, A., Kale, M., Al-Rfou, R., Siddhant, A. and Raffel, C. (2020). mT5: A massively multilingual pre-trained text-to-text transformer. arXiv preprint arXiv:2010.11934.
  • Lample, G. and Conneau, A. (2019). Cross-lingual language model pretraining. arXiv preprint arXiv:1901.07291.
  • Conneau, A., Khandelwal, K., Goyal, N., Chaudhary, V., Wenzek, G., Guzmán, F. and Stoyanov, V. (2019). Unsupervised cross-lingual representation learning at scale. arXiv preprint arXiv:1911.02116.
  • Feng, F., Yang, Y., Cer, D., Arivazhagan, N. and Wang, W. (2020). Language-agnostic bert sentence embedding. arXiv preprint arXiv:2007.01852.
  • Rust, P., Pfeiffer, J., Vulić, I., Ruder, S. and Gurevych, I. (2020). How Good is Your Tokenizer? On the Monolingual Performance of Multilingual Language Models. arXiv preprint arXiv:2012.15613.
  • Goyal, N., Du, J., Ott, M., Anantharaman, G. and Conneau, A. (2021). Larger-Scale Transformers for Multilingual Masked Language Modeling. arXiv preprint arXiv:2105.00572.
  • Fan, A., Bhosale, S., Schwenk, H., Ma, Z., El-Kishky, A., Goyal, S.,… & Joulin, A. (2021). Beyond english-centric multilingual machine translation. The Journal of Machine Learning Research, 22(1), 4839-4886.