From Generative Models to Large Language Models
local graph
Chapter 4 — From Generative Models to Large Language Models
Section titled “Chapter 4 — From Generative Models to Large Language Models”In this chapter, you will learn about Generative Language Models (GLMs) and Large Language Model (LLMs). After this, you will learn how to pre-train any language model, such as Generated Pre-trained Transformer 2 (GPT-2), on your own text and use it for tasks such as Natural Language Generation (NLG). You will learn the basics of Text-to-Text Transfer Transformer (T5) models, conduct a hands-on multitask learning experiment with T5, and train a Multilingual T5 (mT5) model on your own Machine Translation (MT) data. After finishing this chapter, you will have an overview of GLMs and their various use cases in text2text applications, such as summarization, paraphrasing, multitask learning, zero-shot learning, and MT.
The following topics will be covered in this chapter:
- Working with GLMs
- Working with text-to-text models
- AR language model training
- GLM training
- NLG using AR models
Technical requirements
Section titled “Technical requirements”The following libraries/packages are required to successfully complete this chapter:
Anacondatransformers 4.0.0pytorch 1.0.2tensorflow 2.4.0SimpleT5 0.1.4datasets 2.10.0tokenizers
All notebooks with coding exercises will be available at the Book GitHub page at https://github.com/PacktPublishing/Mastering-Transformers-Second-Edition.
An introduction to GLMs
Section titled “An introduction to GLMs”While Autoencoder (AE) language models, such as Bidirectional Encoder Representations from Transformers (BERT), are purely based on the encoder part of transformers and are well-suited for classification problems, generative models are either encoder-decoder or decoder-only models. GLMs were originally intended for language generation tasks such as MT or text summarization, but we can see different successful use cases used by GLMs.
AE models are particularly effective for classification tasks, such as text classification and sentiment analysis, as well as token-level tasks such as named entity recognition (NER) or part-of-speech (POS) tagging. Here, AE models simply perform classification by mapping either the special CLS token at the beginning of the sentence or the individual tokens at any position to the predefined class labels. On the other hand, although GLMs have been widely used for language generation tasks, they have also been successfully used for classification tasks recently.
GLMs are pre-trained using one of two objectives: either a causal language modeling objective, which allows the model to predict the next word in a sequence (for example, GPT-3 or PaLM), or a denoising objective, where the model learns to restore the original sentence from a corrupted one (such as T5 and BART). While the former purely relies on the decoder part of the transformers, also called Auto Regressive (AR) model, the latter uses both encoder-decoder parts of the transformers, also called text-to-text or seq-to-seq model.
These models are commonly used in tasks such as MT, dialog systems, and text summarization. An interesting feature that emerges here is that it is possible to use generated text for classification purposes mostly solved by Encoder-only models. However, the reverse is not true. We could not use Encoder-only models for generation. For instance, it is nearly impossible to translate a text with BERT.
Controlling the textual output of the generative models is crucial for preventing issues such as toxic text generation and model hallucinations during problem-solving. By controlling the output, we can easily use GLMs for classification tasks. The critical trick is to express tasks as instructions. Here are some examples:
| Task | Input Template | Possible Textual Output |
|---|---|---|
| Sentiment Analysis | input text + “what is the sentiment?” | “it is positive” “it is negative” |
| Text Classification | input text + “what is the text about?” | “it is about the economy” “it is about health”. |
| Text Regression | Input text + “Can you rate the sentence quality on a scale of 1-5?” | “it is 3.0” “it is 1.0” |
| NER | “… John … Paris …” + prompt | “Paris is a city entity” “John is a person entity” |
Table 4.1 – Prompting for tasks
A piece of text called a prompt is added to the input so that the model is directed toward the desired target.
Thanks to the generation capacity of LLMs and prompting (we will discuss prompting in detail in later chapters), generative models approach any task as a text-to-text problem, which leads to successful solutions. This approach provides the opportunity to apply multi-task learning very easily since we can handle diverse tasks in the same batch. We can map many tasks into a single structure, which is text-to-text. Major language models such as GPT-3, PaLM, and ChatGPT —which are currently popular—take advantage of this generative feature. We will also discuss LLMs in Chapter 10.
A notable example of using GLMs and instruction-based multi-task learning is the FLAN framework. The framework was able to model 1,800 different instruction fine-tuning tasks simultaneously without changing the model’s architecture. By scaling (the initial proposal used LaMDA 137B) the model to the 540-billion-parameter language model (PaLM) and scaling (the initial task size was 62) to 1,800 tasks, the model can be successful even in tasks that are unaware of its existence during training, which is called zero-shot learning. Thanks to such generative models, which allow scaling up in this direction, it is not surprising that we encounter fascinating applications every day.
It is also important to note that prompt engineering as we see it today will vanish in time. We have seen many research articles that aim to find the most effective prompts. However, with advancements in instruction fine-tuning, we are getting closer to having more and more natural instructions. ChatGPT is a fantastic example of these advancements. Instruction capability of ChatGPT (the GPT-3.5 and davinci-003 models) have shown that a better understanding of instructions and a greater ability to follow them by the model can lead to many new features. You might have seen many people working with these fine-tuned models and creating great tools such as conversational question-answering systems.
But (at the time this book was being written) some problems still exist. LLMs still suffer from hallucination, and much research is being conducted to solve this issue. Sometimes, even if you provide a nice and well-written context and ask a question about it (Open Book Question Answering or OBQA), you will be welcomed by a hallucinated answer. It is very important to use such tools, but it is more important to know their problems as well.
Working with GLMs
Section titled “Working with GLMs”The Transformer architecture was originally intended to be effective for text-to-text tasks such as MT and summarization, but it has been used in diverse NLP problems, ranging from token classification to coreference resolution. Subsequent works began to use the left and right parts of the architecture separately and more creatively. Other than next-word prediction, some denoising objectives are also utilized to fully recover the original input from corrupted or truncated input.
While text-to-text models such as T5 use both encoder and decoder parts, decoder-only models such as GPT uses only decoder part. Decoder-only AR prevents the model from accessing words to the right of the current word in a forward direction (or to the left of the current word in a backward direction), which is called unidirectionality.
GPT and its successors (GPT-2, GPT-3, InstructGPT (a.k.a GPT-3.5), and ChatGPT), Transformer-XL, and XLNet are some of the popular decoder-only AR models in the literature. Even though XLNet is based on autoregression, it somehow managed to make use of both contextual sides of the word in a bidirectional fashion, with the help of the permutation-based language objective. Now, we start introducing them and show how to train the models with a variety of experiments. Let’s look at GPTs first.
GPT model family
Section titled “GPT model family”AR models are made up of multiple decoder blocks of transformers. Each block contains a masked multi-head self-attention layer along with a pointwise feed-forward layer. The activation in the final transformer block is fed into a SoftMax function that produces the word probability distributions over an entire vocabulary of words to predict the next word. Notable examples are mostly from Open AI’s GPT model family.
In the original GPT paper Improving Language Understanding by Generative Pre-Training (2018), the authors addressed several bottlenecks that traditional ML-based NLP pipelines are subject to. For example, firstly, traditional pipelines require both a massive amount of task-specific data and task-specific architecture. Secondly, it is hard to apply task-aware input transformations with minimal changes to the architecture of the pre-trained model. The original GPT and its successors (GPT-2 and GPT-3), designed by the OpenAI team, have focused on these problems and their solutions to alleviate these bottlenecks. The major contribution of the original GPT study is that the pre-trained model achieved satisfactory results, not only for a single task but diverse tasks, which is called multi-task learning. Having learned the generative model from unlabeled data, which is self-supervised pre-training, the model is simply fine-tuned to a downstream task (or multiple tasks) with a relatively small amount of task-specific data, which is called supervised fine-tuning (SFT). This two-stage scheme is widely used in other transformer models as well, where self-supervised pre-training is followed by supervised fine-tuning.
GPT models showed us that GLMs can solve zero-shot task generalization problems by relying specifically on multi-task learning. To make multi-task learning feasible, the GPT architecture is kept as generic as possible: only the inputs are transformed in a task-specific manner, while the entire architecture is kept exactly the same. This approach converts the textual input into a suitable format for the task so that the pre-trained model can understand the task from it. The left part of Figure 4*.1* (from the original paper) illustrates the Transformers architecture and training objectives used in the original GPT work. The right side shows how to transform input for fine-tuning on several tasks.
To put it simply, for a single-sequence task such as text classification, the input is passed through the network as-is, and the linear layer takes the last activations to make a decision. For sentence-pair tasks such as textual entailment, the input that is made up of two sequences is marked with a delimiter, shown as the second example in Figure 4*.1*. In both scenarios, the architecture sees uniform token sequences being processed by the pre-trained model. The delimiter used in this transformation helps the pre-trained model to know which part is the premise and the hypothesis in the case of textual entailment. Thanks to input transformation, we do not have to make substantial changes in the architecture across the tasks.
You can see a representation of input transformation here:

Figure 4.1 – Input transformation (from the original paper)
The GPT and its successors have mainly focused on achieving a particular architectural design that eliminates the need for a fine-tuning phase. This is based on the idea that a model can learn a great deal about a language in the pre-training phase, leaving little work to be done during fine-tuning. During inference, the model is given a text as well as a few examples of tasks as input. In some cases, such as zero-shot learning, no examples are provided at all.
Successors of the original GPTs
Section titled “Successors of the original GPTs”The popular ChatGPT, as the names suggest, is based on GPT, which was developed by the OpenAI team. Along the way, the team designed several other models, including GPT2, GPT3, InstructGPT, and ChatGPT.
GPT-2 (see the paper Language Models are Unsupervised Multitask Learners, 2019), a successor to the original GPT called WebText, is a larger model than GPT and was trained on much more training data than the original one. GPT-2 achieved better results on seven out of the eight tasks in a zero-shot setting in which there was no fine-tuning applied but had limited success in some other tasks. The idea behind the GPT-2 is that language models mostly need self-supervised pre-training. Although the ideas behind the model were very valuable, the performance was not very good. However, it worked surprisingly well in some cases. Researchers pursued this approach because they realized that this zero-shot/few-shot learning idea could be applied by scaling some aspects of training process. They saw that a task-agnostic model could be trained on a huge and diverse dataset.
Since they had seen that the zero and few-shot capabilities of language models substantially improved by scaling up the model size, the dataset size, and the task size in multi-tasking, the OpenAI team trained the GPT-3 model (see the paper Language models are few-shot learners, 2020) with 175 billion parameters, which is 100 times bigger than GPT-2. The study showed that scaling up models substantially improves task-agnostic and few-shot learning performance.
The architectures of GPT-2 are GPT-3 are similar, with the main differences usually being in the model size, diverse tasks, and the dataset quantity/quality. Due to the massive amount of data in the dataset and the large number of parameters it is trained on, it achieved better results on many downstream tasks in zero-shot, one-shot, and few-shot (such as K=32 shots) settings without any gradient-based fine-tuning. The team showed that the model performance increased as the parameter size and the number of examples increased for many tasks, including translation, question answering, and masked-token tasks.
One of the main problems of GLMs is the potential for generating toxic information. In response to concerns about toxic language and misinformation, the team introduced a new approach called InstructGPT as another extension of the GPT model family. To enhance the safety and usefulness of the model, the team employed a technique called reinforcement learning from human feedback (RLHF) to refine GPT-3. In comparison to GPT-3, the InstructGPT model demonstrates an improved ability to comprehend and execute instructions expressed in natural language. Furthermore, it exhibits a reduced likelihood of generating false or harmful information.
The OpenAI team has developed a three-step process for InstructGPT. The initial step involves fine-tuning the model, followed by the creation of a reward model (RM). The third and final step is to take the supervised fine-tuning model and refine it further using reinforcement learning. One advantage of InstructGPT is its strong alignment with human intention. This is achieved through the utilization of a reinforcement learning framework, which enables it to learn from human feedback. It is said that Popular ChatGPT is based on InstructionGPT, but we have not seen any documentation about how ChatGPT has been trained yet.
Transformer-XL
Section titled “Transformer-XL”Another important generative model is Transformer-XL. The author of the model stated that Transformer models suffer from the fixed-length context due to a lack of recurrence in the initial design and context fragmentation, although they are capable of learning long-term dependencies. Most transformers break down documents into a list of fixed-length (mostly 512) segments, where any information flow across segments is not possible. Consequently, the language models are not able to capture long-term dependencies beyond this fixed-length limit. Moreover, the segmentation procedure builds the segments without paying attention to sentence boundaries. A segment can be absurdly made up of the second half of a sentence and the first half of its successor, hence the language models can miss the necessary contextual information when predicting the next token. This problem is referred to as the context fragmentation problem in the literature.
To address and overcome these issues, the Transformer-XL authors (see the paper Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context, 2019) proposed a new transformer architecture that includes a segment-level recurrence mechanism and a new positional encoding scheme. This approach inspired many subsequent models. The largest possible dependency length that the model can attend is limited by the number of layers and segment lengths.
Masked Language Modeling (MLM) has dominated the pre-training phase of encoder-only transformer architectures. However, it has faced criticism in the past since the masked tokens are present in the pre-training phase but are absent during the fine-tuning phase, which leads to a discrepancy between pre-training and fine-tuning. Because of this absence, the model may not be able to use all of the information learned during the pre-training phase. XLNet (see the paper XLNet: Generalized Autoregressive Pretraining for Language Understanding, 2019) replaces MLM with Permuted Language Modeling (PLM), which is a random permutation of the input tokens to overcome this bottleneck. The permutation language modeling makes each token position utilize contextual information from all positions, leading to capturing bidirectional context. The objective function only permutes the factorization order and defines the order of token predictions, but doesn’t change the natural positions of sequences. Briefly, the model chooses some tokens as targets after permutation, and it then tries to predict them conditioned on the remaining tokens and the natural positions of the targets. It makes it possible to use an AR model in a bidirectional fashion.
XLNet takes advantage of both AE and AR models. It is, indeed, a generalized AR model. Besides its objective function, XLNet is made up of two important mechanisms: it integrates the segment-level recurrence mechanism of Transformer-XL into its framework, and it includes the careful design of the two-stream attention mechanism for target-aware representations.
Let’s discuss those models using both parts of the Transformers in the next section.
Working with text-to-text models
Section titled “Working with text-to-text models”The left encoder and the right decoder parts of the transformer are connected with cross-attention, which helps each decoder layer attends over the final encoder layer, which means it exploits encoded information accumulated at the encoder layer. This naturally pushes models toward producing output that is closely tied to the original input. The following are popular text-to-text models that keep the encoder and decoder part of the transformer:
- T5: Exploring the limits of transfer learning with a unified text-to-text transformer
- BART: Bidirectional and Auto-Regressive Transformer
- PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization Sequence-to-Sequence models
Let’s begin to understand and work with T5.
Multi-task learning with T5
Section titled “Multi-task learning with T5”Most NLP architectures, ranging from Word2Vec to transformers, learn embeddings and other parameters by predicting the masked words using context (neighbor) words. We treat NLP problems as word prediction problems. While some text-to-text models purely rely on next-word prediction, some, such as T5 and BART, exploit denoising objectives, which maximize the model capacity in terms of reconstructing randomly corrupted text. That is, the model is trained to predict missing or corrupted tokens in the input. T5 (see the paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, 2019) emphasized this point, and the authors developed their own objective function based on it. But the main contribution of T5 is its capacity for multi-task learning by rephrasing the task as instruction.
T5 proposed a unifying framework to solve many tasks under the same structure. The idea underlying T5 is to rephrase all NLP tasks to a text-to-text (Seq2Seq) problem where both input and output are a list of tokens. Transformers have been found to be useful in applying the same model to diverse NLP tasks, as seen in GPT-3, from question answering to text summarization, which enables us to employ multi-task training.
The following diagram, which is inspired by the original paper, shows how T5 solves many (four in this figure) different NLP tasks—MT, linguistic acceptability, semantic similarity, and summarization—within a unified framework:

Figure 4.2 – The T5 framework
The T5 model roughly follows the original encoder-decoder transformer model. The modifications are done in the layer normalization, denoising objective function, and position embedding scheme. Instead of using sinusoidal positional embedding or learned embedding, T5 uses relative positional embedding, which is becoming more common in transformer architectures.
T5 casts tasks into a text-to-text format. The model is fed with text that is made up of a task prefix and the input attached to it. We convert a labeled textual dataset to a {'inputs': '....', 'targets': ...'} format, where we insert the purpose in the input as a prefix. Then, we train the model with labeled data so that it learns what to do and how to do it. As shown in the preceding diagram, for the English-German translation task, the "translate English to German: That is good." input is going to produce "das is gut.". Likewise, any input with a "summarize:" prefix will be summarized by the model.
It should be noted that the T5 model is not designed for task-agnostic purposes. In the next subsection, we will discuss how to modify it to become task-agnostic, which is referred to as T0.
Multi-task training with T5
Section titled “Multi-task training with T5”Now, let’s take a simple look at how to apply multi-task training in a T5 architecture with the SimpleT5 library. To fully understand and address multitask learning, we’ll start with a proof-of-concept (PoC). Our PoC will be an exercise that’s focused on determining whether the multi-tasking idea can be turned into a reality. But it is important to explore all potential implications, of course. To start, model selection, datasets, and task diversity will be kept as simple as possible. We will use two different datasets: the glue-sst2 dataset for sentiment analysis and the opus_en-de (English-German) machine translation dataset from the Opus project.
NLP libraries
In this book, we are using various sources and libraries so you can experience different infrastructures. In this way, we will learn about a lot of open-source software. We circulate them for the community. For example, we will now use the SimpleT5 library for multi-task training. In the next subsection, we will train T5 with the simpletransformer library for MT. They are both built on top of Hugging Face’s Transformers library.
First, let’s install the necessary libraries:
pip install simpleT5 datasetsFor now, let’s download the small checkpoint of the T5 model so that we can do faster training. But please, do not forget that we need bigger models to improve performance for real production. This is especially crucial for few-shot problems.
from simplet5 import SimpleT5model = SimpleT5()model.from_pretrained("t5","t5-small")Now, we will use the datasets library to load the datasets and prepare them for modeling. As SimpleT5 requires a pandas DataFrame and for the column names to be [source_text, target_text], we renamed the columns within our pandas DataFrame. We take only the first 1,000 sentences for quick prototyping. Once you have successfully trained the model, you should/can use the entire dataset to improve the accuracy!
import pandas as pdfrom datasets import load_datasetsst2_df =pd.DataFrame( load_dataset("glue", "sst2", split="train[:1000]"))sst2_df=sst2_df[["sentence","label"]]sst2_df.columns= ["source_text","target_text"]Now we will use prompts to rephrase the tasks so they are suitable for text-to-text. We add the instruction “What is the sentiment? Good or Bad?” to the source sentence. Likewise, we set suitable tokens "Good" and "Bad" for 1 and 0 for the target text as follows:
prompt_sentiment=". What is the sentiment ? "\ +"Good or Bad ?"sst2_df["source_text"]= sst2_df\ .source_text\ .apply(lambda x: x +prompt_sentiment)sst2_df["target_text"]=sst2_df\ .target_text\ .apply(lambda x:"Good" if x==1 else "Bad")We will make a similar arrangement in the MT dataset to fit the text-to-text template. Let’s load only 1,000 instances from the opus en-de dataset first. Notice that we set source and target as English and German respectively to apply English-to-German translation:
opus=load_dataset("opus100","de-en", split="train[:1000]")opus_df=pd.DataFrame(opus)opus_df["source_text"]=opus_df.apply( lambda x: x.translation["en"], axis=1)opus_df["target_text"]=opus_df.apply( lambda x: x.translation["de"], axis=1)opus_df= opus_df[["source_text","target_text"]]The prompt that we add at the end of the sentences is "Translate English to German", as follows:
prompt_tr=". Translate English to German"opus_df["source_text"]= opus_df\ .source_text\ .apply(lambda x: x +prompt_tr)Our two tasks are ready for training. We merge and shuffle them:
merge= opus_df.append(sst2_df).sample(frac=1.0)merge.head(5)
Figure 4.3 — Two different NLP tasks in one seq-2-seq format
Finally, we have two tasks in one bag in the form of seq-2-seq. We take 1,800 instances for training and 200 for testing:
train_df=merge[:1800]eval_df= merge[1800:]Thanks to the SimpleT5 framework, the training is very simple. We keep the source token length as 512, which is longer than the target length, 128:
model.train(train_df=train_df, eval_df=eval_df, source_max_token_len = 512, target_max_token_len = 128, batch_size = 8, max_epochs = 3, use_gpu = True, precision = 32)Once the training is successfully completed, we can experience the application of multi-task learning with inference. Now we will take the same sentence, "The cats are fun!", for both sentiment analysis and MT using the appropriate prompt.
Let’s start with sentiment by just adding a sentiment prompt to the sentence:
import torchmodel.device= torch.device("cpu")a_sentence="The cats are fun!"model.predict(a_sentence+ prompt_sentiment)Output:['Good']The output is "Good", which is the correct label. But the important thing at this point is that the model understood what the task is. T5 checkpoints (T5-small, T5-base or T5-large) have been already pre-trained with different tasks. So, they have the potential to misunderstand the tasks. We can say now that we have correctly guided the model with prompting. We do not care now if the model classifies perfectly or not. Thus, we do not evaluate the model’s performance.
Now, change the instruction to en-de translation by adding prompt_tr to the sentence and pass the prompt to the model:
model.predict(a_sentence+ prompt_tr)Output: ['Die Katzen sind spass!']Wow! It worked out well. In both cases, the model understood what to do. The model’s translation capacity is very good even though we use few instances since the pre-trained T5 checkpoints have been trained on such translation tasks before. We used transfer learning here by fine-tuning! However, let us remind you that we need to take some action to increase the performance of the model:
- First of all, use the entire dataset, not just 1,000 pieces.
- Increase task diversity. Tasks such as NER, question-answering, and summarization can be added.
- Use more than one dataset for each task.
- Increase instruction diversity. Use the same dataset with a different prompt.
- We used T5-small as the initial model. Choose larger models such as T5-base or T5-large as suitable for your hardware.
- Model training can take a lot of time. Focus on parameter-efficient approaches and frameworks.
In this part, we have built a simple multi-task learning model by combining all NLP problems into a single format. Now, let’s discuss what T0 is.
Zero-Shot Text Generalization with T0
Section titled “Zero-Shot Text Generalization with T0”The T5 framework was successful in the tasks for which it was trained. This success can be attributed to its multi-tasking modeling scheme. In other words, solving different tasks within the same architecture has a positive effect on each task by circulating knowledge between them. However, the T5 framework has a shortcoming in that it is not task-agnostic, which means it is not designed for solutions that were not included in its training.
It is known that scaling the model’s parameters, dataset size, and task diversity can lead to breakthroughs in the language understanding capabilities of the models for a variety of difficult tasks, as well as held-out tasks. With this motivation, the T0 team worked on a task-agnostic model that could successfully solve zero-shot generalization. This model, called T0, was trained based on the T5 architecture, which considers scaling the model and the diversity of the data.
Here, you can see a simplified T0 diagram of training and inference:

Figure 4.4 – The T0 framework
As shown in the figure, the model is first trained on a diverse mixture of held-in tasks (at the top of the figure). Then, it is evaluated on zero-shot generalization to the held-out tasks that were not seen during training (at the bottom of the figure). There are 62 datasets grouped into 12 tasks, and the T0 model is tested for the zero-shot task generalization problem between tasks, not datasets.
Another Denoising-Based Seq2Seq Model – BART
Section titled “Another Denoising-Based Seq2Seq Model – BART”As with XLNet, the BART model (see the paper BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension, 2019) takes advantage of the schemes of AE and AR models. It uses standard Seq2Seq transformer architecture, with a small modification. However, it has a different training objective than other AR models. It uses a variety of noising approaches that corrupt documents rather than predicting the next word. The main contribution of the model to the field is that it allows us to apply several types of creative corruption schemes, as shown in the following diagram:

Figure 4.5 – Diagram from the original BART paper
We will look at each scheme in detail, as follows:
- Token masking: Tokens are randomly masked with a
[MASK]symbol, the same as with the BERT model. - Token deletion: Tokens are randomly removed from the documents. The model is forced to determine which positions are removed.
- Text infilling: Following SpanBERT, a number of text spans are sampled, and then they are replaced by a single
[MASK]token. There is also[MASK]token insertion. - Sentence permutation: The sentences in the input are segmented and shuffled in a random order.
- Document rotation: The document is rotated so that it begins with a randomly selected token, C in the preceding diagram. The objective is to find the start position of a document.
The BART model can be fine-tuned in several ways for downstream applications such as BERT.
For the task of sequence classification, the input is passed through an encoder and a decoder, and the final hidden state of the decoder is considered the learned representation. Then, a simple linear classifier can make predictions. Likewise, for token classification tasks, the entire document is fed into the encoder and decoder, and the last state of the final decoder is the representation for each token. Based on these representations, we can carry out token classification tasks such as NER and POS tagging.
For sequence generation, the decoder block of the BART model can be directly fine-tuned for sequence-generation tasks such as abstractive QA or summarization. The BART authors trained the models using two standard summarization datasets: CNN / DailyMail and XSum. The authors also showed that it is possible to use both the encoder part—which consumes a source language—and the decoder part, which produces the words in the target language as a single pre-trained decoder for MT. They replaced the encoder embedding layer with a new randomly initialized encoder in order to learn words in the source language. Then, the model is trained in an end-to-end fashion, which trains the new encoder to map foreign words into an input that BART can denoise to the target language. The new encoder can use a separate vocabulary, including foreign language, from the original BART model.
In the Hugging Face platform, we can access the original pre-trained BART model with the following line of code:
AutoModel.from_pretrained('facebook/bart-large')When we call the standard summarization pipeline of the transformers library, as shown in the following line of code, a distilled pre-trained BART model is loaded. This call implicitly loads the sshleifer/distilbart-cnn-12-6 model and the corresponding tokenizers, as follows:
summarizer = pipeline("summarization")The following code explicitly loads the same model and the corresponding tokenizer. The code example takes a text to be summarized and outputs the results:
from transformers import ( BartTokenizer, BartForConditionalGeneration, BartConfig)from transformers import pipelinemodel = BartForConditionalGeneration\ .from_pretrained('sshleifer/distilbart-cnn-12-6')tokenizer = BartTokenizer\ .from_pretrained('sshleifer/distilbart-cnn-12-6')nlp=pipeline("summarization", model=model, tokenizer=tokenizer)text='''We order two different types of jewelry from thiscompany the other jewelry we order is perfect.However with this jewelry I have a few things Idon't like. The little Stone comes out of theseand customers are complaining and bringing themback and we are having to put new jewelry in theirholes. You cannot sterilize these in an autoclave...[truncated]'''q=nlp(text)import pprintpp = pprint.PrettyPrinter(indent=0, width=100)pp.pprint(q[0]['summary_text'])(' The little Stone comes out of these little stones and customers are complaining and bringing ' 'them back and we are having to put new jewelry in their holes . You cannot sterilize these in an ' 'autoclave because it heats up too much and the glue does not hold up so the second group of ' 'these that we used I did not sterilize them that way and the stones still came out.')O/In the next section, we look at how to train base models.
GLM training
Section titled “GLM training”In this section, you will learn how it is possible to train your own language models. We will start with GPT-2 and get a deeper look inside its different functions for training using the transformers library.
You can find any corpus to train your own GPT-2, but for this example, we used Emma by Jane Austen, which is a romantic novel. Training on a much bigger corpus is highly recommended to generate more general language.
Before we start, it’s good to note that we used TensorFlow’s native training functionality to show that all Hugging Face models can be directly trained on TensorFlow or PyTorch if you wish to. Follow these steps:
- You can download the Emma raw text by using the
wget https://raw.githubusercontent.com/teropa/nlp/master/resources/corpora/gutenberg/austen-emma.txt
- The next step is to train the
BytePairEncodingtokenizer for GPT-2 on a corpus that you intend to train your GPT-2 on. The following code will import theBPEtokenizer from thetokenizersfrom tokenizers.models import BPEfrom tokenizers import Tokenizerfrom tokenizers.decoders import ByteLevel as ByteLevelDecoderfrom tokenizers.normalizers import Sequence, Lowercasefrom tokenizers.pre_tokenizers import ByteLevelfrom tokenizers.trainers import BpeTrainer - As you can see, in this example, we intend to train a more advanced tokenizer by adding more functionality, such as the
Lowercasenormalization. To make atokenizerobject, you can use theThe first line makes a tokenizer from thetokenizer = Tokenizer(BPE())tokenizer.normalizer = Sequence([Lowercase()])tokenizer.pre_tokenizer = ByteLevel()tokenizer.decoder = ByteLevelDecoder()BPEtokenizer class. For the normalization part,Lowercasehas been added, and thepre_tokenizerattribute is set toByteLevelto ensure we have bytes as our input. Thedecoderattribute must be also set toByteLevelDecoderto be able to decode correctly. - Next, the tokenizer will be trained using a
50000maximum vocabulary size and an initial alphabet fromByteLevel,trainer = BpeTrainer(vocab_size=50000,inital_alphabet=ByteLevel.alphabet(),special_tokens=["<s>","<pad>","</s>","<unk>","<mask>"])tokenizer.train(["austen-emma.txt"], trainer) - It is also necessary to add special tokens to be considered. To save the tokenizer, you are required to create a directory,
!mkdir tokenizer_gpt
- You can save the tokenizer by running the
tokenizer.save("tokenizer_gpt/tokenizer.json")
- Now that the tokenizer is saved, it’s time to preprocess the corpus and make it ready for GPT-2 training using the saved tokenizer, but first, important imports must not be forgotten. The code to do the imports is illustrated in the
from transformers import (GPT2TokenizerFast, GPT2Config, TFGPT2LMHeadModel)
- And the tokenizer can be loaded by using
GPT2TokenizerFast,tokenizer_gpt = GPT2TokenizerFast.from_pretrained("tokenizer_gpt") - It is also essential to add special tokens with their marks,
tokenizer_gpt.add_special_tokens({"eos_token": "</s>","bos_token": "<s>","unk_token": "<unk>","pad_token": "<pad>","mask_token": "<mask>"})
- You can also double-check to see if everything is correct or not by running the
This code will output the End-of-Sentence (EOS) token Identifier (ID), which istokenizer_gpt.eos_token_id>> 2
2for the current tokenizer. - You can also test it for a sentence by executing the
For this output,tokenizer_gpt.encode("<s> this is </s>")>> [0, 265, 157, 56, 2]
0is the beginning of the sentence,265,157, and56are related to the sentence itself, and the EOS is marked as2, which is</s>. - These settings must be used when creating a configuration object. The following code will create a
configobject and the TensorFlow version of theconfig = GPT2Config(vocab_size=tokenizer_gpt.vocab_size,bos_token_id=tokenizer_gpt.bos_token_id,eos_token_id=tokenizer_gpt.eos_token_id)model = TFGPT2LMHeadModel(config) - On running the
configobject, you can see the configuration in dictionary format,As you can see, other settings are not touched, and the interesting part is thatconfig>> GPT2Config { "activation_function": "gelu_new", "attn_pdrop": 0.1, "bos_token_id": 0, "embd_pdrop": 0.1, "eos_token_id": 2, "gradient_checkpointing": false, "initializer_range": 0.02, "layer_norm_epsilon": 1e-05, "model_type": "gpt2", "n_ctx": 1024, "n_embd": 768, "n_head": 12, "n_inner": null, "n_layer": 12, "n_positions": 1024, "resid_pdrop": 0.1, "summary_activation": null, "summary_first_dropout": 0.1, "summary_proj_to_labels": true, "summary_type": "cls_index", "summary_use_proj": true, "transformers_version": "4.3.2", "use_cache": true, "vocab_size": 11750}vocab_sizeis set to11750. The reason for this is that we set the maximum vocabulary size to be50000, but the corpus had fewer words, and its Byte-Pair Encoding (BPE) token created11750words. - Now, you can get your corpus ready for pre-training,
with open("austen-emma.txt", "r", encoding='utf-8') as f:content = f.readlines()
- The content will now include all raw text from the raw file, but it is required to remove
'\n'from each line and drop lines with fewer than10characters,content_p = []for c in content:if len(c)>10:content_p.append(c.strip())content_p = " ".join(content_p)+tokenizer_gpt.eos_token - Dropping short lines will ensure that the model is trained on long sequences in order to be able to generate longer sequences. At the end of the preceding snippet,
content_phas the concatenated raw file witheos_tokenadded to the end. But you can follow different strategies too—for example, you can separate each line by adding</s>to each line, which will help the model to recognize when the sentence ends. However, we intend to make it work for much longer sequences without encountering EOS. The code is illustrated in the following snippet:The GPT tokenizer from the preceding code snippet will tokenize the whole text and make it one whole, long sequence of token IDs.tokenized_content = tokenizer_gpt.encode(content_p) - Now, it’s time to make the samples for training,
sample_len = 100examples = []for i in range(0, len(tokenized_content)):examples.append(tokenized_content[i:i + sample_len])
- The preceding code makes
examplesa size of100for each one starting from a given part of text and ending at100tokens later:Intrain_data = []labels = []for example in examples:train_data.append(example[:-1])labels.append(example[1:])train_data, there will be a sequence of size99from the start to the 99th token, and the labels will have a token sequence from1to100. - For faster training, it is required to put the data in the form of a TensorFlow dataset,
Import tensorflow as tfbuffer = 500batch_size = 16dataset = tf.data.Dataset.from_tensor_slices((train_data, labels))dataset = dataset.shuffle(buffer).batch(batch_size,drop_remainder=True)
bufferis the buffer size used for shuffling data, andbatch_sizeis the batch size for training.drop_remainderis used to drop the remainder if it is less than16. - Now, you can specify your
optimizer,loss, andmetricsproperties,optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5,epsilon=1e-08, clipnorm=1.0)loss = tf.keras.losses\.SparseCategoricalCrossentropy(from_logits=True)metric = tf.keras.metrics\.SparseCategoricalAccuracy('accuracy')model.compile(optimizer=optimizer,loss=[loss, *[None] * model.config.n_layer],metrics=[metric]) - The model is compiled and ready to be trained with the number of epochs you wish,
You will see an output that looks something like this:epochs = 10model.fit(dataset, epochs=epochs)

