Lora

gpu-accelerationretrieval-augmented-generationllm-inferencetensorrtgemmanvidia-generative-ai-exampleslarge-language-modelsmicroservicetriton-inference-serverLLMfinetuningragnemo

Gemma Parameter Efficient Fine-Tuning with LoRA using NeMo Framework

Gemma is a groundbreaking new open model in the Gemini family of models from Google. Gemma is just as powerful as previous models but compact enough to run locally on NVIDIA RTX GPUs. Gemma is available in 2 sizes: 2B and 7B parameters. With NVIDIA NeMo, you can customize Gemma to fit your usecase and deploy an optimized model on your NVIDIA GPU.

In this tutorial, we'll go over a specific kind of customization -- Low-rank adapter tuning to follow a specific output format (also known as LoRA). To learn how to perform full parameter supervised fine-tuning for instruction following (also known as SFT), see the companion notebook. For LoRA, we'll perform all operations within the notebook on a single GPU. The compute resources needed for training depend on which Gemma model you use. For the 7 billion parameter variant of Gemma, you'll need a GPU with 80GB of memory. For the 2 billion parameter model, 40GB will do.

We'll also learn how to export your custom model to TensorRT-LLM, an open-source library that accelerates and optimizes inference performance of the latest LLMs on the NVIDIA AI platform.

Introduction

LoRA tuning is a parameter efficient method for fine-tuning models, where we freeze the base model parameters and update an auxiliary "adapter" with many fewer weights. At inference time, the adapter weights are combined with the base model weights to produce a new model, customized for a particular use case or dataset. Because this adapter is so much smaller than the base model, it can be trained with far fewer resources than it would take to fine-tune the entire model. In this notebook, we'll show you how to LoRA-tune small models like the Gemma models on a single A100 GPU.

For this example, we're going to tune our Gemma model on the PubMedQA dataset, a Question Answering dataset for biomedical texts. We'll see later on that our base model performs pretty poorly on this dataset -- not necessarily because it can't accurately extract the answers from the context, but because it fails to respond in the "yes/no/maybe" format expected. With LoRA finetuning, we'll modify our model to respond in the way we need for our task.

Download the base model

For all of our customization and deployment processes, we'll need to start off with a pre-trained version of Gemma in the .nemo format. You can download the base model in .nemo format from the NVIDIA GPU Cloud, or convert checkpoints from another framework into a .nemo file. You can choose to use the 2B parameter or 7B parameter Gemma models for this notebook -- the 2B model will be faster to customize, but the 7B model will be more capable.

You can download either model from the NVIDIA NGC Catalog, using the NGC CLI. The instructions to install and configure the NGC CLI can be found here.

To download the model, execute one of the following commands, based on which model you want to use:

ngc registry model download-version "nvidia/nemo/gemma_2b_base:1.1"

or

ngc registry model download-version "nvidia/nemo/gemma_7b_base:1.1"

Getting NeMo Framework

NVIDIA NeMo Framework is a generative AI framework built for researchers and PyTorch developers working on large language models (LLMs), multimodal models (MM), automatic speech recognition (ASR), and text-to-speech synthesis (TTS). The primary objective of NeMo is to provide a scalable framework for researchers and developers from industry and academia to more easily implement and design new generative AI models by being able to leverage existing code and pretrained models.

If you haven't already, you can pull a container that includes the version of NeMo Framework and all dependencies needed for this notebook with the following:

docker pull nvcr.io/nvidia/nemo:24.01.gemma

The best way to run this notebook is from within the container. You can do that by launching the container with the following command

docker run -it --rm --gpus all --ipc=host --network host -v $(pwd):/workspace nvcr.io/nvidia/nemo:24.01.gemma

Then, from within the container, start the jupyter server with

jupyter lab --no-browser --port=8080 --allow-root --ip 0.0.0.0

Data Preparation

First let's download the data, and use the provided script to divide it into train/validation/test splits

[ ]

Let's look at a sample of our training data

[ ]

As we can see, the data is in json format and includes several different fields and labels. For doing parameter efficient fine-tuning with NeMo Framework, we need the data in jsonl format. We also need to reformat our dataset into input and output pairs so that we can tune our model in a supervised way. The helper functions below take care of extracting and reformatting the raw data and writing out the jsonl file.

[ ]
[ ]

Here's an example of what the data looks like after formatting

[ ]

Configuration and Training

NeMo Framework uses config objects to control many of its operations, which allows you to quickly see what options you can change and carry out different experiments. We can start by downloading an example config file from github.

