AI Logic

Model Compression

LoRA

Updated:

How LoRA works. The left side shows the computation for one weight matrix: the input x passes through the frozen weight W₀ and through a branch of the trainable A (r × k) and B (d × r), and the branch is scaled by α / r and added. The upper right shows W₀ and the product B·A being added into a single matrix W before inference, and the lower right shows which Transformer weights it is applied to

Background and Overview

LoRA (Low-Rank Adaptation) is a fine-tuning method that freezes the pretrained weights and trains only the product of two small matrices (a low-rank matrix) added to each layer. It was proposed in 2021 by Hu, Shen, et al. at Microsoft.

When a large language model is fine-tuned for each use case, all of its weights are retrained, so there is a full copy of the model for every use case. For GPT-3 175B, a single copy is 350GB. Training also requires a large amount of GPU memory to hold the gradients and optimizer states (moving averages for Adam) for all weights.

LoRA assumes that "the change in weights during fine-tuning, ΔW\Delta W, can be represented with a low rank," and trains ΔW\Delta W by replacing it with the product BABA of two thin matrices. On GPT-3 175B, the paper showed the following effects.

  • About 10,000 times fewer trainable parameters: the saved checkpoint shrank from 350GB to about 35MB (with r=4r = 4, applied only to the query and value weights).
  • About one-third of the GPU memory during training: reduced from 1.2TB to 350GB.
  • No slowdown at inference: the trained BABA can be added to the original weights and merged into a single matrix, so inference costs the same as an ordinary model.
  • Accuracy equal to or better than training all weights: verified on RoBERTa, DeBERTa, GPT-2, and GPT-3.

Although "compression" is not in its name, it is widely used as a way to reduce the cost of training and storage, together with QLoRA, which combines it with quantization.

Theory (Low-Rank Updates)

The update ΔW\Delta W to a pretrained weight W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} is expressed as the product of two matrices (Section 4.1 of the paper).

W0+ΔW=W0+BA,B∈Rd×r, A∈Rr×k, r≪min⁡(d,k)W_0 + \Delta W = W_0 + BA, \qquad B \in \mathbb{R}^{d \times r},\ A \in \mathbb{R}^{r \times k},\ r \ll \min(d, k)

The output hh for an input xx is the sum of the result of the original weights and the result of the low-rank branch (Eq. (3) in the paper).

h=W0x+ΔWx=W0x+αrBAxh = W_0 x + \Delta W x = W_0 x + \frac{\alpha}{r} B A x

The procedure is as follows (left side of the figure at the top).

  1. Freeze the pretrained weights W0W_0 so that they are not updated by gradients.
  2. Add AA (r×kr \times k) and BB (d×rd \times r) alongside each weight matrix. AA is initialized with Gaussian random values and BB with zeros. At the start of training BA=0BA = 0, so the model output is the same as the original model.
  3. Multiply the output of the low-rank branch by α/r\alpha / r and add it to W0xW_0 x.
  4. Train only AA and BB on the downstream task data.
  5. Before inference, compute W=W0+αrBAW = W_0 + \frac{\alpha}{r} BA and store it as a single matrix.

The number of trainable parameters per weight matrix drops from dkdk to r(d+k)r(d + k). For example, with d=k=12,288d = k = 12{,}288 (the hidden width of GPT-3 175B) and r=4r = 4, it goes from about 150 million to about 98,000.

α\alpha is a constant with respect to rr; the paper simply sets α\alpha to the first value of rr it tried and does not tune it. This is because, when training with Adam, changing α\alpha is roughly the same as changing the learning rate. Scaling by α/r\alpha / r reduces the need to retune the learning rate and other hyperparameters when rr changes.

It can also be viewed as a generalization of training all weights. If LoRA is applied to every weight matrix and rr is increased up to the rank of the original weights, it has roughly the same expressiveness as training all weights.

Why a Low Rank Is Enough

LoRA was inspired by the observation of Li et al. (2018) and Aghajanyan et al. (2020) that "large pretrained models can in fact be trained within a low-dimensional subspace." The paper hypothesized that the change in weights needed for fine-tuning also has a low "intrinsic rank." As an analogy, when teaching a new job to an expert who already knows a lot, it is enough to convey a few key points rather than rewrite all of their knowledge.

