Skip to content
ImagineWorld

Large Language Models

node_idnode-book_mastering-transformers_chapter-10-large-language-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleLarge Language Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The field of large language models (LLMs) has made significant progress in recent years with the development of models such as GPT-3 (175B), PaLM (540B), BLOOM (175B), LLaMA(65B), Falcon(180B), Mistral (7B), and many others. These models have shown impressive abilities in various natural language tasks. It may be challenging to cover such an important topic in a short book section. We have already covered many aspects of the topic, especially in Chapter 4. Moreover, throughout the book, we have discussed the paradigm of neural language models and their training process.

In this chapter, we discuss LLMs and run a couple of experiments. We will also show that it is possible to fine-tune LLMs using a similar process as in the previous chapters, with only minor differences.

We will discuss the following in detail:

  • Why large language models?
  • Fine-tuning large language models

We will need the following packages:

  • transformers==4.35.2
  • accelerate==0.25.0
  • bitsandbytes== 0.42.0
  • peft==0.7.1
  • trl== 0.7.9

What exactly defines a “normal” language model when we talk about a large language model? Sometimes people use the terms “language model” and “large language model” interchangeably, but they may actually refer to different things as every LLM is an LM, but not every LM is an LLM.

In the past, we referred to models that calculate the likelihood of the next word in a sequence using n-grams as “language models.” Nowadays, “large language models” typically refers to transformer-based neural models with billions of parameters trained on massive datasets such as ChatGPT and LLaMA. These models are all generative language models. Encoder-only language models with around 100 million parameters, such as BERT, and simple n-gram models can be considered language models (LMs).

To simplify things, we can say that the term LLM refers to decoder-only models with more than 1 billion parameters and a generative feature. These two features emerged because recent studies have shown that when the models are scaled and trained with large datasets, they perform very well. Specifically, their zero- and few-shot performances improve, and they are able to follow given instructions very effectively with respect to size. Additionally, the generative feature allows us to approach any type of problem within this framework, as the input and output are in a free-text format, which has popularized prompt engineering. We can use an LLM to generate numeric predictions or even computer code for various NLP problems.

Current trends in LLMs include Reinforcement Learning from Human Feedback (RLHF).

We can formalize the steps of the RLHF paradigm as follows:

  • Self-supervised: Let the model gain knowledge on its own
  • Supervised: Provide information for the model to learn
  • Human feedback: Observe the model and correct its behavior

As shown in the following figure (Figure 10*.1*), the initial stage involves training vanilla pre-training language models (PTLMs). In this stage, we use a specific self-supervised objective function, such as next-word prediction, to enhance the model’s language understanding capacity. In the second step, we adapt the model to follow natural language instructions by utilizing instruction-following datasets. Through this process, the language model gains knowledge of various tasks and becomes capable of solving unfamiliar problems.

Figure 10.1 – A high-level representation of RLHF

In the final stage (step 3), a distinct feature is introduced compared to the traditional pre-training and fine-tuning two-stage process. This last stage highlights the importance of a reward function and policy optimization for reinforcement learning (RL). Human annotators actively participate in experiments with the model and rank its results. These rankings are used to evaluate the text outputs generated by the language model. In the field of RLHF, one of the primary research areas focuses on developing a reward model that accurately represents these human preferences.

With the release of ChatGPT, there has been a great deal of excitement both within and beyond the field regarding LLMs. To put it simply, a large language model is essentially just a bigger version of a language model, as the name suggests. However, the exact size of “large” is still unclear. To give you an idea of scale, models with fewer than billions of parameters are not considered large today. It’s important to note that this notion of scale is completely relative. A billion-parameter model may be considered large now, but in a few years or even months, it may no longer hold true.

Not only the scale but also other metrics affect the quality of these models. The quality, in this case, is not quantified as numbers reported in scientific articles because there is currently no reliable measurement for understanding the quality of the output. However, we can still find ways to measure it. Let’s consider a scenario where you want an Open Book Question Answering (OBQA) model to be able to answer questions related to a specific context. In this case, you may expect the model to provide exact answers directly taken from the respective context. However, for other use cases, you may prefer the answers to be more conversational and delivered in a specific tone of voice rather than being extracted from the context.

