How does QLoRA fine-tune on one GPU?

Authors
How does QLoRA fine-tune on one GPU?

QLoRA fine-tunes a large language model on one GPU by shrinking the frozen model to 4-bit numbers and training only a few small extra pieces on top of it. This cuts the memory need so much that a model which once needed many GPUs now fits on a single one.

In this blog, we will learn about how QLoRA fine-tunes a large language model on one GPU. We will also see why full fine-tuning needs so much memory, how LoRA trains only small adapters, how quantization shrinks the model to 4-bit, the three tricks that QLoRA adds on top, a short code example, and where QLoRA works well and where it fails.

We will cover the following:

  • What is fine-tuning?
  • Why does full fine-tuning need so much memory?
  • What is LoRA?
  • What is quantization?
  • What is QLoRA?
  • Trick 1: 4-bit NormalFloat (NF4)
  • Trick 2: Double Quantization
  • Trick 3: Paged Optimizers
  • How one training step works in QLoRA
  • The memory math: why it fits on one GPU
  • A simple example of QLoRA in code
  • Full fine-tuning vs LoRA vs QLoRA
  • Where QLoRA works well and where it fails

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is fine-tuning?

Before jumping into QLoRA, we must know what fine-tuning is, because QLoRA is a way of doing fine-tuning.

Inside an LLM (Large Language Model), there are billions of numbers. These numbers are called weights or parameters. The weights decide how the model behaves. Training a model means updating these parameters until the model gives good answers.

A big company first trains the model on a huge amount of general text from the internet. This model knows a lot about the world, but it does not know our specific task.

Fine-tuning is the process of taking an already trained model and training it a little more on our own data, so that it becomes good at our specific task.

Let's say we have a student who has finished school. The student knows math, science, and languages. Now, we want this student to become a doctor. We do not send the student back to class one. We only teach medicine on top of what the student already knows. This is fine-tuning.

For example, we can fine-tune a general model on our company's customer support chats, so that it answers like our support team.

Why does full fine-tuning need so much memory?

The simple way to fine-tune is to update every single weight of the model. This is called full fine-tuning.

The problem is memory. A GPU has its own memory, and everything needed for training must fit inside it.

We have a detailed blog on how an LLM uses GPU memory that explains how a model fills up GPU memory step by step.

During full fine-tuning, the GPU must hold four things for every weight:

  • The weight itself. Usually stored in 16-bit format, which is 2 bytes per weight.
  • The gradient. The gradient tells us in which direction and by how much each weight must change. It is one more number per weight.
  • The optimizer states. The optimizer is the part that actually updates the weights. The popular optimizer called Adam keeps two extra numbers for each weight to remember the past updates. These are usually kept in 32-bit format.
  • The activations. These are the in-between results the model computes while reading our training text. They are needed later to compute the gradients.

Put together, full fine-tuning with Adam needs 2 bytes for the weight, 2 bytes for the gradient, and 8 bytes for the two optimizer numbers. That is 12 bytes or more for every weight, before we even count the activations. Many training setups also keep a 32-bit master copy of the weights, which adds 4 more bytes and makes it 16 bytes per weight.

Now, let's do the math for a 65 billion parameter model:

65,000,000,000 weights x 12 bytes = about 780 GB

Even with the lower 12-byte count, this matches the QLoRA paper, which says that regular 16-bit fine-tuning of a 65B model needs more than 780 GB of GPU memory. A single large GPU often has 48 GB to 80 GB of memory. So, we need many GPUs. That is very costly, and most people cannot do it.

We needed a solution for that, and LoRA was introduced to solve a big part of this problem.

What is LoRA?

LoRA stands for Low-Rank Adaptation. It freezes all the original weights and trains only a few small extra matrices that sit next to them.

A model is made of many layers. Each layer has a big table of numbers called a weight matrix. Let's say one weight matrix W has size 4096 x 4096. That is about 16.7 million numbers.

In full fine-tuning, we learn a change to W. Let's call this change delta_W (delta means change). It has the same size, 16.7 million numbers. LoRA says that this change does not need to be so big. It can be written as two thin matrices multiplied together:

delta_W  =  B  x  A

W  : 4096 x 4096   (frozen, not trained)
B  : 4096 x 16     (trained)
A  : 16   x 4096   (trained)

Here, the number 16 is called the rank. It is small by choice.

Let's count the numbers that we train:

B : 4096 x 16 = 65,536
A : 16 x 4096 = 65,536
Total         = 131,072

So, instead of training 16.7 million numbers, we train only about 131 thousand. That is less than 1 percent.

These small matrices A and B are called adapters. The output of the layer becomes:

output = W x input + B x A x input

The frozen big part does its old job, and the small adapter adds the new learning on top.