Chapter 7 of the paper examines this hypothesis on GPT-3 175B.

  • Even rank 1 can be enough. When LoRA was applied to the query WqW_q and value WvW_v, r=1r = 1 gave almost the same accuracy as r=64r = 64 (Table 6).
  • Increasing the rank adds directions that are mostly unhelpful. Comparing the singular value decompositions of AA trained with r=8r = 8 and r=64r = 64, they overlapped only in about the top one direction. The paper considers the remaining directions to be close to noise picked up during training.
  • The update amplifies directions that are not prominent in the original weights. Rather than following the top singular directions of WW, ΔW\Delta W amplified directions that exist in WW but are not emphasized, by about 21.5 times (with r=4r = 4). This can be interpreted as drawing out features learned during pretraining but not prominent, to fit the task.

A low rank is enough when pretraining and the downstream task are similar. The paper also notes that when the task moves far from the original model, such as a task in a language different from pretraining, a small rr will likely not match training all weights.

Experimental Results

Table 4 of the paper shows the results of each method on GPT-3 175B (accuracy for WikiSQL and MNLI-m, ROUGE-1/2/L for SAMSum).

MethodTrainable parametersWikiSQLMNLI-mSAMSum
Full fine-tuning175,255.8M73.889.552.0 / 28.0 / 44.5
Bias only (BitFit)14.2M71.391.051.3 / 27.4 / 43.5
Prefix (layer-wise)20.2M70.189.550.8 / 27.3 / 43.5
Adapter7.1M71.989.853.0 / 28.9 / 44.8
LoRA4.7M73.491.753.8 / 29.8 / 45.9

On the average of the eight GLUE tasks in Table 2, LoRA also matched full fine-tuning with far fewer parameters.

ModelFull fine-tuningLoRA
RoBERTa base86.4 (125.0M)87.2 (0.3M)
RoBERTa large88.9 (355.0M)89.0 (0.8M)
DeBERTa XXL91.1 (1500.0M)91.3 (4.7M)

The numbers in parentheses are the numbers of trainable parameters.

  • Inference speed: In Table 1, running GPT-2 medium with batch size 1 and sequence length 128, one forward pass took 19.8 ms with LoRA (after merging the weights), while adding adapters made it 23.9–25.8 ms (a 20.7–30.3% increase).
  • Training speed: On GPT-3 175B, throughput per V100 was 43.1 tokens/s with LoRA versus 32.5 tokens/s with full fine-tuning, about 25% faster. This is because gradients for most of the weights need not be computed.
  • Which weights to apply it to: Comparing with the parameter count fixed at 18M (Table 5), applying rank 4 to both WqW_q and WvW_v was more accurate than applying rank 8 to WqW_q alone (WikiSQL 70.4 → 73.7). Applying it to more types of weights is more effective than raising the rank of one weight.

Practical Considerations

  • Decide which weights to apply it to. The paper's experiments used only WqW_q and WvW_v in self-attention and froze the MLP. The later QLoRA paper reports that without applying it to all linear layers, it did not match full fine-tuning. When in doubt, applying it to all linear layers is the safe choice.
  • Start with a small rr. In the paper, 1–8 was often enough, and raising rr did not improve accuracy. Fix α\alpha according to rr and tune with the learning rate.
  • Save only AA and BB for each use case. By keeping one copy of the original model, switching tasks only requires subtracting BABA and adding a different B′A′B'A'. By the paper's estimate, 100 tasks for GPT-3 can be stored in about 354GB instead of 35TB.
  • Activations take up more training memory than the LoRA parameters (according to the analysis in the QLoRA paper). For long sequences, combine it with gradient checkpointing and mixed-precision training.

Once BABA is merged into the original weights to speed up inference, different AA and BB can no longer be used for different tasks within a single batch. When requests for various tasks need to be processed in one batch, compute with the branch unmerged (in that case, it is slightly slower due to the branch computation).

Comparison with Other Methods

The following table compares methods that adapt a model to downstream tasks with few parameters from the same perspectives.

