A Hands-On Introduction to the Subject
local graph
Chapter 2 — A Hands-On Introduction to the Subject
Section titled “Chapter 2 — A Hands-On Introduction to the Subject”So far, we have had an overall look at the evolution of natural language processing (NLP) using deep learning (DL)-based methods. We have learned some basic information about transformers and their respective architecture. In this chapter, we are going to have a deeper look into how a transformer model can be used. Tokenizers and models, such as bidirectional encoder representations from transformer (BERT), will be described in more technical detail with hands-on examples, including how to load a tokenizer/model and use community-provided pretrained models. However, before using any specific model, we will understand the installation steps required to provide the necessary environment by using Anaconda. In the installation steps, installing libraries and programs on various operating systems such as Linux, Windows, and macOS will be covered. The installation of PyTorch and TensorFlow, with two versions of a central processing unit (CPU) and a graphics processing unit (GPU), is also shown. A quick jump into a Google Colaboratory (Google Colab) installation of the transformer library is provided. There is also a section dedicated to using models in the PyTorch and TensorFlow frameworks.
The Hugging Face models repository is also another important part of this chapter, in which finding different models and steps to use various pipelines are discussed—for example, models such as bidirectional and auto-regressive transformer (BART), BERT, and TAble PArSing (TAPAS) are detailed, with a glance at generative pretrained transformer 2 (GPT-2) text generation. However, this is purely an overview, and this part of the chapter relates to getting the environment ready and using pretrained models. No model training is discussed here, as this is given greater significance in upcoming chapters.
We first discuss how to use the Transformer library for inference by community-provided models; then, we describe the datasets library and how to load various datasets and benchmarks and use metrics. Cross-lingual datasets and how to use local files with the datasets library are also considered here. With this chapter, we get the system ready for the rest of the book to develop your own NLP pipeline with transformers.
We will cover the following topics in this chapter:
- Installing transformer with Anaconda
- Working with language models and tokenizers
- Working with community-provided models
- Working with multimodal transformers
- Working with benchmarks and datasets
- Benchmarking for speed and memory
Technical requirements
Section titled “Technical requirements”You will need to install the libraries and software listed next. Although having the latest version is a plus, it is mandatory to install versions that are compatible with each other. For more information about the latest version installation for the Hugging Face transformer, take a look at their official web page at https://huggingface.co/docs/transformers/installation:
Anacondatransformers 4.25.1pytorch 1.13.1tensorflow 2.9.2datasets 1.4.1
Finally, all the code shown in this chapter is available in this book’s GitHub repository at https://github.com/PacktPublishing/Mastering-Transformers-Second-Edition.
Installing transformer with Anaconda
Section titled “Installing transformer with Anaconda”Anaconda is a distribution of the Python and R programming languages that makes package distribution and deployment easy for scientific computation. In this section, we will describe the installation of the Transformer library. However, it is also possible to install this library without the aid of Anaconda. The main motivation for using Anaconda is to explain the process more easily and moderate the packages used.
To start installing the related libraries, the installation of Anaconda is a mandatory step. The official guidelines provided by the Anaconda documentation offer simple steps to install it for common operating systems (macOS, Windows, and Linux).
Let’s see how we can install it on different platforms in the next sub-sections.
Installation on Linux
Section titled “Installation on Linux”Many Linux distributions are available for users to enjoy, but Ubuntu is one of the preferred ones. In this section, the steps to install Anaconda are covered for Linux. Proceed as follows:
- Download the Anaconda installer for Linux from https://www.anaconda.com/products/individual#Downloads and go to the Linux section, as illustrated in the following screenshot:

Figure 2.1 – Anaconda download link for Linux
- Run a
bashcommand to install it and complete the following steps: - Open the Terminal and run the
bash Terminal./FilePath/For/Anaconda.sh
- Press Enter to see the license agreement and press Q if you do not want to read it all, and then do the following:
- Click Yes to agree.
- Click Yes for the installer to always initialize the
condaroot environment. - After running a
pythoncommand from the Terminal, you should see an Anaconda prompt after the Python version information. - You can access Anaconda Navigator by running an
anaconda-navigatorcommand from the Terminal. As a result, you will see the Anaconda graphical user interface (GUI) start loading the related modules, as shown in the following screenshot:
Figure 2.2 – Anaconda Navigator
Let’s move on to the next section!
Installation on Windows
Section titled “Installation on Windows”The following steps describe how you can install Anaconda on Windows operating systems:
- Download the installer from https://www.anaconda.com/products/individual#Downloads and go to the Windows section, as illustrated in the following screenshot:

Figure 2.3 – Anaconda download link for Windows
- Open the installer and follow the guide by clicking the I Agree button.
- Select the location for installation, as illustrated in the following screenshot:

Figure 2.4 – Anaconda installer for Windows
Don’t forget to check the Add anaconda3 to my PATH environment variable checkbox, as illustrated in the following screenshot. If you do not check this box, the Anaconda version of Python will not be added to the Windows environment variables, and you will not be able to directly run it with a python command from the Windows shell or the Windows command line:

Figure 2.5 – Anaconda installer advanced options
- Follow the rest of the installation instructions and finish the installation.
- You should now be able to start Anaconda Navigator from the Start menu.
Now that we know how to download and install it on Linux, let’s see how we can do it on macOS.
Installation on macOS
Section titled “Installation on macOS”The following steps must be followed to install Anaconda on macOS:
- Download the installer from https://www.anaconda.com/products/individual#Downloads and go to the macOS section, as illustrated in the following screenshot:

Figure 2.6 – Anaconda download link for macOS
- Open the installer.
- Follow the instructions and click the Install button to install macOS in a predefined location, as illustrated in the following screenshot. You can change the default directory, but this is not recommended:

Figure 2.7 – Anaconda installer for macOS
Once you finish the installation, you should be able to access Anaconda Navigator.
Installing TensorFlow, PyTorch, and Transformer
Section titled “Installing TensorFlow, PyTorch, and Transformer”The installation of TensorFlow and PyTorch as two major libraries that are used for DL can be made through pip or conda itself. conda provides a command-line interface (CLI) for the easier installation of these libraries.
For a clean installation and to avoid interrupting other environments, it is better to create a conda environment for the huggingface library. You can do this by running the following code:
conda create -n TransformerThis command will create an empty environment for installing other libraries. Once created, we will need to activate it as follows:
conda activate TransformerThe installation of the Transformer library is easily done by running the following commands:
conda install -c conda-forge tensorflowconda install -c conda-forge pytorchconda install -c conda-forge transformersThe -c argument in the conda install command lets Anaconda use additional channels to search for libraries.
Note that it is a requirement to have TensorFlow and PyTorch installed because the Transformer library uses both of these libraries. An additional note is the easy handling of CPU and GPU versions of TensorFlow by Conda. If you simply put –gpu after tensorflow, it will install the GPU version automatically. For the installation of PyTorch through the cuda library (GPU version), you are required to have related libraries such as cuda, but conda handles this automatically, and no further manual setup or installation is required. The following screenshot shows how conda automatically takes care of installing the PyTorch GPU version by installing the related cudatoolkit and cudnn libraries:

Figure 2.8 – Conda installing PyTorch and related cuda libraries
Note that all of these installations can also be done without conda, but the reason behind using Anaconda is its ease of use. In terms of using environments or installing GPU versions of TensorFlow or PyTorch, Anaconda works like magic and is a good time saver.
Installing and using Google Colab
Section titled “Installing and using Google Colab”Even if the utilization of Anaconda saves time and is useful, in most cases, not everyone has such good and reasonable computation resources available. Google Colab is a good alternative in such cases. The installation of the Transformer library in Colab is carried out with the following command:
!pip install transformersAn exclamation mark before the statement makes the code run in a Colab shell, which is the equivalent to running the code in the Terminal instead of running it using a Python interpreter. This will automatically install the Transformer library.
We will see how to work with a BERT model and tokenizer.
Working with language models and tokenizers
Section titled “Working with language models and tokenizers”In this section, we will look at using the Transformer library with language models, along with their related tokenizers. In order to use any specified language model, we first need to import it. We will start with the BERT model provided by Google and use its pretrained version, as follows:
from transformers import BertTokenizertokenizer = \ BertTokenizer.from_pretrained('bert-base-uncased')The first line of the preceding code snippet imports the BERT tokenizer, and the second line downloads a pretrained tokenizer for the BERT base version. Note that the uncased version is trained with uncased letters, so it does not matter whether the letters appear in upper- or lowercase. To test and see the output, you must run the following line of code:
text = "Using Transformers is easy!"tokenizer(text)This will be the output:
{'input_ids': [101, 2478, 19081, 2003, 3733, 999, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1]}input_ids shows the token ID for each token, and token_type_ids shows the type of each token that separates the first and second sequence, as shown in the following screenshot:

Figure 2.9 – Sequence separation for BERT
attention_mask is a mask of 0s and 1s that is used to show the start and end of a sequence for the transformer model in order to prevent unnecessary computations. Each tokenizer has its own way of adding special tokens to the original sequence. In the case of the BERT tokenizer, it adds a [CLS] token to the beginning and an [SEP] token to the end of the sequence, which can be seen by 101 and 102. These numbers come from the token IDs of the pretrained tokenizer.
A tokenizer can be used for both PyTorch- and TensorFlow-based Transformer models. In order to have an output for each one, the pt and tf keywords must be used in return_tensors. For example, you can use a tokenizer by simply running the following command:
encoded_input = tokenizer(text, return_tensors="pt")encoded_input has the tokenized text to be used by the PyTorch model. In order to run the model—for example, the BERT base model—the following code can be used to download the model from the huggingface model repository:
from transformer import BertModelmodel = BertModel.from_pretrained("BERT-base-uncased")The output of the tokenizer can be passed to the downloaded model with the following line of code:
output = model(**encoded_input)This will give you the output of the model in the form of embeddings and cross-attention outputs.
When loading and importing models, you can specify which version of a model you are trying to use. If you simply put TF before the name of a model, the Transformer library will load the TensorFlow version of it. The following code shows how to load and use the TensorFlow version of BERT base:
from transformers import BertTokenizer, TFBertModeltokenizer = \ BertTokenizer.from_pretrained('BERT-base-uncased')model = TFBertModel.from_pretrained("BERT-base-uncased")text = " Using Transformer is easy!"encoded_input = tokenizer(text, return_tensors='tf')output = model(**encoded_input)For specific tasks, such as filling masks using language models, there are pipelines designed by Hugging Face that are ready to use. For example, the task of filling a mask can be seen in the following code snippet:
from transformers import pipelineunmasker = \ pipeline('fill-mask', model='BERT-base-uncased')unmasker("The man worked as a [MASK].")This code will produce the following output, which shows the scores and possible tokens to be placed in the [``MASK] token:
[{'score': 0.09747539460659027, 'sequence': 'the man worked as a carpenter.', 'token': 10533, 'token_str': 'carpenter'}, {'score': 0.052383217960596085, 'sequence': 'the man worked as a waiter.', 'token': 15610, 'token_str': 'waiter'}, {'score': 0.049627091735601425, 'sequence': 'the man worked as a barber.', 'token': 13362, 'token_str': 'barber'}, {'score': 0.03788605332374573, 'sequence': 'the man worked as a mechanic.', 'token': 15893, 'token_str': 'mechanic'}, {'score': 0.03768084570765495, 'sequence': 'the man worked as a salesman.', 'token': 18968, 'token_str': 'salesman'}]To get a neat view using pandas, run the following code:
pd.DataFrame(unmasker("The man worked as a [MASK]."))The result can be seen in the following screenshot:

Figure 2.10 – Output of the BERT mask filling
So far, we have learned how to load and use a pretrained BERT model and have understood the basics of tokenizers, as well as the difference between PyTorch and TensorFlow versions of the models. In the next section, we will learn to work with community-provided models by loading different models, reading the related information provided by the model authors, and using different pipelines such as text-generation or question-answering (QA) pipelines.
Working with community-provided models
Section titled “Working with community-provided models”Hugging Face has tons of community models provided by collaborators from large artificial intelligence (AI) and information technology (IT) companies such as Google and Facebook. Individuals and universities also provide many interesting models. Accessing and using them is also very easy. To start, you should visit the Transformer models directory available on their website (https://huggingface.co/models), as shown in the following screenshot:

Figure 2.11 – An overview of Hugging Face models repository
Apart from these models, there are also many good and useful datasets available for NLP tasks. To start using some of these models, you can explore them by keyword searches, or just specify your major NLP task and pipeline.
For example, we are looking for a table QA model. After finding a model that we are interested in, a page such as the following one will be available from the Hugging Face website (https://huggingface.co/google/tapas-base-finetuned-wtq):

Figure 2.12 – TAPAS model page
On the right side, there is a panel where you can test this model. Note that this is a table QA model that can answer questions about a table provided to the model. If you ask a question, it will reply by highlighting the answer. The following screenshot shows how it gets input and provides an answer for a specific table:

Figure 2.13 – Table QA using TAPAS
Each model has a page provided by the model authors that is also known as a model card. You can use the model by the examples provided on the model page. For example, you can visit the GPT-2 huggingface repository page and take a look at the example provided by the authors (https://huggingface.co/gpt2), as shown in the following screenshot:

Figure 2.14 – Text-generation code example from the Hugging Face GPT-2 page
Using pipelines is recommended because all the dirty work is taken care of by the Transformer library. As another example, let’s assume you need an out-of-the-box zero-shot classifier. The following code snippet shows how easy it is to implement and use such a pretrained model:
from transformers import pipelineclassifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")sequence_to_classify = "I am going to france."candidate_labels = ['travel', 'cooking', 'dancing']classifier(sequence_to_classify, candidate_labels)The preceding code will provide the following result:
{'labels': ['travel', 'dancing', 'cooking'], 'scores': [0.9866883158683777, 0.007197578903287649, 0.006114077754318714], 'sequence': 'I am going to france.'}We are done with the installation and the hello-world application part. So far, we have introduced the installation process, completed the environment settings, and experienced the first transformer pipeline. In the next section, we will introduce the datasets library, which will be an essential utility in the upcoming experimental chapters.
Working with multimodal transformers
Section titled “Working with multimodal transformers”Multimodal transformers such as CLIP are very useful where more than one modality is involved. In order to provide a use-case for this kind of model, a very simple and straight forward example is given.
Zero-shot image classification can be very useful when only class names or phrases related to the classes are available. CLIP, which is a multimodal model, is able to represent images and texts in the same semantic space and can be very handy in this situation. To have a zero-shot image classifier with no prior knowledge about what classes can be or might be, imagine a case where class names are given with no examples for each of them. The only knowledge that is available at the moment is these names or maybe phrases and a set of images, which were not seen before.
- The first thing that is needed to perform this experiment is to have a few images or download them from
from PIL import Imageimport requestsurl = "http://images.cocodataset.org/test-stuff2017/000000000448.jpg"image = Image.open(requests.get(url, stream=True).raw)
- Now that you have downloaded the image (a test-related image from the COCO dataset), you can easily see if you are using Jupyter Notebook or Colab by just running the
image

Figure 2.15 – A sample for testing CLIP (http://images.cocodataset.org/test-stuff2017/000000000448.jpg)
- The next step is to just create a prompt to be added for all the classes and then create inputs for the
prompt = "a photo of a "class_names = ["fighting", "meeting"]inputs = [prompt + class_name for class_name in class_names]
- Up to this point, the inputs for text and image are ready, but we need to load
from transformers import CLIPProcessor, CLIPModelmodel = (CLIPModel.from_pretrained("openai/clip-vit-large-patch14"))processor = \(CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14"))
- This processor is a wrapper that is very useful for tokenization. At the final step, you can hand the pre-processed and tokenized data to the model and finally get
inputs = processor(text=inputs, images=image,return_tensors="pt", padding=True)outputs = model(**inputs)logits = outputs.logits_per_imageprobs = logits_per_image.softmax(dim=1)
Logits have scores related to each combination (first prompt and image and second prompt and image) 10.9 and 18.5. However, to get the final class probabilities, a final SoftMax is applied to it and will give the results, which are probabilities in our case (0.99 for “meeting”).
Now that we know the basics of multimodal transformers, let’s see how we can use benchmarks and datasets in the next section.
Working with benchmarks and datasets
Section titled “Working with benchmarks and datasets”Thanks to the transformer architecture and transformer library, we are able to transfer what we have learned from a particular task to any other task, which is called transfer learning (TL). By transferring representations between related problems, we are able to train general-purpose models that share common linguistic knowledge across tasks. We can apply it since current deep learning approaches allow us to solve many tasks at the same time, also known as multitask learning (MTL), or in order, also known as sequential transfer learning (STL). Benchmarking mechanisms test the extent to which these capabilities are possessed by the LM.
Before introducing the datasets library, it is worth talking about important benchmarks such as General Language Understanding Evaluation (GLUE), Cross-lingual TRansfer Evaluation of Multilingual Encoders (XTREME), and Stanford Question Answering Dataset (SquAD). Benchmarking is especially critical for evaluating transfer learnings within multitask and multilingual environments. In ML, we mostly tend to focus on a particular metric, which is a performance score on a certain task or dataset. With these benchmarks, we can measure the transfer learning capacity of the language models when we try to solve many tasks at the same time.
Let’s start with the benchmarks.
Important benchmarks
Section titled “Important benchmarks”In the following subsections, we will introduce the important benchmarks that are widely used by transformer-based architectures. These benchmarks exclusively contribute a lot to MTL and to multilingual and zero-shot learning, including many challenging tasks. We will look at the following benchmarks:
- GLUE
- SuperGLUE
- XTREME
- XGLUE
- SQuAD
In order to use fewer pages, we only detail the tasks for the GLUE benchmark.
GLUE benchmark
Section titled “GLUE benchmark”Recent studies addressed the fact that multitask training approaches can achieve better results than single-task learning when using a particular model for a task. In this direction, the GLUE benchmark has been introduced for MTL, which is a collection of tools and datasets for evaluating the performance of MTL models across a list of tasks. It offers a public leaderboard for monitoring submission performance using the benchmark, along with a single-number metric summarizing 11 tasks. This benchmark includes many sentence-understanding tasks covering various datasets of differing sizes, text types, and difficulty levels. The tasks are categorized under three types, outlined as follows:
- Single-sentence tasks:
- The Corpus of Linguistic Acceptability (CoLA)dataset. This task consists of English acceptability judgments drawn from articles on linguistic theory.
- The Stanford Sentiment Treebank (SST-2) dataset. This task includes sentences from movie reviews and human annotations of their sentiment with
pos/neglabels.
- The Stanford Sentiment Treebank (SST-2) dataset. This task includes sentences from movie reviews and human annotations of their sentiment with
- The Corpus of Linguistic Acceptability (CoLA)dataset. This task consists of English acceptability judgments drawn from articles on linguistic theory.
- Similarity and paraphrase tasks:
- The Microsoft Research Paraphrase Corpus (MRPC) dataset. This task looks at whether the sentences in a pair are semantically equivalent.
- The Quora Question Pairs (QQP) dataset. It contains a pair of questions, and the task is to check if they are semantically identical.
- The Semantic Textual Similarity Benchmark (STS-B) dataset. The task involves a set of sentence pairs taken from news headlines, each with a similarity score ranging from 1 to 5.
- The Microsoft Research Paraphrase Corpus (MRPC) dataset. This task looks at whether the sentences in a pair are semantically equivalent.
- Inference tasks:
- The Multi-Genre Natural Language Inference (MNLI) corpus. It is a collection of sentence pairs, and the task is to predict the relation between premise and hypothesis (entailment, contradiction, or neither).
- The Question Natural Language Inference (QNLI) dataset. This is a converted version of SquAD. The task is to check whether a sentence contains the answer to a question.
- The Recognizing Textual Entailment (RTE) dataset. This is a task of textual entailment challenges to combine data from various sources. This dataset is similar to the previous QNLI dataset, where the task is to check whether a first text entails a second one.
- The Winograd Natural Language Inference (WNLI) schema challenge. This is originally a pronoun resolution task linking a pronoun and a phrase in a sentence. GLUE converted the problem into sentence-pair classification, as detailed next.
- The Multi-Genre Natural Language Inference (MNLI) corpus. It is a collection of sentence pairs, and the task is to predict the relation between premise and hypothesis (entailment, contradiction, or neither).
SuperGLUE benchmark
Section titled “SuperGLUE benchmark”Like Glue, SuperGLUE is a new benchmark styled with a new set of more difficult language-understanding tasks and currently offers a public leaderboard of around eight language tasks associated with a single-number performance metric similar to that of GLUE. The motivation behind it is that as of writing this book, the current state-of-the-art GLUE score (it is now 91.3 and was 90.8 at the time of the first edition of the book) surpasses human performance (87.1). Thus, SuperGLUE provides a more challenging and diverse task toward general-purpose, language-understanding technologies. However, it seems that now the models outperform SuperGLUE as well. While the human performance of SuperGLUE is 89.8, the current best model performance is 91.3.
You can access both GLUE and SuperGLUE benchmarks at gluebenchmark.com.
XTREME benchmark
Section titled “XTREME benchmark”In recent years, NLP researchers have increasingly focused on learning general-purpose representations rather than a single task that can be applied to many related tasks. Another way of building a general-purpose language model is by using multilingual tasks. It has been observed that recent multilingual models, such as Multilingual BERT (mBERT) and XLM-R, pre-trained on massive amounts of multilingual corpora, have performed better when transferring them to other languages. Thus, the main advantage here is that cross-lingual generalization enables us to build successful NLP applications in resource-poor languages through zero-shot cross-lingual transfer.
In this direction, the XTREME benchmark has been designed. It currently includes around 40 different languages belonging to 12 language families and includes nine different tasks that require reasoning for various levels of syntax or semantics. However, it is still challenging to scale up a model to cover over 7,000 world languages, and there exists a trade-off between language coverage and model capability. Please check out the following link for more details on this: https://sites.research.google/xtreme.
XGLUE benchmark
Section titled “XGLUE benchmark”XGLUE is another cross-lingual benchmark to evaluate and improve the performance of cross-lingual pretrained models for natural language understanding (NLU) and natural language generation (NLG). It originally consisted of 11 tasks over 19 languages. The main difference from XTREME is that the training data are only available in English for each task. This forces the language models to learn only from the textual data in English and transfer this knowledge to other languages, which is called zero-shot cross-lingual transfer capability. The second difference is that it has tasks for NLU and NLG at the same time. Please check out the following link for more details on this: https://microsoft.github.io/XGLUE/.
SQuAD benchmark
Section titled “SQuAD benchmark”SQuAD is a widely used QA dataset in the NLP field. It provides a set of QA pairs to benchmark the reading comprehension capabilities of NLP models. It consists of a list of questions, a reading passage, and an answer annotated by crowdworkers on a set of Wikipedia articles. The answer to the question is a span of text from the reading passage. The initial version, SQuAD1.1, doesn’t have an unanswerable option where the datasets are collected, so each question has an answer to be found somewhere in the reading passage. The NLP model is forced to answer the question even if this appears impossible. SQuAD2.0 is an improved version whereby the NLP models must not only answer questions when possible but should also abstain from answering when it is impossible to answer. SQuAD2.0 contains 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. Additionally, it also has 100,000 questions taken from SQuAD1.1.
Accessing the datasets with an application programming interface
Section titled “Accessing the datasets with an application programming interface”The datasets library provides a very efficient utility to load, process, and share datasets with the community through the Hugging Face hub. Like TensorFlow datasets, the datasets library makes it easier to download, cache, and dynamically load the sets directly from the original dataset host upon request. The library also provides evaluation metrics along with the data. Indeed, the hub does not hold or distribute the datasets. Instead, it keeps all information about the dataset, including the owner, preprocessing script, description, and download link. To see other features, please check the dataset_infos.json and DataSet-Name.py files of the corresponding dataset under the GitHub repository of the book (https://github.com/PacktPublishing/Mastering-Transformers-Second-Edition).
Let’s start by installing the dataset library as follows:
pip install datasetsThe following code automatically loads the cola dataset using the Hugging Face hub. The datasets.load_dataset() function downloads the loading script from the actual path if the data is not cached already:
from datasets import load_datasetcola = load_dataset('glue', 'cola')cola['train'][25:28]Important note
Reusability of the datasets: As you re-run the code, the datasets library starts caching your loading and manipulation request. It first stores the dataset and starts caching your operations on the dataset, such as splitting, selection, and sorting. You will see a warning message such as “reusing dataset xtreme (/home/savas/.cache/huggingface/dataset…)” or “loading cached sorted….”
In the preceding example, we downloaded the cola dataset from the GLUE benchmark and selected a few examples from the train split of it.
Currently, there are 19,298 datasets and 116 metrics (it was 661 NLP datasets and 21 metrics in the first edition of the book) for diverse tasks, as the following code snippet shows:
from pprint import pprintfrom datasets import list_datasets, list_metricsall_d = list_datasets()metrics = list_metrics()print(f"{len(all_d)} datasets and {len(metrics)} metrics \ exist in the hub\n")pprint(all_d[:20], compact=True)pprint(metrics, compact=True)This is the output:
19298 datasets and 116 metrics exist in the hub.['acronym_identification', 'ade_corpus_v2', 'adversarial_qa', 'aeslc', 'afrikaans_ner_corpus', 'ag_news', 'ai2_arc', 'air_dialogue', 'ajgt_twitter_ar', 'allegro_reviews', 'allocine', 'alt', 'amazon_polarity', 'amazon_reviews_multi', 'amazon_us_reviews', 'ambig_qa', 'amttl', 'anli', 'app_reviews', 'aqua_rat']['accuracy', 'BERTscore', 'bleu', 'bleurt', 'comet', 'coval', 'f1', 'gleu', 'glue', 'indic_glue', 'meteor', 'precision', 'recall', 'rouge', 'sacrebleu', 'sari', 'seqeval', 'squad', 'squad_v2', 'wer', 'xnli']A dataset might have several configurations. For instance, GLUE, as an aggregated benchmark, has many subsets, such as CoLA, SST-2, and MRPC, as we mentioned before. To access each GLUE benchmark dataset, we pass two arguments, where the first is glue and the second is a particular dataset of its example dataset (cola or sst2) that can be chosen. Likewise, the Wikipedia dataset has several configurations provided for several languages.
A dataset comes with the DatasetDict object, including several Dataset instances. When the split selection (split='...') is used, we get Dataset instances. For example, the CoLA dataset comes with DatasetDict, where we have three splits: train, validation, and test. While the train and validation datasets include two labels (1 for acceptable and 0 for unacceptable), the label value of the test split is -1, which means no label.
Let’s see the structure of the CoLA dataset object as follows:
cola = load_dataset('glue', 'cola')colaDatasetDict({train: Dataset({features: ['sentence', 'label', 'idx'], num_rows: 8551 })validation: Dataset({features: ['sentence', 'label', 'idx'], num_rows: 1043 })test: Dataset({ features: ['sentence', 'label', 'idx'], num_rows: 1063 })})cola['train'][12]{'idx': 12, 'label':1,'sentence':'Bill rolled out of the room.'}cola['validation'][68]{'idx': 68, 'label': 0, 'sentence': 'Which report that John was incompetent did he submit?'}cola['test'][20]{'idx': 20, 'label': -1, 'sentence': 'Has John seen Mary?'}The dataset object has some additional metadata information that might be helpful for us: split, description, citation, homepage, license, and info. Let’s run the following code:
print("1#",cola["train"].description)print("2#",cola["train"].citation)print("3#",cola["train"].homepage)1# GLUE, the General Language Understanding Evaluation benchmark(https://gluebenchmark.com/) is a collection of resources for training,evaluating, and analyzing natural language understanding systems.2# @article{warstadt2018neural, title={Neural Network Acceptability Judgments}, author={Warstadt, Alex and Singh, Amanpreet and Bowman, Samuel R}, journal={arXiv preprint arXiv:1805.12471}, year={2018}}@inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019}}3# https://nyu-mll.github.io/CoLA/The GLUE benchmark provides many datasets, as mentioned previously. Let’s download the MRPC dataset as follows:
mrpc = load_dataset('glue', 'mrpc')Likewise, to access other GLUE tasks, we will change the second parameter as follows:
load_dataset('glue', 'XYZ')In order to apply a sanity check of data availability, run the following piece of code:
glue=['cola', 'sst2', 'mrpc', 'qqp', 'stsb', 'mnli', 'mnli_mismatched', 'mnli_matched', 'qnli', 'rte', 'wnli', 'ax']for g in glue: _=load_dataset('glue', g)XTREME (working with a cross-lingual dataset) is another popular cross-lingual dataset that we already discussed. Let’s pick the MLQA example from the XTREME set. MLQA is a subset of the XTREME benchmark, which is designed to assess the performance of cross-lingual QA models. It includes about 5,000 extractive QA instances in the SQuAD format across seven languages, which are English, German, Arabic, Hindi, Vietnamese, Spanish, and Simplified Chinese.
For example, MLQA.en.de is an English-German QA example dataset and can be loaded as follows:
en_de = load_dataset('xtreme', 'MLQA.en.de')en_de DatasetDict({test: Dataset({features: ['id', 'title', 'context', 'question', 'answers'], num_rows: 4517}) validation: Dataset({ features: ['id', 'title', 'context', 'question', 'answers'], num_rows: 512})})It could be more convenient to view it within a pandas DataFrame:
import pandas as pdpd.DataFrame(en_de['test'][0:4])Here is the output of the preceding code:

Figure 2.16 – English-German cross-lingual QA dataset
Now, we are ready to manipulate the dataset instances!
Data manipulation using the datasets library
Section titled “Data manipulation using the datasets library”Datasets come with many dictionaries of subsets, where the split parameter is used to decide which subset(s) or portion of the subset is to be loaded. If this is none by default, it will return a dataset dictionary of all subsets (train, test, validation, or any other combination). If the split parameter is specified, it will return a single dataset rather than a dictionary. For the following example, we retrieve a train split of the cola dataset only:
cola_train = load_dataset('glue', 'cola', split ='train')We can get a mixture of the train and validation subsets as follows:
cola_sel = load_dataset('glue', 'cola', split = 'train[:300]+validation[-30:]')The split expression means that the first 300 examples of train and the last 30 examples of validation are obtained as cola_sel.
We can apply different combinations, as shown in the following split examples:
- The first 100 examples from
trainandvalidation, assplit='train[:100]+validation[:100]' - 50% of
trainand the last 30% ofvalidation, assplit='train[:50%]+validation[-30%:]' - The first 20% of
trainand the examples in the slice [30:50] fromvalidation, assplit='train[:20%]+validation[30:50]'
Now, we will see how to sort and shuffle the dataset!
Sorting, indexing, and shuffling
Section titled “Sorting, indexing, and shuffling”The following execution calls the sort() function of the cola_sel object. We see the first 15 and the last 15 labels:
cola_sel.sort('label')['label'][:15][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]cola_sel.sort('label')['label'][-15:][1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]We are already familiar with Python slicing notation. Likewise, we can also access several rows using similar slice notation or with a list of indices as follows:
cola_sel[6,19,44]{'idx': [6, 19, 44],'label': [1, 1, 1], 'sentence':['Fred watered the plants flat.', 'The professor talked us into a stupor.', 'The trolley rumbled through the tunnel.']}We shuffle the dataset as follows:
cola_sel.shuffle(seed=42)[2:5]{'idx': [159, 1022, 46],'label': [1, 0, 1],'sentence': ['Mary gets depressed if she listens to the Grateful Dead.','It was believed to be illegal by them to do that.','The bullets whistled past the house.']}Important note
Seed value: When shuffling, we need to pass a seed value to control the randomness and achieve a consistent output between the author and the reader.
Caching and reusability
Section titled “Caching and reusability”Using cached files allows us to load large datasets by means of memory mapping (if datasets fit on the drive) by using a fast backend. Such smart caching helps to save and reuse the results of operations executed on the drive. To see cache logs with regard to the dataset, run the following code:
cola_sel.cache_files[{'filename': '/home/savas/.cache/huggingface...,'skip': 0, 'take': 300}, {'filename': '/home/savas/.cache/huggingface...','skip': 1013, 'take': 30}]The output indicated that the data are already cached!
Dataset filter and map function
Section titled “Dataset filter and map function”We might want to work with a specific selection of a dataset. For instance, we can retrieve sentences only, including the term kick in the cola dataset, as shown in the following execution. The datasets.Dataset.filter() function returns sentences, including kick, where an anonymous function and a lambda keyword are applied:
cola_sel = load_dataset('glue', 'cola', split='train[:100%]+validation[-30%:]')cola_sel.filter(lambda s: "kick" in s['sentence'])["sentence"][:3]['Jill kicked the ball from home plate to third base.', 'Fred kicked the ball under the porch.', 'Fred kicked the ball behind the tree.']The following filtering is used to get positive (acceptable) examples from the set:
cola_sel.filter(lambda s: s['label']== 1 )["sentence"][:3]["Our friends won't buy this analysis, let alone the next one we propose.","One more pseudo generalization and I'm giving up.","One more pseudo generalization or I'm giving up."]In some cases, we might not know the integer code of a class label. Suppose we have many classes, and the code of the culture class is hard to remember out of 10 classes. Instead of giving the integer code 1, as with our preceding example, which is the code for acceptable, we can pass an acceptable label to the str2int() function as follows:
cola_sel.filter(lambda s: s['label']== \ cola_sel.features['label'].str2int('acceptable') )["sentence"][:3]This produces the same output as for the previous execution.
Processing data with the map function
Section titled “Processing data with the map function”The datasets.Dataset.map() function iterates over the dataset, applying a processing function to each example in the set, and it modifies the content of the examples. The following execution shows a new 'len' feature being added that denotes the length of a sentence:
cola_new=cola_sel.map(lambda e:{'len': \ len(e['sentence'])})pd.DataFrame(cola_new[0:3])This is the output of the preceding code snippet:

Figure 2.17 – Cola dataset with an additional column
As another example, the following piece of code cut the sentence after 20 characters. We do not create a new feature but, instead, update the content of the sentence feature as follows:
cola_cut=cola_new.map(lambda e: {'sentence': e['sentence'][:20]+ '_'})The output is shown in the following screenshot:

Figure 2.18 – Cola dataset with an update
This is enough to work with an already prepared dataset. Now, it is time to work with our real datasets.
Working with local files
Section titled “Working with local files”To load a dataset from local files in a comma-separated values (CSV), text (TXT), or JavaScript object notation (JSON) format, we pass the file type (csv, text, or json) to the generic load_dataset() loading script, as shown in the following code snippet. Under the ../data/ folder, there are three CSV files (a.csv, b.csv, and c.csv), which are randomly selected toy examples from the SST-2 dataset. We can load a single file, as shown in the data1 object, merge many files, as in the data2 object, or make dataset splits, as in data3:
from datasets import load_datasetdata1 = load_dataset('csv',data_files='../data/a.csv',delimiter="\t")data2 = load_dataset('csv',data_files=['../data/a.csv', '../data/b.csv', '../data/c.csv'],delimiter="\t")data3 = load_dataset('csv',data_files={ 'train':['../data/a.csv','../data/b.csv'], 'test':['../data/c.csv']}, delimiter="\t")In order to get the files in other formats, we pass json or text instead of csv, as follows:
data_json = load_dataset('json', data_files='a.json')data_text = load_dataset('text', data_files='a.txt')So far, we have discussed how to load, handle, and manipulate datasets that are either already hosted in the hub or are on our local drive. Now, we will study how to prepare datasets for transformer model training.
Preparing a dataset for model training
Section titled “Preparing a dataset for model training”Let’s start with the tokenization process. Each model has its own tokenization model that is trained before the actual language model. We will discuss it in detail in the next chapter. To use a tokenizer, we should install the Transformer library. The following example loads the tokenizer model from the pretrained distilBERT-base-uncased model. We use map and an anonymous function with lambda to apply a tokenizer to each split in data3. If batched is selected as True in the map function, it provides a batch of examples to the tokenizer function. The batch_size value is 1000 by default, which is the number of examples per batch passed to the function. If not selected, the whole dataset is passed as a single batch. The code can be seen here:
from Transformer import DistilBERTTokenizertokenizer = (DistilBERTTokenizer.from_pretrained( 'distilBERT-base-uncased'))encoded_data3 = data3.map(lambda e: tokenizer( e['sentence'], padding=True, truncation=True, max_length=12), batched=True, batch_size=1000)As shown in the following output, we see the difference between data3 and encoded_data3, where two additional features— attention_mask and input_ids —are added to the datasets accordingly. We already introduced these two features in the previous part in this chapter. Put simply, input_ids are the indices corresponding to each token in the sentence. They are expected features needed by the Trainer class of Transformer, which we will discuss in the next fine-tuning chapters.
We mostly pass several sentences at once (called a batch) to the tokenizer and further pass the tokenized batch to the model. To do so, we pad each sentence to the maximum sentence length in the batch or a particular maximum length specified by the max_length parameter— 12 in this toy example. We also truncate longer sentences to fit that maximum length. The code can be seen in the following snippet:
data3DatasetDict({train: Dataset({ features: ['sentence','label'], num_rows: 199 })test: Dataset({ features: ['sentence','label'], num_rows: 100 })})encoded_data3DatasetDict({train: Dataset({ features: ['attention_mask', 'input_ids', 'label', 'sentence'], num_rows: 199 })test: Dataset({features: ['attention_mask', 'input_ids', 'label', 'sentence'],num_rows: 100 })})print(encoded_data3['test'][12]){'attention_mask': [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 'input_ids': [101, 2019, 5186, 16010, 2143, 1012, 102, 0, 0, 0, 0, 0], 'label': 0, 'sentence': 'an extremely unpleasant film . '}We are done with the datasets library. Up to this point, we have evaluated all aspects of the datasets. We have covered GLUE-like benchmarking, where classification metrics are taken into consideration. In the next section, we will focus on how to benchmark computational performance for speed and memory rather than classification.
Benchmarking for speed and memory
Section titled “Benchmarking for speed and memory”Just comparing the classification performance of large models on a specific task or a benchmark might turn out to be no longer sufficient. We may need faster inference and memory performance. Thus, we must also consider the computational cost of a particular model for a given environment (random-access memory (RAM), CPU, and GPU) in terms of memory usage and speed. The computational cost of training and deploying to production for inference are the two main values to be measured. Two classes of the Transformer library, PyTorchBenchmark and TensorFlowBenchmark, make it possible to benchmark models for both TensorFlow and PyTorch.
Before we start our experiment, we need to check our GPU capabilities with the following execution:
import torchprint(f"The GPU total memory is \ {torch.cuda.get_device_properties(0).total_memory/(1024**3)} GB")The GPU total memory is 2.89 GBThe output is obtained from NVIDIA GeForce GTX 1050 (3 gigabytes (GB)). The Transformer library currently only supports single-device benchmarking. When we conduct benchmarking on a GPU, we are expected to indicate which GPU device the Python code will run on, which is done by setting the CUDA_VISIBLE_DEVICES environment variable. For example, export CUDA_VISIBLE_DEVICES=0 indicates that the first cuda device will be used.
In the following code example, we compare four randomly selected pretrained BERT models, as listed in the models array. We try different sequence lengths with the help of the sequence_lengths list parameter. We keep the batch size at 4. If you have a better GPU capacity, you can extend the parameter search space with batch values in the range 4–64 and with other parameters:
from transformers import PyTorchBenchmark, PyTorchBenchmarkArgumentsmodels= ["BERT-base-uncased", "distilBERT-base-uncased","distilroBERTa-base", "distilBERT-base-german-cased"]batch_sizes=[4]sequence_lengths=[32,64, 128, 256,512]args = PyTorchBenchmarkArguments(models=models, batch_sizes=batch_sizes, sequence_lengths=sequence_lengths, multi_process=False)benchmark = PyTorchBenchmark(args)Important note
Benchmarking for TensorFlow: The code examples are for PyTorch benchmarking in this part. For TensorFlow benchmarking, we simply use the TensorFlowBenchmarkArguments and TensorFlowBenchmark counterpart classes instead.
We are ready to conduct the benchmarking experiment by running the following code:
results = benchmark.run()This may take some time, depending on your CPU/GPU capacity and argument selection. If you face an out-of-memory problem for this, you should take the following actions to overcome it:
- Restart your kernel or your operating system.
- Delete all unnecessary objects in the memory before starting.
- Set a lower batch size, such as 2, or even 1.
The following output indicates the inference speed performance. Since our search space has four different models and five different sequence lengths, we see 20 rows in the results:

Figure 2.19 – Inference speed performance
Likewise, we see the inference memory usage for 20 different scenarios as follows:

Figure 2.20 – Inference memory usage
To observe memory usage across the parameters, we will plot them using the results object, which stores the statistics. The following execution will plot the time inference performance across models and sequence lengths:
import matplotlib.pyplot as pltplt.figure(figsize=(8,8))t=sequence_lengthsmodels_perf=[list( results.time_inference_result[m]['result'][batch_sizes[0]].values() ) for m in models]plt.xlabel('Seq Length')plt.ylabel('Time in Second')plt.title('Inference Speed Result')plt.plot(t, models_perf[0], 'rs--', t, models_perf[1], 'g--.', t, models_perf[2], 'b--^', t, models_perf[3], 'c--o')plt.legend(models)plt.show()As shown in the following screenshot, two DistilBERT models showed close results and performed better than other two models. The BERT-based-uncased model performs poorly compared to the others, especially as the sequence length increases:

Figure 2.21 – Inference speed result
To plot the memory performance, you need to use the memory_inference_result result of the results object instead of time_inference_result, as shown in the preceding code.
For more interesting benchmarking examples, please check out the following links:
- https://huggingface.co/transformers/benchmarks.html
- https://github.com/huggingface/transformers/tree/master/notebooks
Now that we are done with this section, we have successfully completed this chapter. Congratulations on achieving the installation, running your first hello-world transformer program, working with the datasets library, and benchmarking!
Summary
Section titled “Summary”In this chapter, we have covered a variety of introductory topics, and we also got our hands dirty with the hello-world transformer application. On the other hand, this chapter plays a crucial role in terms of applying what has been learned so far to the upcoming chapters. So, what has been learned so far? We took the first small step by setting up the environment and system installation. In this context, the anaconda package manager helped us to install the necessary modules for the main operating systems. We also went through language models, community-provided models, and tokenization processes. We have tested a very simple approach for zero-shot image classification using multimodal models and a very simple prompt. Additionally, we introduced multitask (GLUE) and cross-lingual benchmarking (XTREME), which enables these language models to become stronger and more accurate. The datasets library was introduced, which facilitates efficient access to NLP datasets provided by the community. Finally, we learned how to evaluate the computational cost of a particular model in terms of memory usage and speed. Transformers frameworks make it possible to benchmark models for both TensorFlow and PyTorch.
The models used in this section were already trained and shared with us by the community. Now, it is our turn to train a language model and disseminate it to the community. In the next chapter, we will learn how to train a BERT language model, as well as a tokenizer, and how to share them with the community.