Based on the example provided, if you require a conversational OBQA model, you may reject a model with higher accuracy and instead choose one that offers the desired tone of voice and writing style.

In the following example, we see the output of an encoder-based QA model fine-tuned with the SQuAD dataset (https://huggingface.co/datasets/squad):

Figure 10.2 – Question answering using https://huggingface.co/distilbert/distilbert-base-cased-distilled-squad

The following example is taken from the ChatGPT interface:

Figure 10.3 – Question answering using ChatGPT

As you can see from the preceding figure, the first model is just a question-answering fine-tuned model but the second one is an LLM that also can understand the instructions you have given to it.

Supervised learning, depicted as step 2 in Figure 10*.1*, has proven to be beneficial in the development of models such as GPT and T5. These models are capable of learning multiple tasks by utilizing prompts. However, a new training scheme, shown in step 3, has been introduced to enhance the models’ ability to produce results in a more desired manner. This approach incorporates human feedback to guide the models. Similar to many reinforcement learning approaches, a reward function is utilized to accomplish this task. The reward function plays a crucial role in guiding the model’s learning process and enabling it to generate the desired output. In the context of NLP, it is important to model the reward function itself.

A model trained on textual examples determines preferences, which requires training using labeled data. Without a reward model, an LM that solely relies on human-labeled data would be insufficient for training. However, only using the reward model to fine-tune results leads to lower ratings for larger models. An LM can take advantage of this and generate misleading outputs, which highlights the need for an original model to stay aligned and prevent such situations. The best approach is to apply a penalty based on the KL divergence between the original model and the reinforcement learning (RL) tuned model. However, the story behind LLMs is not only about this. Very large models come with risks; when trained on open web data, they naturally contain biases. For production purposes, it is important to augment these models with another model that can identify harmful, toxic, or abusive content. Otherwise, even with a well-rated and conversational model, there is still a possibility of unintentionally offending individuals.

T0 is a family of open-source models that are vastly trained on many tasks. In the following figure, you can see the related training sets used to train them.

Figure 10.4 – T0 training sets from https://huggingface.co/bigscience/T0

As an example, we will try to use T0_3B, which is a 3-billion-parameter version of the T0 series. To demonstrate its capabilities, we will try to examine two different case scenarios: coreference resolution and sentiment analysis.

You need to have good GPU capacity, such as A100, to run the following code. First, install the necessary libraries:

!pip install transformers sentencepiece

Second, we need to load the model and the respective tokenizer:

from transformers import(AutoTokenizer,
AutoModelForSeq2SeqLM)
tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")

Afterward, we can use it with the respective instruction prompt for sentiment analysis:

inputs = tokenizer.encode("Is this review positive or negative? Review: This book covers many different ascpect of NLP. I highly recommend buying it!", return_tensors="pt")
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0]))
Output: Positive

As you can see from the instruction prompt, it is a sentiment analysis task. For coreference resolution, we get the following output:

Input: Meysam lives in Germany. He has been living in Berlin for a long time. In the previous sentence, decide who 'he' is referring to.
Output: Meysam
As you can see from the example, the model is capable of understanding the instructions that you give it. Natural instructions and instruction fine-tuning with the help of using different prompt alternatives (instead of only using the same prompt for training) broadens the model's capabilities.

Well done! Now we will fine-tune an LLM, LLaMA, in the next section.

The main purpose of LLMs is to provide zero-shot task generalization with prompt engineering. However, we may still want to fine-tune them for specific tasks. Here, we will fine-tune the most popular open source language model, LLaMA, with the SQuAD dataset. Please note that we can merge different datasets into a single dataset with formatting and train the model. If you want, you can try this in a multi-task experiment. Here, for the sake of simplicity, we are proceeding with a single dataset.

