Grimoire
Sheet
pathfine-tuning/peft
difficultyintermediate
timeO(r·d)
memoryO(r·d)
described2021
revised1w ago

LoRA

Freeze W and learn a rank-r correction BA alongside it. The update has 2rd parameters instead of d², and folds back into W at inference for free.

Theory

The hypothesis is that the weight change induced by adaptation has low intrinsic rank even when the weight itself does not. Parameterise that change as a product of two thin matrices and train only those.

h=W0x+ΔWx=W0x+αrBAx,BRd×r,    ARr×kh = W_0 x + \Delta W x = W_0 x + \frac{\alpha}{r} B A x, \qquad B \in \R^{d \times r},\;\; A \in \R^{r \times k}
eq. 1Hu et al. §4.1

AA is initialised Gaussian and BB at zero, so ΔW\Delta W starts at exactly zero and the adapted model begins as the base model. The α/r\alpha/r factor keeps the update scale roughly constant as rr is varied, which is what makes the learning rate transferable across ranks.

The α/r\alpha/r scaling is why rank and learning rate interact less than you would expect — but it also means α\alpha is not a free parameter once you have tuned the learning rate. Fixing α=2r\alpha = 2r is the usual convention; rsLoRA uses α/r\alpha/\sqrt{r} instead.

Implementation
python · torch ≥ 2.1
import math
import torch
from torch import Tensor, nn


class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int = 16, alpha: int = 32):
        super().__init__()
        self.base = base
        self.base.requires_grad_(False)
        self.A = nn.Parameter(torch.empty(r, base.in_features))
        self.B = nn.Parameter(torch.zeros(base.out_features, r))
        nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
        self.scale = alpha / r

    def forward(self, x: Tensor) -> Tensor:
        return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale

    @torch.no_grad()
    def merge_(self) -> nn.Linear:
        self.base.weight += (self.B @ self.A) * self.scale
        return self.base

Note the association order in the forward: x @ A.T @ B.T costs O(r(d+k))O(r(d+k)) per token, whereas forming B @ A first costs O(dkr)O(dkr) and throws away the entire point.

Trainable params
0.24%
Optimiser state
−99.7%
Inference cost
+0%
7B model, r = 16, adapters on q/k/v/o projections, merged
Related
References
[1]Hu et al. — LoRA: Low-Rank Adaptation of Large Language Models (2021)arXiv:2106.09685
[2]Aghajanyan et al. — Intrinsic Dimensionality Explains the Effectiveness of Fine-Tuning (2020)arXiv:2012.13255
[3]Kalajdzievski — A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA (2023)arXiv:2312.03732