Let's go back to our student. The student's brain is the frozen model. The adapter is a small notebook of medical notes that the student carries. We only write in the notebook. The brain stays the same.

Now, the gradients and the optimizer states are needed only for the adapters, which are tiny. This saves a huge amount of memory.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

But, the frozen model must still sit in GPU memory. A 65B model in 16-bit takes:

65,000,000,000 x 2 bytes = 130 GB

130 GB still does not fit on one GPU. So, LoRA alone is not enough. We need to make the frozen model itself smaller. Here comes quantization into the picture.

What is quantization?

Quantization means storing each number with fewer bits, so that it takes less memory.

With more bits, we can store a number more precisely. With fewer bits, we save memory, but we lose some precision.

Suppose we have a ruler with marks at every millimeter. That is very precise. Now, suppose we use a ruler with marks only at every centimeter. It is less precise, but it is much simpler. Quantization is like moving to the ruler with fewer marks.

With 4 bits, we have only 16 possible values (because 2 x 2 x 2 x 2 = 16). So, every weight must be rounded to one of these 16 values.

Let's see the memory for our 65B model at different sizes:

16-bit : 65B x 2 bytes   = 130 GB
8-bit  : 65B x 1 byte    = 65 GB
4-bit  : 65B x 0.5 bytes = about 33 GB

At 4-bit, the model fits inside a 48 GB GPU, with space left for training.

But, the following question arises. If we round every weight to one of only 16 values, will the model not become much worse? And, can we even train through such a rough model? QLoRA answers both questions.

What is QLoRA?

QLoRA = Quantized + LoRA.

QLoRA keeps the frozen base model in 4-bit format and trains LoRA adapters in higher precision on top of it.

QLoRA was introduced in 2023 by Tim Dettmers and his co-authors in the paper "QLoRA: Efficient Finetuning of Quantized LLMs". In that paper, they fine-tuned a 65B model on a single 48 GB GPU, and the result kept the quality of full 16-bit fine-tuning on their tests. Their best model, called Guanaco, reached 99.3 percent of the performance of ChatGPT on a benchmark called Vicuna, after only 24 hours of fine-tuning on a single GPU.

The key idea is:

  • The big frozen model is stored in 4-bit. It is never trained, so it only needs to be read.
  • The small adapters are stored in 16-bit (a format called BFloat16). They are trained normally.
  • When a layer needs to do math, its 4-bit weights are turned back into 16-bit for that moment, the math is done, and the 16-bit copy is thrown away.

The gradients still flow through the frozen 4-bit model to reach the adapters, but the frozen weights themselves are never changed.

On top of this idea, QLoRA adds three tricks that make it work well. Let's learn each of them.

Trick 1: 4-bit NormalFloat (NF4)

The first question is: which 16 values must we pick for our 4-bit numbers?

The simple way is to spread the 16 values evenly, like the marks on a ruler. But the weights of a trained model are not spread evenly. Most of them are close to zero, and very few are large. If we draw them, they make a bell-shaped curve. This shape is called a normal distribution.

       Number of weights

              ***
            *******
          ***********
       *****************
  ---------------------------
  large    near zero    large
  negative           positive

If we spread our 16 values evenly, many of them get wasted on the rare large values, and too few are left for the crowded area near zero.

NF4 (4-bit NormalFloat) places the 16 values according to the bell curve, so that each value gets roughly the same number of weights. More values are packed near zero, where most weights live, and fewer values are kept at the edges.

Let's say we are opening shoe shops in a city. Most people live in the city center, and very few live at the edges. It makes sense to open more shops in the center. NF4 does the same with its 16 values.

There is one more step. Before rounding, the weights are split into small blocks of 64 weights. For each block, we find the largest absolute value and divide every weight in that block by it, so that all weights fall between -1 and 1. This dividing number is called the quantization constant, and we save it so that we can turn the weights back later.

            Block of 64 weights
                     ↓
Divide by the block's largest absolute value
                     ↓
 Round each to the nearest of 16 NF4 values
                     ↓
  Store 4-bit codes + 1 constant per block

Let's see a tiny example. Just for the sake of understanding, assume a block has only 4 weights, and assume our grid has only 5 values instead of 16:

Grid of allowed values : -1.0, -0.3, 0.0, 0.3, 1.0

Block weights          : 0.02, -0.05, 0.08, -0.16
Largest absolute value : 0.16   (this is the constant)
After dividing         : 0.125, -0.3125, 0.5, -1.0
Nearest grid value     : 0.0,   -0.3,    0.3, -1.0
Stored                 : 4 small codes + the constant 0.16

Here, we can notice that the grid has more values near zero than at the edges, just like NF4. Later, to get the weights back, we multiply each grid value by the constant 0.16, which gives 0.0, -0.048, 0.048, and -0.16. These are close to the original weights, but not exactly the same. This small loss is the price we pay for saving memory.