We will use the following techniques for fine-tuning an LLM:

  • PEFT: As we discussed in Chapter 9, we will update fewer parameters in the model instead of the entire model using LoRA. The key benefit of Parameter Efficient Fine-Tuning (PEFT) is its significant reduction in the number of parameters to be trained. This reduction accelerates and simplifies the training process – a valuable attribute for large-scale machine learning projects such as LLM where time and efficiency are vital.
  • Model quantization: As we discussed in Chapter 9, we will apply methods that use less memory, such as using 4-bit variables instead of 32-bit variables in model parameters using bitsandbytes. Quantization, a method that reduces bit numbers, optimizes computational and memory costs by using low-precision data types such as 8-bit integers rather than 32-bit floating points. This results in less memory usage, lower energy consumption, and faster operations. It also supports embedded devices’ integer data types. Essentially, it’s about transitioning from a high-precision to a low-precision data type.
  • TRL: We will have a simpler, faster fine-tuning experience with the TRL package with efficient memory usage. The TRL library, supported by the Hugging Face team, is a full stack tool for fine-tuning and aligning transformer language and diffusion models using methods such as Supervised Fine-Tuning (SFT), Reward Modeling (RM), and Proximal Policy Optimization (PPO), as well as Direct Preference Optimization (DPO). Install the necessary packages as follows:
    !pip install accelerate ==0.25.0 bitsandbytes ==0.42.0 peft ==0.7.1 transformers ==4.35.2 trl ==0.7.9
    And import the functions and classes:
    import os, torch
    from trl import SFTTrainer
    from peft import LoraConfig, PeftModel
    from datasets import load_dataset
    from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TrainingArguments,
    BitsAndBytesConfig,
    HfArgumentParser,
    pipeline,
    )

Building instruction-following datasets is an important step when training an LLM. The quality and variety of data are essential. Having data of various types and fields will enhance the model in terms of multi-task objectives and zero-shot generalization. At this stage, we will perform a training experiment using the SQuAD dataset to maintain simplicity in the process. However, in your own scenarios, you can incorporate different tasks and expand the range of data.

In the following code, we take 1,000 samples for training and 350 samples for evaluation. You can use the entire dataset in your run, but it will take a long time. Let’s do the following:

import pandas as pd
dataset = load_dataset("squad")
train=pd.DataFrame(dataset["train"].select(range(1000)))
val=pd.DataFrame(dataset["train"].select(range(1000,1350)))
train.iloc[:,2:].head()

Figure 10.5 – SQuAD dataset screenshot

In the output, you can see the presence of context, question, and answer. It is important to remember that during the fine-tuning of the T5 model in the preceding chapters, we transformed the dataset into a text-to-text format. Now, we have just a single text. We must structure the dataset according to the LLaMA template as outlined here:

<s>[INST] Context: ... Question ? [/INST] Answer... </s>

We transform every triple (context, question, answer) in a string like <s> [INST] ... [/INST]... </s>. Let us transform the dataset:

train["text"]=train.apply(lambda x:
f"<s>[INST]Context: {x.context} \
Question: {x.question}[/INST] \
{x.answers['text'][0]} </s>",
axis=1)
val["text"]=val.apply(lambda x:
f"<s>[INST]Context: {x.context} \
Question: {x.question}[/INST] \
{x.answers['text'][0]} </s>",
axis=1)
from datasets import Dataset
train_dataset=Dataset.from_pandas(train[["text"]])
eval_dataset=Dataset.from_pandas(val[["text"]])

Please note that in the preceding code, we have added a new column called "text". We have re-expressed all the content (context, question, answer) in that column, which will be the main focus of the model.

Now we will set up LoRA. We previously used LoRA in Chapter 9 to optimize the T5 model. It is a technique that focuses on reducing the size of models, enabling calculations on less memory. We set it as follows:

peft_config = LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=64,
bias="none",
task_type="CAUSAL_LM",
)

Quantization is a technique that reduces numerical precision in models. Instead of using high-precision data types such as 32-bit floating-point numbers, quantization uses lower-precision data types such as 8-bit or 4-bit integers. This reduces memory usage and speeds up model execution while maintaining accuracy. We set it as follows:

compute_dtype = getattr(torch, "float16")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type=»nf4»,
bnb_4bit_compute_dtype=compute_dtype,
bnb_4bit_use_double_quant=False,
)

Now we get the LLaMA model. To access the LLaMA model, we follow these steps:

  1. LLaMa is a gated model, which means that access needs to be granted before it can be used. To request access, please follow this link: https://huggingface.co/meta-llama/Llama-2-7b-chat-hf.
  2. Once access has been granted, you will need to authenticate with the Hugging Face Hub. To do this, create a token in your Settings tab (https://huggingface.co/settings/tokens) or navigate to Hugging Face Settings > Access Tokens > New token and generate a new read token. Make sure to copy this access token as instructed. You will encounter the following screen:

Figure 10.6 – Access LLaMA 2 on Hugging Face

We pass our read token to get the permission as follows:

from huggingface_hub import login
access_token_read = "hf_BLA_BLA" #<-paste your token here
login(token = access_token_read)
  1. Now it is time to load the LLaMA model. We load a particular LLaMA checkpoint, meta-llama/Llama-2-7b-chat-hf, and its tokenizer
    # LLaMA model
    model_name="meta-llama/Llama-2-7b-chat-hf"
    model = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=bnb_config,
    device_map={"": 0}
    )
    model.config.use_cache = False
    model.config.pretraining_tp = 1
    # Tokenizer
    tokenizer = AutoTokenizer.from_pretrained(model_name,
    trust_remote_code=True)
    tokenizer.pad_token = tokenizer.eos_token
    tokenizer.padding_side = "right"
  2. We will use the SFTTRainer class of the trl library, which is a very talented wrapper function. We just pass the PEFT and quantization objects that we have defined to this trainer. We also tell the trainer to focus on the text column and not
    training_arguments = TrainingArguments(
    output_dir="my_llama",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=1,
    optim="paged_adamw_32bit",
    evaluation_strategy="epoch",
    learning_rate=2e-4,
    weight_decay=0.001,
    fp16=True,
    bf16=True, # if you have A100 resource, you can set it
    lr_scheduler_type="linear"
    )
    from trl import SFTTrainer
    trainer = SFTTrainer(
    model=model,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    peft_config=peft_config,
    dataset_text_field="text",
    max_seq_length=None,
    tokenizer=tokenizer,
    args=training_arguments)
  3. Now we start the training process
    trainer.train()

Great job! You may see that the loss keeps increasing, which is not a good sign for training. This is because we are using a small portion of the dataset. When we use the entire dataset, we may see a better training process. We have just fine-tuned the LLaMA model.

Now let’s try the model with the inference code that follows. We pass the context and question as follows:

prompt='''
Context:Architecturally, the school has a Catholic character. Atop the Main Building's gold dome is a golden statue of the Virgin Mary.
Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes".
Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection.
It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858.
At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome),
is a simple, modern stone statue of Mary.
Question:To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?
'''
# Expected answer: Saint Bernadette Soubirous
squad_llama = pipeline(task="text-generation",
model=model,
tokenizer=tokenizer,
max_length=350)
result = squad_llama(f"<s>[INST] {prompt} [/INST]")
print(result[0]['generated_text'])
Output: Saint Bernadette Soubirous

Perfect! We have got what we expected (Saint Bernadette Soubirous). It is just a straightforward test with a basic example. We need to assess LLM using effective evaluation techniques. Currently, our main focus is not on evaluating LLM, as it is beyond the scope of this chapter.

In this chapter, we discussed the concept of LLMs. We explored how models such as T5 can generate diverse responses when given different prompts. Additionally, we successfully trained LLaMA, an open-source language model, using the PEFT and quantization techniques. Although we didn’t extensively delve into LLMs in this chapter, we touched upon them to some extent. Looking ahead, the next chapter will delve into explainable artificial intelligence, specifically from the perspective of natural language processing.