AI Wiki中文/EN

LoRA: a small trainable change to a frozen matrix

LoRA

Derive factor gradients, test zero initialization and compare learned updates with an exact SVD bound.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A full-rank model can need only a low-rank change

Suppose a frozen four-by-four matrix needs an update with singular values 2, 1, 0.5 and 0. A rank-one update cannot express all three nonzero directions. A rank-two update can capture more, but still misses the final direction. A rank-three update can represent the entire change even if the original matrix itself has full rank.

LoRA, low-rank adaptation, restricts the trainable change rather than replacing the pretrained matrix with a low-rank approximation. Hu and colleagues introduce this parameterization and show how a fixed trained update can be merged for inference. Houlsby and colleagues provide an earlier parameter-efficient alternative: insert small nonlinear adapter modules into the network. The distinction matters because low parameter count alone does not imply weight merging.

Actual factor training reaches the declared SVD bounds; zeroing both factors prevents learning.
Actual factor training reaches the declared SVD bounds; zeroing both factors prevents learning.

Train two factors, keep the base

Use column-vector convention. Let W0∈Rd×kW_0\in\mathbb R^{d\times k} be frozen, A∈Rr×kA\in\mathbb R^{r\times k} and B∈Rd×rB\in\mathbb R^{d\times r} be trainable, and s=α/rs=\alpha/r be a fixed scale. The adapted map is:

h=W0x+sBAx,ΔW=sBA,rank⁡(ΔW)≤r.h=W_0x+sBAx,\qquad \Delta W=sBA,\qquad \operatorname{rank}(\Delta W)\le r.

The bound concerns the update. It does not require W0W_0 or W0+ΔWW_0+\Delta W to have low rank. The choice of which layers receive updates also matters: adapting only query and value projections is a different model class from adapting every linear map.

The number of factor parameters and its ratio to a dense weight matrix are:

PLoRA=r(k+d),ρ=r(k+d)dk.P_{\mathrm{LoRA}}=r(k+d),\qquad \rho=\frac{r(k+d)}{dk}.

For a 4,096-square matrix and rank eight, there are 65,536 factor parameters versus 16,777,216 dense weights, a ratio of 1/2561/256. But our four-square teaching example at rank two has 16 factor parameters, exactly as many as the dense matrix. A small example need not itself demonstrate memory savings.

Let G=∂L/∂WG=\partial\mathcal L/\partial W be the gradient that the effective dense matrix would receive. Differentiating the product gives:

∂L∂A=sB⊤G,∂L∂B=sGA⊤.\frac{\partial\mathcal L}{\partial A}=sB^\top G,\qquad \frac{\partial\mathcal L}{\partial B}=sGA^\top.

Hu and colleagues initialize AA randomly and BB at zero. The initial update is zero, but BB can receive a nonzero gradient. The first gradient for AA is zero; it can become nonzero after BB changes. If both factors start at zero, both gradients vanish, so ordinary gradient descent stays there. This is a property of this factorization, not a general objection to every zero initialization.

For a fixed adapter in deterministic inference without an active dropout branch, define:

Wmerged=W0+sBA.W_{\mathrm{merged}}=W_0+sBA.

Then the separate and merged maps agree in exact arithmetic. Floating-point order can cause small differences. Quantizing the merged matrix introduces another error source. Keeping different adapters for different requests also requires deciding whether to store separate merged copies or execute the added branches dynamically.

Our regression experiment has row-oriented data X∈RN×kX\in\mathbb R^{N\times k}, targets Y∈RN×dY\in\mathbb R^{N\times d} and s=1s=1. Its objective is:

L(A,B)=12N∥X(W0+BA)⊤−Y∥F2.\mathcal L(A,B)=\frac1{2N}\left\|X(W_0+BA)^\top-Y\right\|_F^2.

Writing E=X(W0+BA)⊤−YE=X(W_0+BA)^\top-Y gives the effective weight gradient:

G=E⊤XN.G=\frac{E^\top X}{N}.

Here X=I4X=I_4 and Y=X(W0+D)⊤Y=X(W_0+D)^\top for D=diag⁡(2,1,0.5,0)D=\operatorname{diag}(2,1,0.5,0). The identity design makes output loss exactly a scaled matrix-approximation error. The best rank-rr loss follows from the truncated SVD:

min⁡rank⁡(BA)≤rL=12N∑j>rσj(D)2.\min_{\operatorname{rank}(BA)\le r}\mathcal L=\frac1{2N}\sum_{j>r}\sigma_j(D)^2.

The resulting losses are 0.15625, 0.03125 and zero for ranks one, two and three. This oracle relies on the declared identity design and squared loss. General language-model fine-tuning does not reduce to this SVD formula, and factor gradient descent is not automatically guaranteed to reach every nonconvex optimum.

Compare learned factors with a known optimum

The complete NumPy program freezes a seeded base matrix, initializes one factor randomly and the other at zero, and trains both factors using the derived gradients. It also runs the deliberately stuck all-zero initialization.

"""Actual low-rank factor training against a matrix with a known SVD oracle."""
import json
import numpy as np

def initialize(rank,zero_both=False):
    if type(rank) is not int or not 1<=rank<=4:raise ValueError('Rank1 through4 required')
    rng=np.random.default_rng(13)
    return (np.zeros((rank,4)) if zero_both else rng.normal(0,.1,(rank,4))),np.zeros((4,rank))
def fixture():
    w0=np.random.default_rng(7).normal(size=(4,4));delta=np.diag([2.,1.,.5,0.])
    return w0,delta,np.eye(4)
def objective(a,b,w0,x,y,scale=1.):
    if not np.isfinite(scale) or scale<=0:raise ValueError('Positive finite scale required')
    err=x@(w0+scale*b@a).T-y;g=err.T@x/len(x)
    return float(np.sum(err**2)/(2*len(x))),scale*b.T@g,scale*g@a.T

def train(rank,steps=2000,zero_both=False):
    if type(steps) is not int or not 0<=steps<=10000:raise ValueError('Bounded integer steps required')
    w0,delta,x=fixture();y=x@(w0+delta).T;a,b=initialize(rank,zero_both);history=[]
    for i in range(steps+1):
        loss,ga,gb=objective(a,b,w0,x,y)
        if i%250==0 or i==steps:history.append(dict(step=i,loss=loss))
        if i<steps:a-=.25*ga;b-=.25*gb
    return dict(a=a,b=b,w0=w0,delta=delta,x=x,trace=history)
def demo():
    runs=[]
    for rank in [1,2,3]:
        r=train(rank);a,b,w0,x=r['a'],r['b'],r['w0'],r['x'];singular=np.linalg.svd(r['delta'],compute_uv=False)
        separate=x@w0.T+(x@a.T)@b.T;merged=x@(w0+b@a).T
        runs.append(dict(rank=rank,trainable=a.size+b.size,full_weight_parameters=w0.size,final_loss=r['trace'][-1]['loss'],oracle_loss=float(np.sum(singular[rank:]**2)/8),merge_error=float(np.max(abs(separate-merged))),update_rank=int(np.linalg.matrix_rank(b@a,tol=1e-8)),trace=r['trace']))
    dead=train(2,steps=10,zero_both=True)
    return dict(runs=runs,zero_both_loss=dead['trace'][-1]['loss'],scope='Alpha/r=1, identity design, float64, no dropout; tiny rank2 factors already equal full weight count')
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

After 2,000 updates, ranks one and two reach the oracle losses 0.15625 and 0.03125. Rank three reaches numerical zero, about 1.75×10−311.75\times10^{-31}. Initializing both factors to zero instead leaves the loss at 5.25/8=0.656255.25/8=0.65625. These results are for the authored regression, not an estimate of a language model’s required rank.

Tests check both factor gradients using finite differences at scale 0.7, verify base weights remain unchanged, and compare merged and separate outputs on additional random inputs. They independently compare learned losses with the SVD tail bound and inspect the update rank.

For one input, the extra factor branch requires work proportional to r(k+d)r(k+d) and stores that many trainable scalars; the original dense multiplication still costs O(dk)O(dk). Forming a merged update costs O(dkr)O(dkr) once for that adapter, after which the dense inference shape is unchanged. Optimizer-state savings concern trainable parameters, while activations and differentiation through the frozen network can remain substantial.