This way, NF4 keeps as much detail as possible with only 4 bits.

We have a detailed blog on how llama.cpp runs LLMs on everyday hardware that covers a similar block-wise 4-bit format used for running models.

Trick 2: Double Quantization

Now, the next big question is about those quantization constants.

Every block of 64 weights has one constant. That constant is stored in 32-bit format. So, for each weight, we spend extra memory on constants:

32 bits / 64 weights = 0.5 extra bits per weight

0.5 bits looks small, but for 65 billion weights it adds up to about 4 GB.

Double Quantization means quantizing the quantization constants too. QLoRA takes these 32-bit constants, groups them into blocks of 256, and stores them in 8-bit.

As per the paper, this brings the extra cost down from 0.5 bits to about 0.127 bits per weight. That saves about 0.37 bits per weight, which is about 3 GB for a 65B model.

To learn Quantization and Optimizations, Low-Rank Adaptation (LoRA), and QLoRA in depth, check out our AI and Machine Learning Program at Outcome School.

Trick 3: Paged Optimizers

Even with all this saving, the memory use during training is not constant. Sometimes a very long training example comes in, and the activations suddenly need a lot of memory for a moment. This short spike can cause an out-of-memory error, which means the GPU ran out of space and the training crashes.

Paged Optimizers move the optimizer states to normal computer memory (CPU RAM) when the GPU is about to run out, and bring them back when they are needed.

This uses a feature from NVIDIA called unified memory, which lets data move automatically between the GPU memory and the CPU memory, page by page.

Think of a small study desk. When the desk is full, we move some books to the shelf nearby. When we need them again, we bring them back. The work does not stop. The training becomes a little slower during the spike, but it does not crash.

Now, we have understood all three tricks. Let's see how they work together in one training step.

How one training step works in QLoRA

Let's walk through a single training step for one layer.

Step 1: The 4-bit NF4 weights of the layer are read from GPU memory, along with their quantization constants.

Step 2: The weights are turned back into 16-bit BFloat16 for this moment. This is called dequantization.

Step 3: The layer computes its output using the 16-bit weights, and adds the output of the LoRA adapter on top.

                      input
                        ↓
           +------------+------------+
           ↓                         ↓
[ W: 4-bit -> 16-bit ]      [ adapter: B x A ]
       (frozen)             (16-bit, trainable)
           ↓                         ↓
           +---------->(+)<----------+
                        ↓
                     output

Step 4: The temporary 16-bit copy of W is thrown away. Only the 4-bit version stays in memory.

Step 5: After all layers are done, we compare the model's answer with the correct answer and compute the error, which is called the loss.

Step 6: The gradients flow backward through every layer. They pass through the frozen weights (which are again dequantized for a moment) but are stored only for the adapter matrices A and B.

Step 7: The optimizer updates only A and B. If memory gets tight, the paged optimizer moves its states to CPU memory.

Then the next batch of training data comes in, and the same steps repeat.

This is how QLoRA trains on a model it never changes, and that too with only one GPU.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

The memory math: why it fits on one GPU

Let me put the numbers together for a 65B model, roughly, just for the sake of understanding:

Full 16-bit fine-tuning:
  weights + gradients + Adam states  ->  more than 780 GB  (many GPUs)

LoRA with 16-bit frozen model:
  frozen weights                      ->  130 GB           (still many GPUs)

QLoRA:
  frozen weights in NF4               ->  about 33 GB
  constants after Double Quantization ->  about 1 GB
  adapters + their gradients + Adam   ->  small
  activations                         ->  rest of the space
  Total                               ->  fits in one 48 GB GPU

The paper reports that QLoRA brought the memory need of fine-tuning a 65B model from more than 780 GB down to less than 48 GB.

For smaller models, the saving is even more useful. A 7B or 8B model can be fine-tuned with QLoRA on a single consumer GPU, the type that people use for gaming, which is why QLoRA became so popular.

If we want to go deep into Fine-tuning and Parameter-Efficient Fine-Tuning (PEFT), and build a Large Language Model (LLM) from scratch, we have a complete program on it - check out our AI and Machine Learning Program at Outcome School.

A simple example of QLoRA in code

Now, let's see the code for setting up QLoRA. We will use three Python libraries from Hugging Face that work together: transformers loads the model, peft adds the LoRA adapters, and bitsandbytes does the 4-bit quantization.

First, we load the model in 4-bit as below:

import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,                      # store base weights in 4-bit
    bnb_4bit_quant_type="nf4",              # use NormalFloat 4
    bnb_4bit_use_double_quant=True,         # quantize the constants too
    bnb_4bit_compute_dtype=torch.bfloat16,  # do the math in 16-bit
)

