Autoencoding Language Models
local graph
Chapter 3 — Autoencoding Language Models
Section titled “Chapter 3 — Autoencoding Language Models”In the previous chapter, we looked at and studied how a typical transformer model can be used by Hugging Face’s Transformers. All of the topics in this book so far have included instructions on how to use pre-trained or pre-built models and less information has been given about specific models and their training.
In this chapter, we will learn how we can train autoencoding language models on any given language from scratch. This training will include pretraining and task-specific training of the models. First, we will start with learning about the BERT model and how it works. Then, we will train the language model using a simple and small corpus. Afterward, we will look at how the model can be used inside any Keras model.
For an overview of what will be learned in this chapter, we will cover the following topics:
- Bidirectional Encoder Representations from Transformers (BERT) – one of the autoencoding language models
- Autoencoding language model training for any language
- Sharing models with the community
- Understanding other autoencoding models
- Working with tokenization algorithms
Technical requirements
Section titled “Technical requirements”The technical requirements for this chapter are as follows:
Anacondatransformers >=4.0.0pytorch >=1.0.2tensorflow >=2.4.0datasets >=1.4.1tokenizers
Please also check the corresponding GitHub code of Chapter 3 using https://github.com/PacktPublishing/Mastering-Transformers-Second-Edition.
BERT – one of the autoencoding language models
Section titled “BERT – one of the autoencoding language models”BERT was one of the first autoencoding language models to utilize the encoder Transformer stack with slight modifications for language modeling.
The BERT architecture is a multilayer Transformer encoder based on the original Transformer implementation. The Transformer model itself was originally made for machine translation tasks, but the main improvement made by BERT is the utilization of this part of the architecture to provide better language modeling. This language model, after pretraining, is able to provide a global understanding of the language it is trained on.
In the next subsections, you will learn about autoencoding models such as BERT. You will also learn how to pretrain a model and share it with a community. In the next section, BERT is explained in more detail.
BERT language model pretraining tasks
Section titled “BERT language model pretraining tasks”To have a clear understanding of the MLM used by BERT, let’s define it in more detail. MLM is the task of training a model on input (a sentence with some masked tokens) and obtaining the output as the whole sentence with the masked tokens filled. But how and why does it help a model to obtain better results on downstream tasks such as classification? The answer is simple: if the model can do a cloze test (a linguistic test for evaluating language understanding by filling in blanks), then it has a general understanding of the language itself. For other tasks, it has been pretrained (by language modeling) and will perform better.
Here’s an example of a cloze test: George Washington was the first President of the ___ States.
It is expected that “United” should fill in the blank. For a masked language model, the same task is applied, and it is required to fill in the masked tokens. However, masked tokens are selected randomly from a sentence.
Another task that BERT is trained on is Next Sentence Prediction (NSP). This pretraining task ensures that BERT learns not only the relations of all tokens to each other in predicting masked ones but also helps it understand the relation between two sentences. A pair of sentences is selected and given to BERT with a [SEP] splitter token in between. It is also known from the dataset whether the second sentence comes after the first one or not.
The following is an example of NSP: It is required that the reader fill in the blanks. Bitcoin prices are way over too high compared to other altcoins.
In this example, the model is required to predict it as negative (the sentences are not related to each other).
These two pretraining tasks enable BERT to have an understanding of the language itself. BERT token embeddings provide a contextual embedding for each token. Contextual embedding means each token has an embedding that is completely related to the surrounding tokens. Unlike word2vec and other such models, BERT provides better information for each token embedding. NSP tasks, on the other hand, enable BERT to have better embeddings for [CLS] tokens. This token, as was discussed in the first chapter, provides information about the whole input. [CLS] is used for classification tasks and, in the pretraining part, learns the overall embedding of the whole input. The following figure shows an overview of the BERT model and the respective input and output of the BERT model:

Figure 3.1 – The BERT model
Let’s move on to the next section!
A deeper look into the BERT language model
Section titled “A deeper look into the BERT language model”Tokenizers are one of the most important parts of many NLP applications in their respective pipelines. For BERT, WordPiece tokenization is used. Generally, WordPiece, SentencePiece, and byte pair encoding (BPE) are the three most widely known tokenizers, used by different Transformer-based architectures, which are also covered in the next sections. The primary differences lie in their merging strategies, unit representations (bytes, characters, or subword units), and their flexibility in tokenization schemes and segmentation modes. Each of these algorithms has its advantages and can be chosen based on the specific requirements of the task at hand. The main reason that BERT or any other Transformer-based architecture uses subword tokenization is the ability of such tokenizers to deal with unknown tokens.
BERT also uses positional encoding to ensure the position of the tokens is given to the model. If you recall from Chapter 1, BERT and similar models use non-sequential operations such as dense neural layers. Traditional models, such as LSTM- and RNN-based models, care the natural position In order to provide this extra information to BERT, positional encoding comes in handy.
The pretraining of BERT, such as autoencoding models, provides language-wise information for the model, but in practice, when dealing with different problems such as sequence classification, token classification, or question answering, different parts of the model output are used.
For example, in the case of a sequence classification task, such as sentiment analysis or sentence classification, it is proposed by the original BERT article that CLS embedding from the last layer must be used. However, other research performs classification using different techniques using BERT (using average token embedding from all tokens, deploying an LSTM over the last layer, or even using a CNN on top of the last layer). The last [CLS] embedding for sequence classification can be used by any classifier, but the proposed, and the most common one, is a dense layer with an input size equal to the final token embedding size and an output size equal to the number of classes with a softmax activation function. Using sigmoid is also another alternative when the output could be multilabel and the problem itself is a multilabel classification problem.
To give you more detailed information about how BERT actually works, the following diagram shows an example of an NSP task. Note that the tokenization is simplified here for better understanding:

Figure 3.2 – BERT example for an NSP task
The BERT model has different variations with different settings. For example, the size of the input is variable. In the preceding example, it is set to 512, and the maximum sequence size that the model can get as input is 512. However, this size includes special tokens, [CLS] and [SEP], so it will be reduced to 510. On the other hand, using WordPiece as a tokenizer yields subword tokens and the sequence size, before we can have fewer words, and, after tokenization, the size will increase because the tokenizer breaks words into subwords if they are not commonly seen in the pretrained corpus.
The following screenshot shows an illustration of BERT for different tasks. For an NER task, the output of each token is used instead of [CLS]. In the case of question answering, the question and the answer are concatenated using the [SEP] delimiter token, and the answer is annotated using “ Start/End ” and the span output from the last layer. In this case, Paragraph is the context that Question is asking about it:

Figure 3.3 – BERT model for various NLP tasks
Regardless of all of these tasks, the most important of BERT’s abilities is its contextual representation of text. The reason it is successful in various tasks is because of the Transformer encoder architecture that represents input in the form of dense vectors. These vectors can be easily transformed into output by very simple classifiers.
Positional encoding is essential in maintaining word order. It adds very small amounts of values to the word embeddings to ensure that they are semantically close to what they mean, but they also have a specific order.
Up to this point, you have learned about BERT and how it works. You have learned detailed information on various tasks that BERT can be used for and the important points of this architecture.
In the next section, you will learn how you can pretrain BERT and use it after training.
Autoencoding language model training for any language
Section titled “Autoencoding language model training for any language”We have discussed how BERT works and that it is possible to use the pretrained version of it provided by the Hugging Face repository. In this section, you will learn how to use the Hugging Face library to train your own BERT.
Before we start, it is essential to have good training data, because it will be used for the language modeling. This data is called the corpus, which is normally a huge pile of data (sometimes it is preprocessed and cleaned). This unlabeled corpus must be appropriate for the use case you wish to have your language model trained on; for example, if you are trying to have a special BERT for, let’s say, the English language. Although there are tons of huge, good datasets, such as Common Crawl (https://commoncrawl.org/), we would prefer a small one for faster training.
The IMDB dataset of 50 K movie reviews (available at https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews) is a large dataset for sentiment analysis, but small if you use it as a corpus for training your language model:
- You can easily download and save it in the
.txtformat for language model and tokenizer training by using theimport pandas as pdimdb_df = pd.read_csv("IMDB Dataset.csv")reviews = imdb_df.review.to_string(index=None)with open("corpus.txt", "w") as f:f.writelines(reviews) - After preparing the corpus, the tokenizer must be trained. The
tokenizerslibrary provides fast and easy training for the WordPiece tokenizer. In order to train it on your corpus, you must run thefrom tokenizers import BertWordPieceTokenizerbert_wordpiece_tokenizer =BertWordPieceTokenizer()bert_wordpiece_tokenizer.train("corpus.txt") - This will train the tokenizer. You can access the trained vocabulary by using the
get_vocab()function of the trained tokenizer object. You can get the vocabulary by using theThe following is the output:bert_wordpiece_tokenizer.get_vocab(){'almod': 9111, 'events': 3710, 'bogart': 7647, 'slapstick': 9541, 'terrorist': 16811, 'patter': 9269, '183': 16482, '##cul': 14292, 'sophie': 13109, 'thinki': 10265, 'tarnish': 16310, '##outh': 14729, 'peckinpah': 17156, 'gw': 6157, '##cat': 14290, '##eing': 14256, 'successfully': 12747, 'roomm': 7363, 'stalwart': 13347,...} - It is essential to save the tokenizer to be used afterward. Using the
save_model()function of the object and providing the directory will save the tokenizer vocabulary forbert_wordpiece_tokenizer.save_model("tokenizer") - You can reload it by using the
from_file()tokenizer = \BertWordPieceTokenizer.from_file("tokenizer/vocab.txt") - You can use the tokenizer by following
The special [tokenized_sentence = \tokenizer.encode("Oh it works just fine")tokenized_sentence.tokens['[CLS]', 'oh', 'it', 'works', 'just', 'fine','[SEP]']
CLS] and [SEP] tokens will be automatically added to the list of tokens because BERT needs them for processing input. - Let’s try another sentence using
tokenized_sentence = \tokenizer.encode("ohoh i thougt it might be workingg well")['[CLS]', 'oh', '##o', '##h', 'i', 'thoug', '##t', 'it', 'might', 'be', 'working', '##g', 'well', '[SEP]']
- It seems like a good tokenizer for noisy and misspelled text. Now that you have your tokenizer ready and saved, you can train your own BERT. The first step is to use
BertTokenizerFastfrom the Transformers library. You are required to load the trained tokenizer from the previous step by using theWe have usedfrom transformers import BertTokenizerFasttokenizer = BertTokenizerFast.from_pretrained("tokenizer")BertTokenizerFastbecause it is suggested by the Hugging Face documentation. There is alsoBertTokenizer, which, according to the definition from the library documentation, is not implemented as fast as the fast version. In most of the pretrained models’ documentation and cards, it is highly recommended to use theBertTokenizerFastversion. - The next step is preparing the corpus for faster training by using the
from transformers import LineByLineTextDatasetdataset = \LineByLineTextDataset(tokenizer=tokenizer,file_path="corpus.txt",block_size=128)
- You must provide a data collator
The data collator gets the data and prepares it for the training. For example, the preceding data collator takes data and prepares it for MLM with a probability offrom transformers import DataCollatorForLanguageModelingdata_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer,mlm=True,mlm_probability=0.15)
0.15. The purpose of using such a mechanism is to do the preprocessing on the fly, which makes it possible to use fewer resources. On the other hand, it slows down the training process because each sample has to be preprocessed on the fly at training time. - The training arguments also provide information for the trainer in the training phase, which can be set by using the
from transformers import TrainingArgumentstraining_args = TrainingArguments(output_dir="BERT",overwrite_output_dir=True,num_train_epochs=1,per_device_train_batch_size=128)
- We’ll now make the BERT model itself, which we are going to use with the default configuration (the number of attention heads, Transformer encoder layers, and
from transformers import BertConfig, BertForMaskedLMbert = BertForMaskedLM(BertConfig())
- The final step is to make a
from transformers import Trainertrainer = Trainer(model=bert,args=training_args,data_collator=data_collator,train_dataset=dataset)
- Finally, you can train your language model using the
It will show you a progress bar indicating the progress made in training:trainer.train()
Figure 3.4 – BERT model training progress
During the model training, a log directory called runs will be used to store the checkpoint in steps:

Figure 3.5 – BERT model checkpoints
- After the training is finished, you can easily save the model using the
Up to this point, you have learned how you can train BERT from scratch for any specific language that you desire. You’ve learned how to train the tokenizer and BERT model using the corpus you have prepared.trainer.save_model("MyBERT")
- The default configuration that you provided for BERT is the most essential part of this training process because it defines the architecture of BERT and its hyperparameters. You can take a peek at these parameters by using the
The following is the output:from transformers import BertConfigBertConfig()

Figure 3.6 – BERT model configuration
If you wish to replicate tiny, mini, small, base, and relative models from the original BERT configurations (https://github.com/google-research/bert), you can change these settings:

Figure 3.7 – BERT model configurations
Note that changing these parameters, especially max_position_embedding, num_attention_heads, num_hidden_layers, intermediate_size, and hidden_size, directly affects the training time. Increasing them dramatically increases the training time for a large corpus.
- For example, you can easily make a new configuration for a tiny version of BERT for faster training using the
The following is the result of the code:tiny_bert_config = \BertConfig(max_position_embeddings=512,hidden_size=128,num_attention_heads=2,num_hidden_layers=2,intermediate_size=512)tiny_bert_config

Figure 3.8 – Tiny BERT model configuration
- By using the same method, we can make a tiny BERT model using
tiny_bert = BertForMaskedLM(tiny_bert_config)
- Using the same parameters for training, you can train this tiny
The following is the output:trainer = Trainer(model=tiny_bert, args=training_args,data_collator=data_collator,train_dataset=dataset)trainer.train()
Figure 3.9 – Tiny BERT model configuration
It is clear that the training time has dramatically decreased, but you should be aware that this is a tiny version of BERT with fewer layers and parameters, which is not as good as the BERT base model.
Up to this point, you have learned how to train your own model from scratch, but it is essential to note that using the Datasets library is a better choice when dealing with datasets for training language models or leveraging it to perform task-specific training.
- The BERT language model can also be used as an embedding layer combined with any deep learning model. For example, you can load any pretrained BERT model or your own version that has been trained in Step 19. The following code shows how you must load it to be used in a
from transformers import (TFBertModel, BertTokenizerFast)bert = TFBertModel.from_pretrained("bert-base-uncased")tokenizer = \BertTokenizerFast.from_pretrained("bert-base-uncased")
- You do not need the whole model; instead, you can access the layers by using the
bert.layers[<Transformers.models.bert.modeling_tf_bert.TFBertMainLayer at 0x7f72459b1110>]
- As you can see, there is just a single layer from
TFBertMainLayer, which you can access within your Keras model. However, before using it, it is nice to test it and see what kind of outputThe output is as follows:tokenized_text = tokenizer.batch_encode_plus(["hello how is it going with you","lets test it"],return_tensors="tf",max_length=256,truncation=True,pad_to_max_length=True)bert(tokenized_text)
Figure 3.10 – BERT model output
As can be seen from the result, there are two outputs: one for the last hidden state and one for the pooler output. The last hidden state provides all token embeddings from BERT with additional [CLS] and [SEP] tokens at the start and end, respectively.
- Now that you have learned more about the TensorFlow version of BERT, you can make a Keras model using this
from tensorflow import kerasimport tensorflow as tfmax_length = 256tokens = keras.layers.Input(shape=(max_length,),dtype=tf.dtypes.int32)masks = keras.layers.Input(shape=(max_length,),dtype=tf.dtypes.int32)embedding_layer = bert.layers[0]([tokens,masks])[0][:,0,:]dense = tf.keras.layers.Dense(units=2,activation="softmax")(embedding_layer)model = keras.Model([tokens,masks],dense)
- The
modelobject, which is a Keras model, has two inputs: one for tokens and one for masks. Tokens haveinputs_idsfrom the tokenizer output and the masks will haveattention_mask. Let’s try it and seetokenized = tokenizer.batch_encode_plus(["hello how is it going with you","hello how is it going with you"],return_tensors="tf",max_length= max_length,truncation=True,pad_to_max_length=True) - It is important to use
max_length, truncation, andpad_to_max_lengthwhen using a tokenizer. These parameters make sure that you have the output in a usable shape by padding it to the maximum length of256, which was defined before. Now, you can run the model using this sample:The following is the output:model([tokenized["input_ids"],tokenized["attention_mask"]])
Figure 3.11 – BERT model classification output
- When training the model, you need to compile it using the
compileThe output is as follows:model.compile(optimizer="Adam",loss="categorical_crossentropy",metrics=["accuracy"])model.summary()
Figure 3.12 – BERT model summary
- From the model summary, you can see that the model has 109,483,778 trainable parameters, including BERT. However, if you have your BERT model pretrained and you want to freeze it in task-specific training, you can do so with the
As far as we know, the layer index of the embedding layer ismodel.layers[2].trainable = False
2, so we can simply freeze it. If you rerun thesummaryfunction, you will see that the trainable parameters are reduced to 1,538 which is the number of parameters of the last layer:
Figure 3.13 – BERT model summary with fewer trainable parameters
- As you recall, we used the IMDB sentiment analysis dataset for training the language model. Now, you can use it for training the Keras-based model for sentiment analysis. But first, you need to prepare the input
import pandas as pdimdb_df = pd.read_csv("IMDB Dataset.csv")reviews = list(imdb_df.review)tokenized_reviews = tokenizer.batch_encode_plus(reviews, return_tensors="tf",max_length=max_length,truncation=True,pad_to_max_length=True)import numpy as nptrain_split = int(0.8 *len(tokenized_reviews["attention_mask"]))train_tokens = tokenized_reviews["input_ids"][:train_split]test_tokens = tokenized_reviews["input_ids"][train_split:]train_masks = tokenized_reviews["attention_mask"][:train_split]test_masks = tokenized_reviews["attention_mask"][train_split:]sentiments = list(imdb_df.sentiment)labels = np.array([[0,1] if sentiment == "positive" else\[1,0] for sentiment in sentiments])train_labels = labels[:train_split]test_labels = labels[train_split:]
- Finally, your data is ready, and you can fit
After fitting the model, your model is ready to be used. Up to this point, you have learned how to perform model training for a classification task. You have learned how to save it, and in the next section, you will learn how it is possible to share the trained model with the community.model.fit([train_tokens,train_masks], train_labels, epochs=5)
Sharing models with the community
Section titled “Sharing models with the community”Trained models can be easily shared with the community. This provides more visibility for your work. Hugging Face provides a very easy-to-use model-sharing mechanism:
- You can simply use the following
clitool toTransformers-cli login - After you’ve logged in using your own credentials, you can create
Transformers-cli repo create a-fancy-model-name
- You can put any model name for the
a-fancy-model-nameparameter, and then it is essential to make sure you havegit-lfs:Git LFS is a Git extension used for handling large files. Hugging Face pretrained models are usually large files that require extra libraries such as LFS to be handled by Git.git lfs install - Then, you can clone the repository you have
git clone https://huggingface.co/username/a-fancy-model-name
- Afterward, you can add and remove from the repository as you like, and then, just like Git usage, you have to run the
git add . && git commit -m "Update from $USER"git push
Autoencoding models rely on the left encoder side of the original Transformer and are highly efficient at solving classification problems. Even though BERT is a typical example of an autoencoding model, there are many alternatives discussed in the literature. Let’s take a look at these important alternatives.
Other autoencoding models
Section titled “Other autoencoding models”In this part, we will review autoencoding model alternatives that slightly modify the original BERT. These alternative re-implementations aim to get better downstream tasks by exploiting many sources: optimizing the pretraining process and the number of layers or heads, improving data quality, designing better objective functions, and so forth. The source of improvements roughly falls into two parts: better architectural design choice and pretraining control.
Many effective alternatives have been shared lately, so it is impossible to understand and explain them all here. We can take a look at some of the most cited models in the literature and the most used ones on NLP benchmarks. Let’s start with A Lite BERT (ALBERT) as a re-implementation of BERT that focuses especially on architectural design choice.
Introducing ALBERT
Section titled “Introducing ALBERT”The performance of language models is considered to improve as their size gets bigger. However, training such models is getting more challenging due to both memory limitations and longer training times. To address these issues, the Google team proposed the ALBERT model, which is indeed a reimplementation of the BERT architecture by utilizing several new techniques that reduce memory consumption and increase the training speed. The new design led to the language models scaling much better than the original BERT. Along with 18 times fewer parameters, ALBERT trains 1.7 times faster than the original BERT large model.
The ALBERT model mainly consists of three modifications of the original BERT:
- Factorized embedding parameterization
- Cross-layer parameter sharing
- Inter-sentence coherence loss
The first two modifications are parameter-reduction methods that are related to the issue of model size and memory consumption in the original BERT. The third corresponds to a new objective function: Sentence-Order Prediction (SOP), replacing the NSP task of the original BERT, which led to a much thinner model and improved performance.
Factorized embedding parameterization is used to decompose the large vocabulary-embedding matrix into two smaller matrices. These matrices separate the size of the hidden layers from the size of the vocabulary. This decomposition reduces the embedding parameters from O(V × H) to O(V × E + E × H) where V is vocabulary, H is hidden layer size, and E is embeddings, which leads to more efficient usage of the total model parameters if H E is satisfied.
For instance, let’s consider the following example: In the ALBERT large model, the value of H is 1026, and the size of V is 30000. In this case, assuming that the E value is 128, which satisfies the H>>E condition. The VxH value is approximately 30 M (1026 x 30,000). However, (30,000 × 128 + 128 x 1026) is around 4 M. This leads to a model that is ten times more efficient.
Cross-layer parameter sharing prevents the total number of parameters from increasing as the network gets deeper. The technique is considered another way to improve parameter efficiency since we can keep the parameter size smaller by sharing or copying. In the original paper, they experimented with many ways to share parameters, such as either sharing FF-only parameters across layers or sharing attention-only parameters or entire parameters.
The other modification of ALBERT is inter-sentence coherence loss. As we already discussed, the BERT architecture takes advantage of two loss calculations: the MLM loss and NSP. NSP comes with binary cross-entropy loss for predicting whether or not two segments appear in a row in the original text. The negative examples are obtained by selecting two segments from different documents. However, the ALBERT team criticized NSP for being a topic detection problem, which is considered a relatively easy problem. Therefore, the team proposed a loss based primarily on coherence rather than topic prediction.
The SOP loss was utilized in this case. This loss function prioritizes the modeling of coherence between sentences rather than focusing on topic classification. It employs a similar technique to BERT for positive examples, using two consecutive segments from the same document. For negative examples, it uses the same two consecutive segments but with their order swapped. This approach enables the model to learn more nuanced distinctions between coherence properties at the discourse level.
Now, let’s dive into more detail and see how it works in practice:
- Let’s compare the original BERT and ALBERT configuration with the
Transformerslibrary. The following piece of code shows how you can configure a BERT-Base initial model. As you see in the output, the number of parameters is around#BERT-BASE (L=12, H=768, A=12, Total Parameters=110M)from transformers import BertConfig, BertModelbert_base= BertConfig()model = BertModel(bert_base)print(f"{model.num_parameters() /(10**6)} million parameters")109.48224 million parameters - The following piece of code shows how you can define the ALBERT model with two classes,
AlbertConfigandAlbertModel, from theTransformerslibrary:As a result, the default ALBERT configuration points to# Albert-base Configurationfrom transformers import AlbertConfig, AlbertModelalbert_base = AlbertConfig(hidden_size=768,num_attention_heads=12,intermediate_size=3072,)model = AlbertModel(albert_base)print(f"{model.num_parameters() /(10**6)}\million parameters")'11.683584 million parametersAlbert-xxlarge. We need to set the hidden size, the number of attention heads, and the intermediate size to fit the ALBERT base model. The code shows the ALBERT base model as 11 M, which is 10 times smaller than the BERT base model. The original paper on ALBERT reported benchmarking as in the following table:
Figure 3.14 – ALBERT model benchmarking
- From this point on, in order to train an ALBERT language model from scratch, we need to go through similar phases to those we already illustrated in BERT training in the previous section, titled A deeper look into the BERT language model, by using the uniform Transformers API. There’s no need to explain the same steps here! Instead, let’s load an already-trained ALBERT language model
from transformers import AlbertTokenizer, AlbertModeltokenizer = \AlbertTokenizer.from_pretrained("albert-base-v2")model = AlbertModel.from_pretrained("albert-base-v2")text = "The cat is so sad ."encoded_input = tokenizer(text, return_tensors='pt')output = model(**encoded_input)
- The preceding pieces of code download the ALBERT model weights and their configuration from the Hugging Face hub or our local cache directory if already cached, which means you’ve already called the
AlbertTokenizer.from_pretrained()function before. Since themodelobject is a pre-trained language model, the things we can do with this model are limited for now. We need to train it on a downstream task to be able to use it for inference, which will be the main subject of further chapters. Instead, we can take advantage of its masked language model objectiveThe following is the output:from transformers import pipelinefillmask= pipeline('fill-mask',model='albert-base-v2')pd.DataFrame(fillmask("The cat is so [MASK] ."))
Figure 3.15 – The fill-mask output results for albert-base-v2
The fill-mask pipeline computes the scores for each vocabulary token with the softmax() function and sorts the most probable tokens, where cute is the winner with a probability score of 0.281. You may notice that entries in the token_str column start with the _ character, which is due to the metaspace component of the tokenizer of ALBERT.
Let’s take a look at the next alternative, Robustly Optimized BERT Pretraining Approach (RoBERTa), which mostly focuses on the pretraining phase.
RoBERTa
Section titled “RoBERTa”RoBERTa is another popular BERT reimplementation. It has provided many more improvements in training strategy than architectural design. It outperformed BERT in many tasks on GLUE. Dynamic masking is one of its original design choices. Although static masking is better for some tasks, the RoBERTa team showed that dynamic masking can perform well for overall performance. Let’s discuss the changes made to BERT to get RoBERTa and summarize all of its features.
The changes in architecture are as follows:
- Removing the NSP training objective
- Dynamically changing the masking patterns instead of static masking, which is done by generating masking patterns whenever they feed a sequence to the model
- BPE sub-word tokenizer
The changes in training are as follows:
- Controlling the training data: More data is used, such as 160 GB instead of the 16 GB originally used in BERT. Not only the size of the data but the quality and diversity were taken into consideration in the RoBERTa Model.
- Longer iterations of up to 500 K pretraining steps.
- A longer batch size.
- Longer sequences, which lead to less padding.
- A large 50 K BPE vocabulary instead of a 30 K BPE vocabulary.
Thanks to the Transformers uniform API, as in the preceding ALBERT model pipeline, we initialize the RoBERTa model as follows:
from transformers import RobertaConfig, RobertaModelconf= RobertaConfig()model = RobertaModel(conf)print(f"{model.num_parameters() /(10**6)} million parameters")109.48224 million parametersIn order to load the pretrained model, we execute the following pieces of code:
from transformers import RobertaTokenizer, RobertaModeltokenizer = \ RobertaTokenizer.from_pretrained('roberta-base')model = RobertaModel.from_pretrained('roberta-base')text = "The cat is so sad ."encoded_input = tokenizer(text, return_tensors='pt')output = model(**encoded_input)These lines illustrate how the model processes a given text. The output representation at the last layer is not useful at the moment. As we’ve mentioned several times, we need to fine-tune the main language models. The following execution applies the fill-mask function using the roberta-base model:
from transformers import pipelinefillmask= pipeline("fill-mask ",model="roberta-base", tokenizer=tokenizer)pd.DataFrame(fillmask("The cat is so <mask> ."))The following is the output:

Figure 3.16 – The fill-mask task results for roberta-base
Like the previous ALBERT fill-mask model, this pipeline ranks the suitable candidate words. Please ignore the Ġ prefix in the tokens – that is an encoded space character produced by the byte-level BPE tokenizer, which we will discuss later. You should have noticed that we used the [MASK] and <mask> tokens in the ALBERT and RoBERTa pipeline in order to hold the place for a masked token. This is because of the configuration of the tokenizer. To learn which token expression will be used, you can check tokenizer.mask_token. Please see the following execution:
tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')print(tokenizer.mask_token)[MASK]tokenizer = RobertaTokenizer.from_pretrained('roberta-base')print(tokenizer.mask_token)<mask>To ensure proper mask token use, we can add the fillmask.tokenizer.mask_token expression in the pipeline as follows:
fillmask(f"The cat is very {fillmask.tokenizer.mask_token}.")In the next section, you will learn more about ELECTRA and how it works.
ELECTRA
Section titled “ELECTRA”The ELECTRA model (proposed by Kevin Clark et al. in 2020) focuses on a new masked language model utilizing the replaced token detection training objective. During pre-training the model is forced to learn to distinguish real input tokens from synthetically generated replacements where the synthetic negative example is sampled from plausible tokens rather than randomly sampled tokens. The ALBERT model criticized the NSP objective of BERT for being a topic detection problem and using low-quality negative examples. ELECTRA trains two neural networks, a generator and a discriminator, so that the former produces high-quality negative examples, whereas the latter distinguishes the original token from the replaced token. We know GAN networks from the field of computer vision, in which the G generator produces fake images and tries to fool the D discriminator, and the discriminator network tries to avoid being fooled. The ELECTRA model applies almost the same generator-discriminator approach to replace original tokens with high-quality negative examples that are plausible replacements but synthetically generated.
In order to not repeat the same code with other examples, we only provide a simple fill-mask example for the ELECTRA generator as follows:
fillmask = \ pipeline("fill-mask", model="google/electra-small-generator")fillmask(f"The cat is very \{fillmask.tokenizer.mask_token} .")You can see the entire list of models at https://huggingface.co/Transformers/model_summary.html.
The model checkpoints can be found at https://huggingface.co/models.
DeBERTa
Section titled “DeBERTa”When we look at the GLUE and SuperGLUE NLP benchmarks, we can say that the Decoding-Enhanced BERT with Disentangled Attention (DeBERTa) model has received great attention. It has also given successful results in many academic and industrial projects recently. The following two techniques of DeBERTa have an effect on performance:
- Disentangled attention mechanism: This is based on the assumption that the importance of a word pair is determined by both its content and its relative position. The dependency between words becomes much stronger when they are used side by side rather than when they are used in different sentences.
- Enhanced mask decoder: In the
softmaxlayer, the vanilla BERT model decodes masked words based on aggregated contextual vectors of word contents and position. DeBERTa includes absolute word position embeddings just before the softmax layer.
DeBERTa is supported by Hugging Face’s transformers library, as shown in the following initialization code:
from transformers import DebertaConfig, DebertaModelconfiguration = DebertaConfig()model = DebertaModel(configuration)configuration = model.configWell done! We’ve finally completed the autoencoding model part. Now, we’ll move on to tokenization algorithms, which have an important effect on the success of Transformers.
Working with tokenization algorithms
Section titled “Working with tokenization algorithms”In the opening part of the chapter, we trained the BERT model using a specific tokenizer, namely BertWordPieceTokenizer. Now, it is worth discussing the tokenization process in detail here. Tokenization is a way of splitting textual input into tokens and assigning an identifier to each token before feeding the neural network architecture. The most intuitive way to do this is to split the sequence into smaller chunks in terms of space. However, such approaches do not meet the requirements of some languages, such as Japanese, and also may lead to huge vocabulary problems. Almost all Transformer models leverage subword tokenization not only for reducing dimensionality but also for encoding rare (or unknown) words not seen in training. The tokenization relies on the idea that every word, including rare words or unknown words, can be decomposed into meaningful smaller chunks that are widely seen symbols in the training corpus.
Some traditional tokenizers developed within Moses and the nltk library apply advanced rule-based techniques. However, the tokenization algorithms that are used with Transformers are based on self-supervised learning and extract the rules from the corpus. Simple intuitive solutions for rule-based tokenization are based on using characters, punctuation, or whitespace. Character-based tokenization causes language models to lose the input meaning. Even though it can reduce the vocabulary size, which is good, it makes it hard for the model to capture the meaning of “cat” by means of the encodings of the characters “c,” “a,” and “t.” Moreover, the dimension of the input sequence becomes very large. Likewise, punctuation-based models cannot treat some expressions, such as haven’t or ain’t, properly.
Recently, several advanced subword tokenization algorithms, such as BPE, have become an integral part of Transformer architectures. These modern tokenization procedures consist of two phases: The pre-tokenization phase, which simply splits the input into tokens either using space or language-dependent rules, and the tokenization training phase, which trains the tokenizer and builds a base vocabulary of a reasonable size based on tokens. Before training our own tokenizers, let’s load a pre-trained tokenizer. The following code loads a Turkish tokenizer, which is of the BertTokenizerFast type, from the Transformers library with a vocabulary size of 32 K:
from transformers import AutoModel, AutoTokenizertokenizerTUR = AutoTokenizer.from_pretrained( "dbmdz/bert-base-turkish-uncased")print(f"VOC size is: {tokenizerTUR.vocab_size}")print(f"The model is: {type(tokenizerTUR)}")VOC size is: 32000The model is: Transformers.models.bert.tokenization_bert_fast.BertTokenizerFastThe following code loads an English BERT tokenizer for the bert-base-uncased model:
from transformers import AutoModel, AutoTokenizertokenizerEN = \ AutoTokenizer.from_pretrained("bert-base-uncased")print(f"VOC size is: {tokenizerEN.vocab_size}")print(f"The model is {type(tokenizerEN)}")VOC size is: 30522The model is ... BertTokenizerFastLet’s see how they work! We tokenize the word “telecommunication” with these two tokenizers:
word_en="telecommunication"print(f"is in Turkish Model ? {word_en in tokenizerTUR.vocab}")print(f"is in English Model ? {word_en in tokenizerEN.vocab}")is in Turkish Model ? Falseis in English Model ? TrueThe word_en token is already in the vocabulary of the English tokenizer but not in that of the Turkish one. So, let’s see what happens with the Turkish tokenizer:
tokens=tokenizerTUR.tokenize(word_en)tokens['tel', '##eco', '##mm', '##un', '##ica', '##tion']Since the Turkish tokenizer model has no such a word in its vocabulary, it needs to break the word into parts that make sense to it. All these split tokens are already stored in the model vocabulary. Please notice the output of the following execution:
[t in tokenizerTUR.vocab for t in tokens][True, True, True, True, True, True]Let’s tokenize the same word with the English tokenizer that we already loaded:
tokenizerEN.tokenize(word_en)['telecommunication']Since the English model has the word “telecommunication” in its base vocabulary, it does not need to break it into parts but rather takes it as a whole. By learning from the corpus, the tokenizers are capable of transforming a word into mostly grammatically logical subcomponents. Let’s take a difficult example from Turkish. As an agglutinative language, Turkish allows us to add many suffixes to a word stem to construct very long words. Here is one of the longest words in the Turkish language used in a text (https://en.wikipedia.org/wiki/Longest_word_in_Turkish):
Muvaffakiyetsizleştiricileştiriveremeyebileceklerimizdenmişsinizcesine
It means, “As though you happen to have been from among those whom we will not be able to make a maker of unsuccessful ones easily/quickly.” The Turkish BERT tokenizer may not have seen this word in training, but it has seen its pieces; muvaffak (successful) as the stem, iyet (successfulness), siz (unsuccessfulness), leş (become unsuccessful), and so forth. The Turkish tokenizer extracts components that seem to be grammatically logical for the Turkish language when comparing the results with a Wikipedia article:
print(tokenizerTUR.tokenize(long_word_tur))['muvaffak', '##iyet', '##siz', '##les', '##tir', '##ici', '##les', '##tir', '##iver', '##emeye', '##bilecekleri', '##mi', '##z', '##den', '##mis', '##siniz', '##cesine']The Turkish tokenizer is an example of the WordPiece algorithm since it works with a BERT model. Almost all language models, including BERT, DistilBERT, and ELECTRA, require a WordPiece tokenizer.
Now, we are ready to take a look at the tokenization approaches used with Transformers. First, we’ll discuss the widely used tokenization of BPE, WordPiece, and SentencePiece a bit, and then train them with Hugging Face’s fast tokenizers library.
BPE is a data compression technique. It scans the data sequence and iteratively replaces the most frequent pair of bytes with a single symbol. It was first adapted and proposed in Neural Machine Translation of Rare Words with Subword Units (Sennrich et al. 2015), to solve the problem of unknown words and rare words for machine translation. Currently, it is successfully being used within GPT-2 and many other state-of-the-art models. Many modern tokenization algorithms are based on such compression techniques.
It represents text as a sequence of character n-grams, which are also called character-level subwords. The training starts initially with a vocabulary of all Unicode characters (or symbols) seen in the corpus. This can be small for English but can be large for character-rich languages such as Japanese. Then, it iteratively computes character bigrams and replaces the most frequent ones with special new symbols. For example, t and h are frequently occurring symbols. We replace consecutive symbols with the th symbol. This process is kept iteratively running until the vocabulary has attained the desired vocabulary size. The most common vocabulary size is around 30 K.
BPE is particularly effective at representing unknown words. However, it may not guarantee the handling of rare words and/or words including rare subwords. In such cases, it associates rare characters with a special symbol, <UNK>, which may lead to losing meaning in words a bit. As a potential solution, byte-level BPE (BBPE) has been proposed, which uses a 256-byte set of vocabulary instead of Unicode characters to ensure that every base character is included in the vocabulary.
WordPiece tokenization
Section titled “WordPiece tokenization”WordPiece is another popular word segmentation algorithm widely used with BERT, DistilBERT, and ELECTRA. It was proposed by Schuster and Nakajima to solve the Japanese and Korean voice problem in 2012. The motivation behind this work was that, although not a big issue for the English language, word segmentation is important preprocessing for many Asian languages, because in these languages spaces are rarely used. Therefore, we come across word segmentation approaches in NLP studies in Asian languages more often. Similar to BPE, WordPiece uses a large corpus to learn vocabulary and merging rules. While BPE and BBPE learn the merging rules based on co-occurrence statistics, the WordPiece algorithm uses maximum likelihood estimation to extract the merging rules from a corpus. It first initializes the vocabulary with Unicode characters, which are also called vocabulary symbols. It treats each word in the training corpus as a list of symbols (initially Unicode characters), and then it iteratively produces a new symbol merging two symbols out of all the possible candidate symbol pairs based on the likelihood maximization rather than frequency. This production pipeline continues until the desired vocabulary size is reached.
Sentence piece tokenization
Section titled “Sentence piece tokenization”Previous tokenization algorithms treat text as a space-separated word list. This space-based splitting does not work in some languages. In the German language, compound nouns are written without spaces, for example, “ Menschenrechte ” (human rights). The solution is to use language-specific pre-tokenizers. In German, an NLP pipeline leverages a compound-splitter module to check whether a word can be subdivided into smaller words. However, East Asian languages (for example, Chinese, Japanese, Korean, and Thai) do not use spaces between words. The SentencePiece algorithm is designed to overcome this space limitation, which is a simple and language-independent tokenizer proposed by Kudo et al. in 2018. It treats the input as a raw input stream where space is part of the character set. The tokenizer using SentencePiece produces the _ character, which is also why we saw _ in the output of the ALBERT model example earlier. Other popular language models that use SentencePiece are XLNet, Marian, and T5.
So far, we have discussed subword tokenization approaches. It is time to start conducting experiments for training with the tokenizers library.
The tokenizers library
Section titled “The tokenizers library”You may have noticed that the already-trained tokenizers for Turkish and English are part of the Transformers library in the previous code examples. On the other hand, the Hugging Face team provided the tokenizers library independently from the Transformers library to be fast and give us more freedom. The library was originally written in Rust, which makes multi-core parallel computations possible, and is wrapped in Python (https://github.com/huggingface/tokenizers).
To install the tokenizers library, we use this:
$ pip install tokenizersThe tokenizers library provides several components so that we can build an end-to-end tokenizer from preprocessing the raw text to decoding tokenized unit IDs:
Normalizer→ PreTokenizer → Modeling → Post-Processor → Decoding
The following diagram depicts the tokenization pipeline:

Figure 3.17 – Tokenization pipeline
This pipeline can be explained as follows:
- The normalizer allows us to apply primitive text processing such as lowercasing, stripping, Unicode normalization, and removing accents.
- The PreTokenizer prepares the corpus for the next training phase. It splits the input into tokens depending on the rules, such as whitespace.
- Model training is a subword tokenization algorithm such as BPE, BBPE, and WordPiece, which we’ve discussed already. It discovers subwords/vocabulary and learns generation rules.
- Post-processing provides advanced class construction that is compatible with Transformers models such as BertProcessors. We mostly add special tokens such as
[CLS]and[SEP]to the tokenized input just before feeding the architecture. - The decoder is in charge of converting token IDs back to the original string. It is just for inspecting what is going on.
Let’s see how you can train a BPE-based tokenizer.
Training BPE
Section titled “Training BPE”Let’s train a BPE tokenizer using Shakespeare’s plays:
- It is loaded
We will need a post-processor (import nltkfrom nltk.corpus import gutenbergnltk.download('gutenberg')nltk.download('punkt')plays=['shakespeare-macbeth.txt','shakespeare-hamlet.txt','shakespeare-caesar.txt']shakespeare=[" ".join(s) for ply in plays \for s in gutenberg.sents(ply)]
TemplateProcessing) for all the tokenization algorithms ahead. We need to customize the post-processor to make the input convenient for a particular language model. For example, the following template will be suitable for the BERT model since it needs the[CLS]token at the beginning of the input and[SEP]tokens both at the end and in the middle. - We define the template
from tokenizers.processors import TemplateProcessingspecial_tokens=["[UNK]","[CLS]","[SEP]","[PAD]","[MASK]"]temp_proc= TemplateProcessing(single="[CLS] $A [SEP]",pair="[CLS] $A [SEP] $B:1 [SEP]:1",special_tokens=[("[CLS]", special_tokens.index("[CLS]")),("[SEP]", special_tokens.index("[SEP]")),],)
- We import the necessary components to build an end-to-end
from tokenizers import Tokenizerfrom tokenizers.normalizers import (Sequence,Lowercase, NFD, StripAccents)from tokenizers.pre_tokenizers import Whitespacefrom tokenizers.models import BPEfrom tokenizers.decoders import BPEDecoder
- We start by instantiating BPE
tokenizer = Tokenizer(BPE())
- The preprocessing part has two components: normalizer and
pre-tokenizer. We may have more than one normalizer. So, we compose a sequence of normalizer components that includes multiple normalizers whereNFD()is a Unicode normalizer andStripAccents()removes accents. For pre-tokenization,Whitespace()gently breaks the text based on space. Since the decoder component must be compatible with the model,BPEDecoderis selected for the BPE model:tokenizer.normalizer = Sequence([NFD(),Lowercase(),StripAccents()])tokenizer.pre_tokenizer = Whitespace()tokenizer.decoder = BPEDecoder()tokenizer.post_processor=temp_proc - We are now ready to train the tokenizer on the data. The following execution instantiates
BpeTrainer(), which helps us to organize the entire training process by setting hyperparameters. We set the vocabulary size parameter to5000since our Shakespeare corpus is relatively small. For a large-scale project, we use a bigger corpus and normally set the vocabulary size to aroundWe have completed the training!from tokenizers.trainers import BpeTrainertrainer = BpeTrainer(vocab_size=5000,special_tokens= special_tokens)tokenizer.train_from_iterator(shakespeare, trainer=trainer)print(f"Trained vocab size:{tokenizer.get_vocab_size()}" )Trained vocab size: 5000
Note
Training from the filesystem: To start the training process, we passed an in-memory Shakespeare object as a list of strings to tokenizer.train_from_iterator(). For a large-scale project with a large corpus, we need to design a Python generator that yields string lines mostly by consuming the files from the filesystem rather than in-memory storage. You should also check tokenizer.train() to train from the filesystem storage as applied in the preceding BERT training section.
- Let’s grab a random sentence from Macbeth, name it
sen, and tokenize it with oursen= "Is this a dagger which I see before me, \the handle toward my hand?"sen_enc=tokenizer.encode(sen)print(f"Output: {format(sen_enc.tokens)}")Output: ['[CLS]', 'is', 'this', 'a', 'dagger', 'which', 'i', 'see', 'before', 'me', ',', 'the', 'hand', 'le', 'toward', 'my', 'hand', '?', '[SEP]'] - Thanks to the preceding post-processor function, we see additional
[CLS]and[SEP]tokens in the proper position. There is only one split word, handle (hand,le), since we passed to the model a sentence from Macbeth that the model already knew. Besides, we used a small corpus, and the tokenizer is not forced to use compression. Let’s pass a challenging phrase, “Hugging Face,” that the tokenizer might not know:sen_enc2=tokenizer.encode("Macbeth and Hugging Face")print(f"Output: {format(sen_enc2.tokens)}")Output: ['[CLS]', 'macbeth', 'and', 'hu', 'gg', 'ing', 'face', '[SEP]'] - The term “Hugging” is lower case and split into three pieces
hu,gg, anding, since the model vocabulary contains all other tokens butHugging. Let’s pass two sentences now:Notice that the post-processor injected thetwo_enc=tokenizer.encode("I like Hugging Face!","He likes Macbeth!")print(f"Output: {format(two_enc.tokens)}")Output: ['[CLS]', 'i', 'like', 'hu', 'gg', 'ing', 'face', '!', '[SEP]', 'he', 'li', 'kes', 'macbeth', '!', '[SEP]'][SEP]token as an indicator. - It is time to save the model. We can either save the sub-word tokenization model or the entire tokenization pipeline. First, let’s save the BPE
tokenizer.model.save('.')['./vocab.json', './merges.txt']
- The model saved two files regarding vocabulary and merging rules. The
merge.txtfile is composed of 4,948$ wc -l ./merges.txt4948 ./merges.txt - The top five rules ranked are as shown in the following where we see that [t, h] is the first ranked rule due to that being the most frequent pair. For testing, the model scans the textual input and tries to merge these two symbols first
$ head -3 ./merges.txt#version: 0.2 - Trained by \`huggingface/tokenizers\`t ho ua nth er e
- The BPE algorithm ranks the rules based on frequency. When you manually calculate character bigrams in the Shakespeare corpus, you will find [t, h] the most frequent pair.
- Let’s now save and load the entire
tokenizer.save("MyBPETokenizer.json")tokenizerFromFile =\Tokenizer.from_file("MyBPETokenizer.json")sen_enc3 = \tokenizerFromFile.encode("I like Hugging Face and Macbeth")print(f"Output: {format(sen_enc3.tokens)}")Output: ['[CLS]', 'i', 'like', 'hu', 'gg', 'ing', 'face', 'and', 'macbeth', '[SEP]']
We successfully reloaded the tokenizer!
Training the WordPiece model
Section titled “Training the WordPiece model”In this section, we will train the WordPiece model:
- We start by importing the
from tokenizers.models import WordPiecefrom tokenizers.decoders import WordPiece \as WordPieceDecoderfrom tokenizers.normalizers import BertNormalizer
- The following lines instantiate an empty WordPiece tokenizer and prepare it for training.
BertNormalizeris a pre-defined normalizer sequence that includes the processes of cleaning the text, transforming accents, handling Chinese characters,tokenizer = Tokenizer(WordPiece())tokenizer.normalizer=BertNormalizer()tokenizer.pre_tokenizer = Whitespace()tokenizer.decoder= WordPieceDecoder() - Now, we instantiate a proper trainer,
WordPieceTrainer()forWordPiece(), to organize thefrom tokenizers.trainers import WordPieceTrainertrainer = WordPieceTrainer(vocab_size=5000,\special_tokens=["[UNK]","[CLS]","[SEP]","[PAD]","[MASK]"])tokenizer.train_from_iterator(shakespeare, trainer=trainer)output = tokenizer.encode(sen)print(output.tokens)['is', 'this', 'a', 'dagger', 'which', 'i', 'see', 'before', 'me', ',', 'the', 'hand', '##le', 'toward', 'my', 'hand', '?'] - Let’s use
WordPieceDecoder()to treat thetokenizer.decode(output.ids)'is this a dagger which i see before me, the handle toward my hand?' - We have not come across any
[UNK]tokens in the output since the tokenizer somehow knows or splits the input for encoding. Let’s force the model to produce[UNK]tokens as in the following code. Let’s pass a Turkish sentence totokenizer.encode("Kralsın aslansın Macbeth!").tokens'[UNK]', '[UNK]', 'macbeth', '!']
Well done! We have a couple of unknown tokens since the tokenizer does not find a way to decompose the given word from the merging rules and the base vocabulary.
So far, we have designed our tokenization pipeline all the way from the normalizer component to the decoder component. On the other hand, the tokenizers library provides us with an already made (not trained) empty tokenization pipeline with proper components to build quick prototypes for production. Here are some pre-made tokenizers:
CharBPETokenizer: The original BPEByteLevelBPETokenizer: The byte-level version of the BPESentencePieceBPETokenizer: A BPE implementation compatible with the one used bySentencePieceBertWordPieceTokenizer: The famous BERT tokenizer, using WordPiece
The following code imports these pipelines:
from tokenizers import (ByteLevelBPETokenizer, CharBPETokenizer, SentencePieceBPETokenizer, BertWordPieceTokenizer)All these pipelines are already designed for us. The rest of the process (such as training, saving the model, and using the tokenizer) is the same as our previous BPE and WordPiece training procedures.
Well done! We have made great progress and trained our first Transformer model as well as its tokenizer.
Summary
Section titled “Summary”In this chapter, we have experienced autoencoding models both theoretically and practically. Starting with learning the basics of BERT, we trained it as well as a corresponding tokenizer from scratch. We also discussed how to work inside other frameworks, such as Keras. Besides BERT, we also reviewed other autoencoding models such as ALBERT, RoBERTa, ELECTRA, and DeBERTa. To avoid excessive code repetition, we did not provide the full implementation for training other models. During the BERT training, we trained the WordPiece tokenization algorithm. In the last part, we examined other tokenization algorithms since it is worth discussing and understanding all of them as different Transformer architectures utilize different tokenization algorithms.
Autoencoding models use the left decoder side of the original Transformer and are mostly fine-tuned for classification problems. In the next chapter, we will discuss and learn about the right decoder part of Transformers to implement language generation models.