MethodWhat is trainedInference latencyUsable input lengthAccuracy trend (paper's comparison)
Full fine-tuningAll weightsNoneNot reducedBaseline
Bias only (BitFit)BiasesNoneNot reducedDrops on some tasks
AdapterSmall MLPs inserted between layersYes (deeper network)Not reducedClose to baseline
PrefixVectors prepended to the inputNo extra layers (longer input)ReducedDrops on some tasks
LoRALow-rank matrices alongside the weightsNone (after merging)Not reducedEqual to or better than baseline
QLoRALow-rank matrices (4-bit base)Dequantized to 16 bits at every computationNot reducedSame as 16-bit LoRA

Because adapters add layers, their latency is noticeable in online inference with small batch sizes. Prefix tuning uses part of the input for trainable vectors, which reduces the length available for task input, and increasing the number of vectors sometimes lowered accuracy (Figure 2 of the paper). LoRA avoids both of these drawbacks.

  • When GPU memory is sufficient and fast inference is important, choose LoRA.
  • When GPU memory is insufficient and you want to train a large model, choose QLoRA, which uses a 4-bit base.
  • For tasks very different from pretraining, with enough data and compute, also consider full fine-tuning.

To make the model itself smaller and lighten inference, use low-rank factorization, pruning, or knowledge distillation. Low-rank factorization replaces the trained weights themselves with a product of thin matrices, whereas LoRA represents only the change in weights with a low rank.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

# A single LoRA linear layer written exactly as Eq. (3) of the paper.
# PyTorch has no built-in LoRA, so write it yourself or use the peft library.

class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r=8, alpha=8):
        super().__init__()
        self.base = base                                   # pretrained weights W0 (d × k)
        for p in self.base.parameters():
            p.requires_grad = False                        # 1. freeze W0
        d, k = base.out_features, base.in_features
        # 2. initialize A with a Gaussian and B with zeros (BA = 0 at the start of training)
        #    the paper does not state the std, so 1/r is used here as an example
        self.A = nn.Parameter(torch.randn(r, k) / r)       # r × k
        self.B = nn.Parameter(torch.zeros(d, r))           # d × r
        self.scale = alpha / r                             # 3. scale by α / r
        self.merged = False

    def forward(self, x):
        h = self.base(x)                                   # W0 x
        if not self.merged:
            h = h + self.scale * (x @ self.A.T @ self.B.T)  # + (α/r)·B A x
        return h

    @torch.no_grad()
    def merge(self):
        """5. Merge into W = W0 + (α/r)·BA before inference. Inference cost becomes the same as the original layer"""
        if not self.merged:
            self.base.weight += self.scale * (self.B @ self.A)
            self.merged = True

    @torch.no_grad()
    def unmerge(self):
        """To switch to another task, first subtract BA to return to W0"""
        if self.merged:
            self.base.weight -= self.scale * (self.B @ self.A)
            self.merged = False

    def train(self, mode=True):
        # train with the branch under model.train(), merge the weights under model.eval()
        super().train(mode)
        self.unmerge() if mode else self.merge()
        return self


torch.manual_seed(0)
layer = LoRALinear(nn.Linear(512, 512), r=4, alpha=4)
print("Trainable parameters:", sum(p.numel() for p in layer.parameters() if p.requires_grad))  # 4 × (512 + 512) = 4096

layer.train()
opt = torch.optim.AdamW([p for p in layer.parameters() if p.requires_grad], lr=1e-3)
x = torch.randn(16, 512)
loss = layer(x).pow(2).mean()
loss.backward()                                            # gradients reach only A and B
opt.step()

layer.eval()                                               # merge the weights
with torch.no_grad():
    print(layer(x).shape)


# Using it with a real language model (peft library)
# from peft import LoraConfig, get_peft_model
# config = LoraConfig(r=8, lora_alpha=8, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM")
# model = get_peft_model(model, config)          # apply LoRA to Wq and Wv (the paper's main setting)
# model = model.merge_and_unload()               # after training, merge into W0 + BA and return to a regular model

FAQ

Q. What should the rank $r$ be?
A.

In the paper's GPT-3 175B experiments, r=1r = 1 was enough when applied to the query and value weights, and raising it to r=64r = 64 barely changed accuracy. A practical approach is to start at around 4–8 and increase it if that is not enough. However, the paper notes that for tasks very different from pretraining, a small rr may not be enough.

Q. Does LoRA slow down inference?
A.

Not if the weights are merged. Adding the trained BABA to the original weights to form W=W0+αrBAW = W_0 + \frac{\alpha}{r}BA makes the computation the same as an ordinary linear layer. Unlike adapters, LoRA does not add layers, which is its advantage. However, when different tasks' AA and BB need to be used within a single batch, the branch is computed without merging, which adds computation.

Q. What is the difference between LoRA and [QLoRA](/model-compression/qlora)?
A.

Both freeze the original weights and train only low-rank matrices. The difference is how the frozen weights are stored: LoRA keeps them in 16 bits, while QLoRA quantizes them to 4 bits (NF4). QLoRA needs much less memory, but training is not faster because the weights are dequantized to 16 bits at every computation.

References

  1. E. J. Hu, Y. Shen, P. Wallis, Z. Allen-Zhu, Y. Li, S. Wang, L. Wang, and W. Chen, "LoRA: Low-Rank Adaptation of Large Language Models," arXiv:2106.09685, 2021.
  2. T. Dettmers, A. Pagnoni, A. Holtzman, and L. Zettlemoyer, "QLoRA: Efficient Finetuning of Quantized LLMs," arXiv:2305.14314, 2023.
  3. microsoft/LoRA (implementation by the paper's authors)