Skip to content
ImagineWorld

Parameter Efficient Fine-Tuning

node_idnode-book_mastering-transformers_chapter-09-parameter-efficient-fine-tuning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleParameter Efficient Fine-Tuning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Parameter Efficient Fine-Tuning

Section titled “Chapter 9 — Parameter Efficient Fine-Tuning”

Fine-tuning has become a prevalent modeling paradigm in AI, particularly in transfer learning. All of the experiments in this book up to this chapter have been based on updating all parameters. Therefore, it is more accurate to use the term full fine-tuning from now on (also called full model fine-tuning or full parameter fine-tuning).

In this chapter, we will look at partial fine-tuning strategies. As we consider the continuously increasing parameters of large language models (LLMs), fine-tuning and the inference of LLMs become prohibitively expensive. Full fine-tuning requires a complete update of all parameters, saving large models separately for each task. Unfortunately, this process is computationally expensive in terms of both memory and running time. For example, Bidirectional Encoder Representations from Transformers (BERT) has 300 million parameters, T5 has up to 11 billion, GPT has 175 billion, Pathways Language Model (PaLM) has 540 billion parameters, and so forth. Therefore, we need to think much more about Parameter-Efficient Fine-Tuning (PEFT).

In this chapter, we will cover the following topics:

  • What is PEFT?
  • Hands-on PEFT experiments

We will need the following packages:

  • adapter-transformers==3.2.1
  • transformers==4.29.0
  • peft==0.3.0
  • datasets==2.12.0

Before we start, let’s ask ourselves the following question: In the era of ChatGPT, we know that LLMs can solve many problems without the need for any additional updates or fine-tuning operations; so, do we still need fine-tuning operations?

Yes! We currently use models such as ChatGPT to efficiently solve general problems such as sentiment analysis, named-entity recognition (NER), and summarization. However, our industry or academia requires very specific natural language processing (NLP) tasks that are influenced by factors such as culture, domain, time, and geography. Studies (see Is ChatGPT a General-Purpose Natural Language Processing Task Solver?, Chengwei Qin et al.) have shown that fine-tuning a model outperforms ChatGPT-like language models. Therefore, it is better to fine-tune the model.

Additionally, it is possible to use relatively smaller models such as BERT or T5 by fine-tuning them for on-premises use within the company. This approach mitigates the risk of information security breaches. In summary, for now, it is necessary to use fine-tuning to meet our NLP needs.

The advantages of PEFT can be summarized as follows:

  • When dealing with multiple tasks, it is essential to use PEFT methods. Full fine-tuning produces distinct fine-tuned model parameters for each task, which can be costly when serving models that handle numerous tasks. PEFT makes it easy to switch tasks in deployment.
  • Parameter-efficient tuning allows for quick adaptation to new tasks without catastrophic forgetting, in addition to parameter savings. Since we only update the task-related parameters without modifying the parameters of the main model, the main models do not undergo considerable forgetting.
  • PEFT methods provide us with the chance to manage complicated procedures such as hyperparameter optimization when it comes to time and memory complexity. Even with high-performance hardware, performing full fine-tuning is not feasible in resource-intensive applications such as HPO.
  • Multi-task learning can be applied more easily using PEFT methods. Frameworks such as AdapterFusion leverage the knowledge from multiple source tasks to enhance performance on a target task.

In this chapter, we address PEFT methods, run a couple of experiments, and see the difference in terms of model performance and training efficiency. We also address the problem of whether we can achieve the same performance as full fine-tuning by training some of the parameters or other efficient fine-tuning methods. Let us first discuss PEFT approaches.

Several approaches have been developed to democratize LLMs during inference and fine-tuning. Some approaches other than partial fine-tuning are quantizations such as int8, distillation, and sparsification. These approaches reduce memory requirements for inference and fine-tuning. Recently, we have seen a great effort in the modification of models. these efforts, which are called PEFT, aim to keep the number of parameters updated as low as possible while maintaining comparable performance with full training. Although some PEFT studies have shown better results than full fine-tuning, it has been found that these successes can be sensitive to hyperparameters.