[ ]

Now we'll read in this default config file with Hydra, and apply an override that enables the use of Megatron core.

[ ]
[ ]

Let's see what the default configuration looks like before we make any modifications

[ ]

To see all of the different configuration options available, you can take a look at the file we downloaded. For this example, we're going to update a couple of settings to point to our newly-prepared datasets and to make sure the LoRA tuning runs on our A100. Feel free to experiment with these different options -- you can swap in your own datasets and change the training settings depending on what GPU you're using.

For data our data configuration, we'll point to the jsonl files we wrote out earlier. concat_sampling_probabilities determines what percentage of the finetuning data you would like to come from each file -- in our example we only have 1 training file so we choose [1.0]

[ ]

For our model settings, we don't have much to change since we're reading in a pretrained model and can inherit the values that were already set. We need to point to our existing .nemo file, specify that we want to use LoRA as our scheme for finetuning, and choose our parallelism and batch size values. The values below should be appropriate for a single A100 GPU.

Make sure to change the restore_from_path setting if you're using a different checkpoint!

[ ]

Finally, we set some options for the trainer. We'll be training on 1 GPU on a single node, at bfloat16 precision. For this example we'll also only train for 50 steps, with a validation check every after every 20 iterations.

[ ]

With our configurations set, we are ready to initialize our Trainer object to handle our training loop, and an experiment manager to handle checkpointing and logging.

[ ]

After initializing the Trainer object we can load our model from disk into memory. To load the model weights we'll need a config object for the model, which we can read from the .nemo file on disk and update it with any new settings we added in our LoRA config above.

[ ]

Now, let's see how to add the LoRA Adapter to our model and train it. We can specify that we want to use LoRA by using the LoraPEFTConfig class, which stores the types of applicable adapter and the hyperparameters required to initialize the adapter module.

[ ]

We can then call add_apater to actuall add the LoRA adapter to our base model and prepare it for training. When we first call add_adapter, the model prints out the parameter count before and after the operation and we can see the number of trainable parameters rise.

[ ]

Note: If you want to use a different PEFT method, you can use a different config class in place of LoraPEFTConfig, such as CanonicalAdaptersPEFTConfig, IA3PEFTConfig, or PtuningPEFTConfig. You can also use a combination of the methods by passing in a list: model.add_adapter([LoraPEFTConfig(model_cfg), PtuningPEFTConfig(model_cfg)])

We're now ready to start training! As the training loop runs, you'll see the validation loss drop significantly -- even with this short demonstration.

[ ]

Once training is completed you should see a saved '.nemo' file in the nemo_experiments/{taurus}_lora_pubmedqa folder. This checkpoint will only contain the trained adapter weights, and not the frozen base model weights.

We can also now see how the newly finetuned model performs on the test data:

[ ]

Much better! If you want to learn how to export our new model for optimized inference using TensorRT-LLM, continue on to the "Exporting to TensorRT-LLM" section.

Exporting to TensorRT-LLM

TensorRT-LLM is an open-source library for optimizing inference performance to acheive state-of-the-art speed on NVDIA GPUs. The NeMo framework offers an easy way to compile .nemo models into optimized TensorRT-LLM engines which you can run locally embedded in another application, or serve to other applications using a server like Triton Inference Server.

To start with, lets create a folder where our exported model will land

[ ]

To export the model to TensorRT-LLM, we'll need to merge the weights of the base model and the weights of the adapter. If you're using the NeMo Framework container, you'll find a script for this at /opt/NeMo/scripts/nlp_language_modeling/merge_lora_weights/merge.py. Otherwise, you can download the standalone script from GitHub at https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/nlp_language_modeling/merge_lora_weights/merge.py. To run the merge script, you'll need the path to the base model and trained adapter, as well as a path to save the merged model to.

[ ]

With our merged model weights, we just need to create an instance of the TensorRTLLM class and call the TensorRTLLM.export() function -- pointing the nemo_checkpoint_path argument to the newly merged model from above.

This creates a couple of files in the folder we created -- an engine file that holds the weights and the compiled execution graph of the model, a tokenizer.model file which holds the tokenizer information, and config.json which holds some metadata about the model (along with model.cache, which caches some operations and makes it faster to re-compile the model in the future.)

[ ]

With the model exported into TensorRTLLM, we can perform very fast inference:

[ ]

There's also a convenient function to deploy a the model as a service, backed by Triton Inference Server:

[ ]