Figure 4.6 – GPT-2 training using TensorFlow/Keras
We will now look at NLG using AR models. Now that you have saved the model, it will be used for generating sentences in the next section.
Up until this point, you have learned how it is possible to train your own model for NLG. In the next section, we describe how to utilize NLG models for language generation.
NLG using AR models
Section titled “NLG using AR models”In the previous section, you learned how it is possible to train an AR model on your own corpus. As a result, you trained a GPT-2 version of your own. But the answer to the question How can I use it? remains. To answer that, let’s proceed as follows:
- Let’s start generating sentences from the model you have just trained,
Thedef generate(start, model):input_token_ids = tokenizer_gpt.encode(start,return_tensors='tf')output = model.generate(input_token_ids,max_length = 500,num_beams = 5,temperature = 0.7,no_repeat_ngram_size=2,num_return_sequences=1)return tokenizer_gpt.decode(output[0])
generatefunction that is defined in the preceding code snippet takes astartstring and generates sequences following that string. You can change parameters such asmax_lengthto a smaller sequence size ornum_return_sequencesto have different generations. - Let’s just try it with an empty string,
We get the following output:generate(" ", model)

Figure 4.7 – GPT-2 text-generation example
As you can see from the preceding output, a long text is generated, even if the semantics of the text is not very pleasing, but the syntax is almost correct in many cases.
- Now, let’s try different starts, with
max_lengthset to a lower value such as30,As you may recall,generate("weston was very good")>> 'weston was very good; but it, that he was a great must be a mile from them, and a miss taylor in the house;'westonis one of the characters from the novel. - To save the model, you can use the following code to make it reusable for publishing or
model.save_pretrained("my_gpt-2/")
- To make sure your model is saved correctly, you can try loading it,
Two files are saved—amodel_reloaded = TFGPT2LMHeadModel.from_pretrained("my_gpt-2/")
configfile and amodel.h5file, which is for the TensorFlow version. We can see both of these files in the following screenshot:
Figure 4.8 – Language model save_pretrained output
- Hugging Face also has a standard for filenames that must be used—these standard filenames are available by using the
However, when using thefrom transformers import (WEIGHTS_NAME, CONFIG_NAME,TF2_WEIGHTS_NAME)
save_pretrainedfunction, it is not required to put the filenames—just the directory will suffice. - Hugging Face also has
AutoModelandAutoTokenizerclasses, as you saw in the previous sections. You can also use this functionality to save the model, but before doing that there are still a few configurations that need to be done manually. The first thing is to save the tokenizer in the right format to be used byAutoTokenizer. You can do this by usingsave_pretrained, as follows:This is the output:tokenizer_gpt.save_pretrained("tokenizer_gpt_auto/")
Figure 4.9 – Tokenizer save_pretrained output
- The file list is shown in the directory you specified, but
tokenizer_configmust be manually changed to be usable. First, you should rename it asconfig.json, and secondly, you should add a property in JavaScript Object Notation (JSON) format, indicating that themodel_typeproperty isgpt2, as follows:{"model_type":"gpt2",...} - Now, everything is ready, and you can simply use these two lines of code to load
modelandtokenizer:However, do not forget to setmodel = AutoModel.from_pretrained("my_gpt-2/", from_tf=True)tokenizer = AutoTokenizer.from_pretrained("tokenizer_gpt_auto")from_tftoTruebecause your model is saved in TensorFlow format.
Well done. You have now learned how you can pre-train and save your own text-generation model using TensorFlow and transformers. You have also learned how to train your own AR models.
Summary
Section titled “Summary”In this chapter, we have covered various aspects of GLMs (AR and seq2seq), from pre-training to fine-tuning. We looked at the best features of such models by training GLMs and fine-tuning them on tasks such as MT and multi-task training. We explored the basics of more complex models such as T5, GPT3, and T0 and used this kind of model to perform MT. We used different Python libraries to train T5-based multi-task learning prototyping. We trained GPT-2 on our own corpus and generated text using it. We learned how to save it and use it with AutoModel. We also had a deeper look into how BPE can be trained and used, using the tokenizers library.
In the next chapter, we will see how to fine-tune models for text classification.
References
Section titled “References”- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D. and Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI blog, 1(8), 9.
- Lewis, M., Liu, Y., Goyal, N., Ghazvininejad, M., Mohamed, A., Levy, O. and Zettlemoyer, L. (2019). BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension. arXiv preprint arXiv:1910.13461.
- Xue, L., Constant, N., Roberts, A., Kale, M., Al-Rfou, R., Siddhant, A. and Raffel, C. (2020). mT5: A massively multilingual pre-trained text-to-text transformer. arXiv preprint arXiv:2010.11934.
- Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M. and Liu, P. J. (2019). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. arXiv preprint arXiv:1910.10683.
- Yang, Z., Dai, Z., Yang, Y., Carbonell, J., Salakhutdinov, R. and Le, Q. V. (2019). XLNet: Generalized Autoregressive Pretraining for Language Understanding. arXiv preprint arXiv:1906.08237.
- Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V. and Salakhutdinov, R. (2019). Transformer-xl: Attentive Language Models Beyond a Fixed-Length Context. arXiv preprint arXiv:1901.02860.
- Chowdhery A, Narang S, Devlin J, Bosma M, Mishra G, Roberts A, Barham P, Chung HW, Sutton C, Gehrmann S, Schuh P. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311. 2022 Apr 5.
- Sanh V, Webson A, Raffel C, Bach SH, Sutawika L, Alyafeai Z, Chaffin A, Stiegler A, Scao TL, Raja A, Dey M. Multitask prompted training enables zero-shot task generalization. arXiv preprint arXiv:2110.08207. 2021 Oct 15.