There are various PEFT approaches in the literature such as adapters, prompt-tuning, prefix-tuning, (IA)3, BitFit, and Low-rank Adaptation of Large Language Models (LoRA) to name a few. These approaches have been classified into three main categories in a survey (see Scaling Down to Scale Up: A Guide to Parameter-Efficient Fine-Tuning, Vladislav Lialin, Vijeta Deshpande, and Anna Rumshisky):

  • Additive methods:
  • Selective methods
  • Low-rank fine-tuning:

Additive methods add new task-specific neural weights (parameters) to transformers. The weights of the original model are kept frozen and just shared between tasks. Only these added weights are trained during the fine-tuning stage, which leads to < %1 parameter efficiency, which also supports multi-task learning. To reduce the parameters to be updated, bottleneck architecture can be applied in this model family, projecting the original dimension to a lower degree and mapping back to the original again. As the added weights can be shared specifically for tasks, it is an easy-to-use method. adapter-transformers is a powerful library for this purpose. We will use it for hands-on study.

Adapters can be roughly classified as serial and parallel. Serial adapters are the adapter layers added in a sequential manner. Adapter tuning (described in the paper Parameter-efficient transfer learning for NLP, Neil Houlsby et al., International Conference on Machine Learning, PMLR) tuning (described in Prefix-tuning: Optimizing continuous prompts for generation, Xiang Lisa Li and Percy Liang) and prompt-tuning (described in The power of scale for parameter-efficient prompt tuning, Brian Lester, Rami Al-Rfou, and Noah Constant) attach additional tokens to input on the hidden layer of the model in a parallel manner. While prefix-tuning appends a learnable vector to the attention head at each transformer layer, prompt-tuning appends this vector only to the input embedding. Prefix-tuning and prompt-tuning utilize soft-prompting, which means a trainable continuous prompt is added instead of adding a discrete word or token as we do during the prompt engineering phase. With training, we expect the model to estimate the embedding of this soft (or continuous) prompt. The disadvantage of such affixes (prefix, infix, and suffix) reduce the model’s usable sequence length.

Approaches in this family do not add a new parameter to language models and update only the selected parameter based on certain methods. Bias-only, BitFit, for instance, trains only bias terms on the network while freezing all other parameters. Sparse fine-tuning methods, such as FISH Mask, select some parameters of the model based on a formula such as Fisher information in FISH Mask. SparseAdapter applies the sparsification method to added adapters instead of the main model. Thus, it is considered both a selective and additive method.

The low-rank structure is very common in the AI field. Many tasks have a certain low-rank structure, which helps to perform various computations rapidly in a low-rank subspace. The most important PEFT method of this family is LoRA (see LoRA: Low-Rank Adaptation of Large Language Models, Edward J. Hu, et al.). It performs low-rank fine-tuning by training trainable pairs of rank decomposition matrices for Wq (query) and Wv (value) matrices in the self-attention mechanism. All pretrained model parameters are kept frozen, and only these two Wq (query) and Wv (value) matrices are left trainable with reparameterization. LoRA decomposes them into a product of two low-rank matrices.

This reparameterization process reduces the number of trainable parameters significantly due to its selective and low-rank nature, while also achieving performance levels comparable to full training. The main motivation for this approach is the latency problem for additive adapter models. Adapter-based models raise inference latency problems as they have to process sequentially and LLM relies on hardware parallelism. Since the adapter layer must be computed in addition to the base model, this inevitably introduces additional latency. These serial adapter models are suitable for model fine-tuning, especially on a single GPU.

The authors of AdaLoRA (see Adaptive Budget Allocation for Parameter-Efficient Fine-Tuning, Qingru Zhang et al.) proposed a variant of LoRA to enhance the LoRA approach in two ways. Firstly, AdaLoRA fine-tunes LLM by attributing different importance to matrices and pruning redundant singular values. This approach underlines that weight matrices have varying levels of importance across different modules and layers when fine-tuning pretrained models. Secondly, while LoRA applies SVD (Singular Value Decomposition) to query and value projections only, AdaLoRA applies it to all weight matrices to improve its performance.

Now, it is time to get our hands dirty with some experiments. We will do this in the next section.

In this section, you may encounter some problems or errors when using the CPU. We suggest you use GPU for training. We will solve two different classification problems using PEFT. Throughout the book, we have mentioned the sentiment analysis problem several times. Now, to diversify our experiments, let’s also include the NLI (Natural Language Inference) problem.