model = AutoModelForCausalLM.from_pretrained(
    "your-base-model-name",
    quantization_config=bnb_config,
    device_map="auto",
)

Here, we can see that each setting maps to an idea we learned:

  • load_in_4bit=True stores the frozen model in 4-bit.
  • bnb_4bit_quant_type="nf4" picks the NF4 format from Trick 1.
  • bnb_4bit_use_double_quant=True turns on Double Quantization from Trick 2.
  • bnb_4bit_compute_dtype=torch.bfloat16 tells it to dequantize to 16-bit for the math, like in Step 2.

Then, we add the LoRA adapters like below:

from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

model = prepare_model_for_kbit_training(model)

lora_config = LoraConfig(
    r=16,                      # the rank of the adapters
    lora_alpha=32,             # scaling for the adapter output
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    lora_dropout=0.05,
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, lora_config)
model.print_trainable_parameters()

Here, we have:

  • prepare_model_for_kbit_training gets the 4-bit model ready for training, for example by keeping some small parts in higher precision.
  • r=16 is the rank, the same 16 that we used in our LoRA math.
  • target_modules tells which weight matrices get adapters. Here, we are adding them to the attention layers.
  • print_trainable_parameters() prints how many weights are trainable. We will see that it is a very small percentage of the full model.

Finally, for Trick 3, we pick a paged optimizer in the training settings:

from transformers import TrainingArguments

args = TrainingArguments(
    output_dir="qlora-output",
    optim="paged_adamw_8bit",   # paged optimizer
    per_device_train_batch_size=4,
    learning_rate=2e-4,
)

Here, optim="paged_adamw_8bit" uses a paged version of the AdamW optimizer, so that memory spikes do not crash the training. After this, we pass the model, the data, and these arguments to a trainer, and the training runs on one GPU.

At the end, we save only the adapters. They are usually a few hundred megabytes or less, while the base model stays as it is.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

Full fine-tuning vs LoRA vs QLoRA

Let me tabulate the differences between full fine-tuning, LoRA, and QLoRA for your better understanding.

PointFull fine-tuningLoRAQLoRA
Which weights are trainedAll weightsOnly small adaptersOnly small adapters
Base model format16-bit16-bit, frozen4-bit NF4, frozen
GPU memory needVery highMediumLow
GPUs needed for a 65B modelManySeveralOne 48 GB GPU
Training speedNormalFastA bit slower, due to dequantizing
Output savedFull new modelSmall adapter fileSmall adapter file
QualityBest possibleClose to fullClose to full, as per the paper

Where QLoRA works well and where it fails

Where QLoRA works well:

  • When we have only one GPU, or a small budget.
  • When we want to teach a model a new style, format, or domain, like our support chats or our coding style.
  • When we want many different adapters for many tasks on the same base model. We keep one base model and swap small adapter files.

Where QLoRA has limits:

  • It is slower per step than LoRA on a 16-bit model, because the weights must be dequantized again and again.
  • Rounding to 4-bit loses a little detail. The paper showed that NF4 keeps quality very close, but it is not exactly the same as 16-bit.
  • Adapters with a small rank cannot add a huge amount of new knowledge. If we want to change the model deeply, full fine-tuning is still stronger.

Now we must have understood how QLoRA fine-tunes on one GPU.

Frequently Asked Questions

Does QLoRA reduce the quality of the model?

Only a little. Rounding the frozen weights to 4-bit loses a little detail, so the result is not exactly the same as 16-bit. But the QLoRA paper showed that NF4 keeps quality very close, and their fine-tuned 65B model kept the quality of full 16-bit fine-tuning on their tests.

Can we fine-tune a 7B model with QLoRA on a gaming GPU?

Yes. A 7B or 8B model can be fine-tuned with QLoRA on a single consumer GPU, the type that people use for gaming. The frozen model is stored in 4-bit, and only the small adapters are trained, so the memory need becomes small enough to fit on one such GPU.

Is QLoRA slower than LoRA?

Yes, a bit. QLoRA is slower per step than LoRA on a 16-bit model, because the 4-bit weights must be dequantized to 16-bit again and again for the math in every layer. In return, the frozen model takes far less GPU memory, which is what lets a large model fit on one GPU.

What do we save at the end of QLoRA fine-tuning?

We save only the small adapters. They are usually a few hundred megabytes or less, while the base model stays as it is. This also means we can keep one base model and swap small adapter files for many different tasks.

Which libraries do we use for QLoRA?

We use three Python libraries from Hugging Face that work together. The transformers library loads the model, peft adds the LoRA adapters, and bitsandbytes does the 4-bit quantization. A paged optimizer such as paged_adamw_8bit is picked in the training settings to handle memory spikes.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.