Equations · Hu et al., “LoRA: Low-Rank Adaptation of Large Language Models” (2021)

The LoRA formula (W₀ + BA), explained

LoRA fine-tunes a large model by freezing its weights and learning a small low-rank correction to each chosen matrix.

h=W0x+ΔWx=W0x+αrBAx,B∈Rd×r, A∈Rr×k, r≪min⁡(d,k)h = W_0 x + \Delta W x = W_0 x + \frac{\alpha}{r} B A x, \quad B \in \mathbb{R}^{d \times r},\ A \in \mathbb{R}^{r \times k},\ r \ll \min(d, k)

Open in the decoder →

Term by term

  1. W0∈Rd×kW_0 \in \mathbb{R}^{d \times k}

    The pretrained weight matrix, frozen. The subscript 0 marks it as the original.

  2. ΔW=BA\Delta W = BA

    The learned update. As a product of a d×rd \times r and an r×kr \times k matrix, it has rank at most rr.

  3. B∈Rd×r, A∈Rr×kB \in \mathbb{R}^{d \times r},\ A \in \mathbb{R}^{r \times k}

    The two small trainable matrices. AA starts random and BB starts at zero, so training begins from the original model.

  4. r≪min⁡(d,k)r \ll \min(d, k)

    The rank is much smaller than the matrix's dimensions: often 4 to 64 against thousands.

  5. αr\frac{\alpha}{r}

    A constant scaling of the update, so changing rr does not require retuning the learning rate.

Shapes

A small worked example

For d=k=4096d = k = 4096 and r=8r = 8: full fine-tuning of the matrix trains 40962≈16.84096^2 \approx 16.8 million numbers; LoRA trains 2×4096×8=65,5362 \times 4096 \times 8 = 65{,}536, about 0.4%. After training, BABA can be added into W0W_0, so inference costs nothing extra.

In code

import numpy as np

def lora_forward(x, W0, A, B, alpha, r):
    return W0 @ x + (alpha / r) * (B @ (A @ x))

Every symbol in it

xi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)W∈Rd×kW \in \mathbb{R}^{d \times k}Real numbers (ℝ) and shapesW∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}Bold uppercase (matrix)ΔW\Delta WDelta (capital)Rn×d\mathbb{R}^{n \times d}Times (cross)x∈Rd\mathbf{x} \in \mathbb{R}^dElement oflog⁡p(x)≥LELBO\log p(x) \geq \mathcal{L}_{\text{ELBO}}Inequalitiesmax⁡(0,x)\max(0, x)Max and minα\alphaAlphaab\frac{a}{b}Fraction

Other equations