We will conduct two experiments as follows:

  • Efficiently fine-tuning the BERT model for an IMDb sentiment dataset with adapter-transformers
  • Efficiently fine-tune FLAN-T5 for an NLI task with the LoRA framework

Fine-tuning a BERT checkpoint with adapter tuning

Section titled “Fine-tuning a BERT checkpoint with adapter tuning”

For the first problem, we will specifically address the IMDb sentiment task that we already fine-tuned with full fine-tuning methods before. This way, we will have the opportunity to compare:

  1. Start with installing the necessary packages
    !pip install datasets==2.12.0 adapter-transformers==3.2.1
    As you can see, we do not install HF’s transformers packages since adapter-transformers is used as a drop-in replacement for HF’s transformers library.
  2. Now, we will import the
    import torch, os
    from torch import cuda
    import numpy as np
    from transformers import AdapterTrainer
    from transformers import (BertTokenizerFast,
    BertForSequenceClassification Trainer)
  3. TrainingArgumentsfrom datasets import load_dataset. We will fine-tune a bert-base-uncased
    model_path= 'bert-base-uncased'
    tokenizer =BertTokenizerFast.from_pretrained(model_path)
  4. As in the previous hands-on experiment, we load smaller portions from the IMDb dataset: 4K for training, 1K for testing, and 1K
    imdb_train= load_dataset('imdb',
    split="train[:2000]+train[-2000:]")
    imdb_test= load_dataset('imdb',
    split="test[:500]+test[-500:]")
    imdb_val= load_dataset('imdb',
    split="test[500:1000]+test[-1000:-500]")
  5. We define tokenize_it() function to encode the datasets
    def tokenize_it(e):
    return tokenizer(e['text'],
    padding=True,
    truncation=True)
    enc_train=imdb_train.map(tokenize_it,
    batched=True, batch_size=1000)
    enc_test=imdb_test.map(tokenize_it,
    batched=True, batch_size=1000)
    enc_val=imdb_val.map(tokenize_it,
    batched=True, batch_size=1000)
    Training argument initialization will be the same as in the previous vanilla training. The only different hyperparameter is learning_rate set as 2e-4. Recall that in our other vanilla fine-tuning process, we mostly tended to select a lower learning_rate of around 2e-5. Selecting higher learning_rate values can be risky for full fine-tuning as we update entire parameters, which leads to catastrophic forgetting. But now, we are safe as we only update some added parameters and do not touch the entire BERT model. So, you can select a higher learning_rate if you want.
  6. We define the training arguments
    training_args = TrainingArguments(
    "/tmp",
    do_train=True,
    do_eval=True,
    num_train_epochs=3,
    learning_rate=2e-4,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    fp16=True,
    load_best_model_at_end=True
    )
  7. We will now define the metrics that we want to monitor during training in the compute() function. For now, let’s keep it simple and monitor the Accuracy
    def compute_acc(p):
    preds = np.argmax(p.predictions, axis=1)
    acc={"Accuracy": (preds == p.label_ids).mean()}
    return acc
  8. We load the bert-base-uncased checkpoint
    from transformers import BertModelWithHeads
    model = BertModelWithHeads.from_pretrained(model_path)
  9. Now, we will define an adapter named "imdb_sentiment". Thus, we will freeze all other original parameters in modeling and only allow the update of the
    model.add_adapter("imdb_sentiment")
  10. We will add a trainable classification head and associate it with an added adapter, namely imdb_sentiment. For this head, we will also specify how many classes it
    model.add_classification_head("imdb_sentiment",num_labels=2)
  11. Now, we inform the training process that the added adapter will be trained as in the following code:
    model.train_adapter("imdb_sentiment")
    We do this because, in some cases, we may not want to train the added parameters. We may especially need this during the multi-task learning phase. Let us see the parameter efficiency as follows:
    trainable_params=model\
    .num_parameters(only_trainable=True)/(2**20)
    all_params=model.num_parameters() /2**20
    print(f"{all_params=:.2f} M\n"+
    f"{trainable_params=:.2f} M\n"+
    f"The efficiency ratio is \
    {100*trainable_params/all_params:.2f}%")
    The output is as follows:
    all_params=105.83 M
    trainable_params=1.42 M
    the efficiency ratio = 1.34%
    As you can see, we have a parameter gain of about 1.34%.
  12. We define AdapterTrainer instead of HF’s vanilla Trainer class. The following code triggers the
    trainer = AdapterTrainer(
    model=model,
    args=training_args,
    train_dataset=enc_train,
    eval_dataset=enc_val,
    compute_metrics=compute_acc)
    trainer.train()
    The output of the training is as follows:

Figure 9.1 – Training with adapter-transformers

  1. As we can see, we fine-tune the model in 1.34 minutes for 3 epochs. Keep them in mind. Let’s look at the overall
    import pandas as pd
    q=[trainer.evaluate(eval_dataset=data) for data in\
    [enc_train, enc_val, enc_test]]
    pd.DataFrame(q, index=["train","val","test"]).iloc[:,:5]
    The output of the execution is as follows:

Figure 9.2 – Performance with adapter-transformers

Well, our test accuracy performance is about 0.912.

The results suggest that the model has been fine-tuned quickly and successfully. But is it really fast and successful? We need to look at the results of experiments with vanilla fine-tuning. We have already conducted this IMDb experiment identically in Chapter 8. Let’s just recall the results of this experiment. The following screenshot shows the outputs generated by the vanilla fine-tuning process for three epochs:

Figure 9.3 – Training with vanilla Transformers (without adapters)

With vanilla full fine-tuning, the training process takes 8.15 minutes while the fine-tuning of the model takes 1.34 minutes. As we can see, the accuracy performances are comparable. So, we can safely say that PEFT fine-tuning is really fast and successful!

Efficiently fine-tune FLAN-T5 for an NLI task with Lora

Section titled “Efficiently fine-tune FLAN-T5 for an NLI task with Lora”

NLI involves determining whether a given hypothesis is true (entailment), false (contradiction), or undetermined (neutral) given a corresponding premise.