Low rank is a modeling constraint, not a quality guarantee

The useful rank depends on the target task, chosen layers, base model and training setup. A low-rank parameterization can underfit a necessary change. Increasing rank adds capacity but does not guarantee better held-out performance. Parameter count, checkpoint size, training memory and measured latency are different quantities.

LoRA’s mergeability concerns an additive linear branch at a specified weight. A bottleneck adapter with a nonlinear activation generally cannot be absorbed into one fixed affine matrix. Conversely, leaving LoRA branches unmerged adds computation. The original paper’s merged inference argument should not become an unconditional “zero latency” claim for every serving setup.

Finite-precision merge–subtract cycles can accumulate rounding error; preserve the original base rather than relying on repeated subtraction as exact recovery. Dropout, biases, scale conventions and target-module selection must match between training, serialization and inference. QLoRA adds quantized base storage, with its own arithmetic and merging qualifications.

Follow the rank and the gradients

  1. Does rank-eight LoRA require the base matrix to have rank eight? Answer: No. The bound applies to the added product BABA, not to the frozen base or necessarily the resulting sum.
  2. For a 4,096-square matrix and rank eight, how many factor parameters are trained? Answer: 8(4096+4096)=65,5368(4096+4096)=65,536, or 1/2561/256 of the dense matrix’s 16,777,216 weights, excluding any separately trained biases or other modules.
  3. Why can random AA and zero BB learn when two zero factors cannot? Answer: Initially ∂L/∂B=sGA⊤\partial\mathcal L/\partial B=sGA^\top can be nonzero. Two zero factors make both product gradients zero under the stated update rule.
  4. What is the rank-two oracle loss for this experiment, and can it be reused as a language-model bound? Answer: The omitted squared singular value is 0.520.5^2, divided by 2N=82N=8, giving 0.03125. The identity-design regression assumptions do not hold for a general language-model loss.

Compare the location of adaptation as well as its size

Hu and colleagues study low-rank weight increments; Houlsby and colleagues study inserted bottleneck modules, including normalization and task-specific components in their configuration. They are different adaptation families, even when a parameter budget happens to match.

A careful comparison fixes the base model, data, evaluation and training budget, then reports the updated modules and inference configuration. The small SVD experiment isolates a capacity limit and an initialization failure; empirical task results require a separate experiment.

Make a prediction, then check

If both LoRA factors begin at zero, what happens under ordinary gradient descent?

Choose one answer

Learning objectives

  • Distinguish rank of the update from rank of the base matrix.
  • Derive gradients and explain asymmetric initialization.
  • State the conditions for merging and for parameter savings.

Prerequisites & connections

Explore related knowledge →

References

  1. LoRA: Low-Rank Adaptation of Large Language Models — v2
    Edward J. Hu; Yelong Shen; Phillip Wallis; Zeyuan Allen-Zhu; Yuanzhi Li; Shean Wang; Lu Wang; Weizhu Chen · 2021
  2. Parameter-Efficient Transfer Learning for NLP
    Neil Houlsby; Andrei Giurgiu; Stanislaw Jastrzebski; Bruna Morrone; Quentin De Laroussilhe; Andrea Gesmundo; Mona Attariyan; Sylvain Gelly · 2019

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read LoRA v2 PDF4/5 sections4.1/4.2 and Houlsby ICML2019 PDF2/3. Seven paired equations and four explained exercises. Actual factor optimization, all gradients including scale.7, frozen base, merge equality on new inputs, zero-factor failure and known SVD tail losses. Identity-design squared-loss oracle only; no unconditional latency or rank guarantee.

  • Single AI author read LoRA v2 PDF4/5 sections4.1/4.2 and Houlsby ICML2019 PDF2/3. Seven paired equations and four explained exercises. Actual factor optimization, all gradients including scale.7, frozen base, merge equality on new inputs, zero-factor failure and known SVD tail losses. Identity-design squared-loss oracle only; no unconditional latency or rank guarantee.
  • Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures checked:seven final directly viewed,five byte-identical to previously viewed images. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.