We will use the SNLI project for the task. The SNLI project (https://nlp.stanford.edu/projects/snli/) is a collection of 570,000 sentence pairs annotated with the labels contradiction, entailment, and neutral.

An example for each category is as follows:

premisehypothesislabel
A man inspects the uniform of a figure in a country.The man is sleeping.Contradiction
An older and younger man smiling.Two men are smiling and laughing at the cats playing on the floor.Neutral
A soccer game with multiple males playing.Some men are playing a sport.Entailment

Table 9.1 – Three examples from the Original SNLI dataset

As seen in the preceding table, we are given premise and hypothesis and the task is to map the sentence pair to a proper category. We will efficiently train the FLAN-T5 model for this purpose starting with installing the necessary libraries:

  1. We start by installing the necessary
    !pip install transformers==4.29.0 peft==0.3.0 datasets==2.12.0
  2. Let us import
    from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
    from transformers import (default_data_collator,
    get_linear_schedule_with_warmup)
    from peft import (get_peft_config, get_peft_model,
    get_peft_model_state_dict,LoraConfig, TaskType)
    import torch, os
    from torch.utils.data import DataLoader
    from tqdm import tqdm
    import pandas as pd
    from datasets import (load_dataset,
    Dataset, DatasetDict)
  3. There are 570K examples in the SNLI dataset. We will work with a 1% sample for faster prototyping. The same code can be used for the entire
    dataset = load_dataset("snli")
    snli_sampled=pd.DataFrame(dataset["train"])
    snli_sampled=snli_sampled.sample(frac=0.01)
  4. We will see label distribution of the sampled SNLI dataset
    snli_sampled.label.value_counts()
    The output is as follows:
    2 1870
    1 1825
    0 1798
    -1 9
    Name: label, dtype: int64
  5. Eliminate unlabeled instances (with the - 1
    snli_sampled= snli_sampled[snli_sampled.label>-1]
  6. The label names are
    names=dataset["train"].features["label"].names
    Names
    Output: ['entailment', 'neutral', 'contradiction']
  7. We will need a dictionary of id2label:
    mapp=dict(enumerate(names))
    mapp
    OUTPUT: {0: 'entailment',
    1: 'neutral',
    2: 'contradiction'}
    The dataset is ready. However, the current dataset format is suitable for text classification. We could fine-tune a BERT model for the task, but in this experiment, we will treat the task differently and fine-tune a text-to-text model, flan-t5, by rephrasing instances. We already introduced flan-t5 as a generative model in Chapter 4. FLAN Framework (https://github.com/google-research/FLAN) was able to model 1,800 different instruction fine-tuning tasks simultaneously without changing the model architecture. The framework explored the T5 model’s capacity for improving the ability of language models at scale to perform zero-shot tasks based purely on instructions. As FLAN-T5 is a text-to-text model, we need to convert our current NLP task (text1, text2-> label) into a text-to-text instruction format (text-in->text-out) by rephrasing it. Therefore, we need to cast both the input and output as text using a template. For this, we will use the following prompt method. You can improve this prompt method with more interesting and alternative expressions and repeat the experiment.
  8. Let’s run the following rephrasing code and examine the new form of
    snli_sampled_df= pd.DataFrame(snli_sampled)
    snli_sampled_df["text"]= snli_sampled_df\
    .apply(lambda x: "S1:" +x.premise
    +"S2:"+x.hypothesis+
    ". The relation between S1 and S2 is labeled "+
    "as entailment, neutral or contradiction ?",
    axis=1)
    snli_sampled_df["label"]=snli_sampled_df\
    .apply(lambda x: f"It is {mapp[x.label]}",
    axis=1)
    The output looks like the following:

Figure 9.4 – Rephrasing the task as task-instruction of SNLI dataset

  1. Now, we have two new text and label String where text includes a rephrased form of premise and hypothesis. Likewise, label is a rephrased form of the original label (1-> "it is neutral"). Let us examine the last resulting text as follows:
    S1:Three men in uniform walk around town. S2:Three men rob the residents. The relation between S1 and S2 is labeled as entailment, neutral or contradiction ?.
    The text field has both premise and hypothesis. We named them S1 and S2 in order, but we could have named their original names, premise and hypothesis. You can try it differently. We also inject a question (e.g., The relation between S1 and S2 I... ?) to direct the T5 model to the targeted output. To direct the model’s output to desired selections, we provided hints (… is labeled as entailment, neutral, or contradiction ?) for potential tags that might be outputted by the model because generative language models are prone to producing random words or hallucinations. We try to narrow down the output space.
  2. We divide the dataset into two parts: training (70%) and validation (30%) and store them in the snli_sampled_dict dictionary object
    CUT=snli_sampled_df.shape[0]*7//10
    print(f"Training set size is {CUT}")
    print(f"Validation set size is \
    {snli_sampled_df.shape[0]-CUT}")
    print(f"Total size is {snli_sampled_df.shape[0]}")
    snli_sampled_dict= DatasetDict({
    "train":
    Dataset.from_pandas(snli_sampled_df[:CUT])
    "validation":
    Dataset.from_pandas(snli_sampled_df[CUT:])
    })
    The output is as follows:
    Training set size is 3847
    Validation set size is 1650
    Total size is 5497
  3. The tokenization and encoding parts of our work are slightly different from our text (sentiment) and token classification (NER) problems. Because both the input and the output are natural language, we need to pass both parts through the tokenizer to encode them. The following preprocess_function() function performs this operation. We usually apply this process in all
    def preprocess_function(examples):
    inputs = examples["text"]
    targets = examples["label"]
    model_inputs = tokenizer(inputs,
    max_length=max_length,
    padding="max_length",
    truncation=True,
    return_tensors="pt")
    labels = tokenizer(targets,
    max_length=max_target_len,
    padding="max_length",
    truncation=True,
    return_tensors="pt")
    labels = labels["input_ids"]
    labels[labels == tokenizer.pad_token_id] = -100
    model_inputs["labels"] = labels
    return model_inputs
  4. Now, it’s time to choose the model. Model selection is a critical step because it must be compatible with your hardware resources. So, how do we choose a model based on hardware capacity? We can follow a rough formula for calculation. The formula is so simple that you will only need a GPU support of 10 times the number of parameters of a language model. For example, a BERT base model has 110 million parameters. It will cost you (110Mx10) 1.2 GB GPU. This is why the BERT base model is very comfortable with the latest resources. If we use the 3-billion-parameter google/flan-t5-xl model, the cost will be 3Bx10 = ~30 GB GPU (one parameter requires a 10-byte GPU). This is a very rough calculation. Likewise, flan-t5-base with 250M parameters (~2.5 GB GPU is needed) or flan-t5-large with 780M parameters (~8 GB GPU is needed) are the other calculations. As 16 GB GPU has become a widely common resource recently, we can start by training flan-t5-base in this experiment. We have commented out the other two bigger alternatives now. As I now have a NVIDIA A100 40 GB GPU, I can train the pipeline with flan-t5-xlarge later.
  5. Now, we load tokenizer
    model_name_or_path="google/flan-t5-base" # 250M parameters
    #model_name_or_path="google/flan-t5-large" #780M parameters
    #model_name_or_path="google/flan-t5-xl" # 3B parameters
    tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
  6. We will pass the snli_sample_dict object through the process function that I have prepared. There is a sequence length issue that needs to be considered carefully here: input and output size. For efficiency, I am trying to keep these values as small as possible but not damage the dataset, so that the model runs quickly. When we examine the dataset, we can see that the safe values for input and output sizes are around 150 and 10, respectively, based on the maximum token count. There is no input or output sequence exceeding these values. We can use the tokenizer.tokenize() function to measure it. We skip this calculation now.
  7. Let’s run the
    max_length = 150
    max_target_len=10
    snli_processed = snli_sampled_dict.map(
    preprocess_function,
    batched=True,
    num_proc=1,
    remove_columns=snli_sampled_dict["train"].column_names,
    load_from_cache_file=False,
    )
    train_dataset = snli_processed["train"]
    eval_dataset = snli_processed["validation"]
  8. Let’s have a quick look at the
    pd.DataFrame(train_dataset).head(3)
    The output is as follows:

Figure 9.5 – A processed dataset with tokenizer

As you can see, the input and label are converted from text (string) to a list of token IDs.

  1. Now, we will define DataLoader in the following code. When selecting the batch size (32 here), we were generous because we have plenty of space in our GPU capacity. If you receive a memory error with this value, choose a smaller batch size. However, keep in mind that smaller batch size values may affect modeling performance. The recent report suggests that a batch size of 16 or 32 gives the optimum performance. But it is subject to
    batch_size = 32
    train_dataloader = DataLoader(
    train_dataset,
    shuffle=True,
    collate_fn=default_data_collator,
    batch_size=batch_size,
    pin_memory=True)
    eval_dataloader = DataLoader(
    eval_dataset,
    collate_fn=default_data_collator,
    batch_size=batch_size,
    pin_memory=True)
  2. In the following code snippet, we will train our model with LoRA by controlling the with_peft=True variable. Then, for comparison, we will perform vanilla training without using LoRA. The main difference between the two trainings is that the get_peft_model() method indicates that the T5 model will be trained with LoRA. We arrange the necessary information regarding configuration with the LoraConfig object. Another difference is the learning_rate value. In our previous experiment with adapter-transformers, we kept the learning_rate higher when applying PEFT. In our current experiment, the learning_rate value is kept at 1e-3 with PEFT (Lora), while it is 5e-5 without it. For now, we will run this code with the with_peft=True setting. Then, we will set this Boolean value to False, which means we apply vanilla training to see the difference between the two:
    with_peft=True
    model = AutoModelForSeq2SeqLM\
    .from_pretrained(model_name_or_path)
    lr=2e-5
    if with_peft:
    lr=1e-3
    peft_config = LoraConfig(
    task_type=TaskType.SEQ_2_SEQ_LM,
    inference_mode=False,
    r=8,
    lora_alpha=32,
    lora_dropout=0.1)
    model = get_peft_model(model, peft_config)
    model.print_trainable_parameters()
    OUTPUT:
    trainable params: 884K || all params: 248M || trainable: 0.35%
    If the r variable in this code controls the degree of the low-rank subspace, the recommended value in the LoRA paper (Hu, Edward J., et al. “Lora: Low-rank adaptation of large language models.” arXiv preprint arXiv:2106.09685 (2021)) for this variable is 8. Accordingly, the number of trainable parameters is 884,736 for flan-t5-base. This accounts for 0.35% of the entire model parameters. If you set the r variable to 4 and try again, you will see that the number of trainable parameters decreases to 442,368 (0.17%). However, we need to control whether we sacrifice success or not while changing it.
  3. We will use a classic nested training and evaluation loop as suggested in the legacy code of the repository (https://huggingface.co/docs/peft)
    device="cuda"
    model = model.to(device)
    num_epochs = 3
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
    lr_scheduler = get_linear_schedule_with_warmup(
    optimizer=optimizer,
    num_warmup_steps=0,
    num_training_steps=\
    (len(train_dataloader) * num_epochs),)
    import time
    st = time.time()
    for epoch in range(num_epochs):
    model.train()
    total_loss = 0
    for step, batch in enumerate(tqdm(train_dataloader)):
    batch={k:v.to(device) for k, v in batch.items()}
    outputs = model(**batch)
    loss = outputs.loss
    total_loss += loss.detach().float()
    loss.backward()
    optimizer.step()
    lr_scheduler.step()
    optimizer.zero_grad()
    model.eval()
    eval_loss = 0
    eval_preds = []
    for step, batch in enumerate(tqdm(eval_dataloader)):
    batch = {k: v.to(device) for k, v in batch.items()}
    with torch.no_grad():
    outputs = model(**batch)
    loss = outputs.loss
    eval_loss += loss.detach().float()
    eval_preds.extend(
    tokenizer.batch_decode(
    torch.argmax(outputs.logits, -1)\
    .detach().cpu().numpy(),
    skip_special_tokens=True)
    )
    eval_loss_avg = eval_loss / len(eval_dataloader)
    train_loss_avg = total_loss / len(train_dataloader)
    print(f"{epoch=}-> {train_loss_avg=}\t {eval_loss_avg=}")
    et = time.time()
    elapsed_time = et - st
  4. Now, we will see the overall performance of PEFT with the
    zipped=zip(eval_preds,
    snli_sampled_dict["validation"]["label"])
    q=[real.strip() in pred.strip()\
    for pred,real in zipped]
    print(f"{model_name_or_path=}")
    print(f"{num_epochs=}")
    print(f"{elapsed_time=:.2f} seconds" \
    + (" with PEFT" if with_peft else " without PEFT"))
    print(f"Accuracy={sum(q)/len(q):.2f}")
    The output of the code is as follows:
    model_name_or_path='google/flan-t5-base'
    num_epochs = 3
    elapsed_time = 90.51 seconds with PEFT
    Accuracy = 0.86
  5. Now, let’s run the same code with with_peft=False. We will get the following output. As you can see, the training process without LoRA is worse than with LoRA in terms of The output is as follows:
    model_name_or_path='google/flan-t5-base'
    num_epochs=3
    elapsed_time=117.82 seconds without PEFT
    Accuracy=:84
    When we try scaling the model size, we obtain a result that looks like the following table:

With LoRA

Without LoRA

Model

# params

Time (sec.)

Accuracy

Time

Accuracy

flan-t5-base

250M

91

86

117

84

flan-t5-large

780M

280

90

369

90

flan-t5-xlarge

3B

879

92

OOM

OOM

Table 9.2 – Performance comparison of the FLAN-t5 checkpoints

Note

For flan-t5-xlarge, an out-of-memory (OOM) error was encountered with a batch size of 32. Lowering the batch size would resolve this error, but in this case, the comparison would become invalid.

This table tells us two things. First, training models with LoRA show good performance and efficiency in terms of speed without sacrificing accuracy. On the other hand, as we scale the model parameters by using larger models, our training slows down while our model performance begins to improve. As you can see, we obtained accuracy values of 86, 90, and 92, respectively for the base, large, and xlarge models of FLAN. But we could not say the model training with LoRA outperforms vanilla training, at least for now.

  1. Now, we will save the model and see the
    peft_model_path="my_lora_model"
    model.save_pretrained(peft_model_path)
    !ls -lh $peft_model_path
    total 9.2M
    -rw-r--r-- 1 root root 333 May 25 20:22 adapter_config.json
    -rw-r--r-- 1 root root 3.5M May 25 20:22 adapter_model.bin

Note

LoRA is a smaller model that can be trained more quickly. However, loading the base model and the LoRA model separately may cause delays in inference. To minimize these delays, the PEFT library includes a function called merge_and_unload(). This function merges the adapter weights with the base model, making it easier to use the merged model as a standalone model.

  1. Merging and saving the model is
    model = model.merge_and_unload()
    model.save_pretrained("my_lora_model_merged")
  2. Loading the merged and saved model is
    model = AutoModelForSeq2SeqLM\
    .from_pretrained("my_lora_model_merged",
    load_in_8bit=True)
  3. As you can see, the adapter model only allocates 3.5M instead of a 500 MB file. Let’s load the saved model and infer it
    from peft import PeftModel, PeftConfig
    config = PeftConfig.from_pretrained(peft_model_path)
    model = AutoModelForSeq2SeqLM\
    .from_pretrained(config.base_model_name_or_path)
    model = PeftModel.from_pretrained(model,peft_model_path)
    model.eval()
    my_text= snli_sampled_dict["validation"]["text"][0]
    my_label= snli_sampled_dict["validation"]["label"][0]
    print(f"{my_text=}")
    print(f"{my_label=}")
    The output is as follows:
    My_text: S1:A girl wearing a black jacket and pink boots is poking in the water of the creek with a stick, from the creek bank.S2:The girl is poking around in the creek trying to find something that she lost. The relation between S1 and S2 is labeled as entailment, neutral or contradiction ?
    My_label: It is neutral.
  4. Let us my_text
    inputs = tokenizer(my_text, return_tensors="pt")
    with torch.no_grad():
    outputs = model.generate(
    input_ids=inputs["input_ids"],
    max_new_tokens=10)
    print(tokenizer.batch_decode(
    outputs.detach().cpu().numpy(),
    skip_special_tokens=True))
    ['It is neutral'] # prediction

We successfully predicted the case. We will now discuss quantized LoRA.

With the increasing number of parameters in LLMs, there has been a growing push to find more efficient and memory-friendly methods. One recent study proposed the QLoRA model (see QLoRA: Efficient fine-tuning of quantized LLMs, Tim Dettmers et al.), which builds upon the already efficient LoRA model. This approach has gained widespread use in LLMs. QLoRA operates by quantizing the LLM to 4 bits, which significantly reduces the model’s memory usage compared to LoRA. The quantized LLM is then fine-tuned using the LoRA approach, which enables the refined model to maintain most of the accuracy of the original LLM while being considerably faster and smaller.

To use QLoRA, simply initialize the model with the following code snippet. The remaining code is identical to the preceding code. Please note that the code requires the bitsandbytes module, which can be installed as follows:

!pip install bitsandbytes

Replace the last two lines of code from Step 17 with the following code:

from transformers import BitsAndBytesConfig
from peft import prepare_model_for_kbit_training
from transformers import AutoModelForSeq2SeqLM
model_name = "google/flan-t5-base"
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
model = AutoModelForSeq2SeqLM\
.from_pretrained(model_name_or_path,
quantization_config=bnb_config,
device_map={"":0})
model.gradient_checkpointing_enable()
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, peft_config)

Please restart this process from Step 17 and see how we can get a better running time while maintaining most of the accuracy of the original model and LoRA.

Well done! Congratulations! With the help of PEFT, we have successfully solved two different problems, achieving the same level of success without having to train the entire language model and saving time in the process.

In this chapter, we discussed how to make the fine-tuning process more effective with PEFT. We covered three different PEFT methods: additive, selective, and low-rank. We utilized the adapter-transformers and HF’s PEFT framework for the hands-on experiments. We took text classification and NLI tasks and solved them with two Python PEFT libraries.

Besides their benefits, LLMs place big barriers in front of us such as training, fine-tuning, and inference. How to overcome these barriers is an important field of study. In the future, we will focus on how to handle, control, and utilize LLMs, as well as how to democratize them. In this chapter, we only focused on how to efficiently fine-tune them, but there are many aspects that we can work on!

In the next chapter, we will discuss how to work with LLMs.

  • Zaken, Elad Ben, Shauli Ravfogel, and Yoav Goldberg. “ Bitfit: Simple parameter-efficient fine-tuning for transformer-based masked language-models.” arXiv preprint arXiv:2106.10199 (2021).
  • Sung, Yi-Lin, Varun Nair, and Colin A. Raffel. “ Training neural networks with fixed sparse masks.” Advances in Neural Information Processing Systems 34 (2021): 24193-24205.
  • He, Shwai, et al. “ Sparseadapter: An easy approach for improving the parameter-efficiency of adapters.” arXiv preprint arXiv:2210.04284 (2022).