← All notes

Efficient LLMs

Contents

LoRA (Low-Rank Adaptation)

In simple words, this is the method where a large language model learns a new task by training a small update instead of rewriting all its weights. [1]

The difficulty of fine-tuning an entire model is scale. Full fine-tuning stores the combined result as another complete set of weights. Updating every parameter of a large model requires substantial training memory, and each finished task produces another full-sized set of weights to store and deploy.

LoRA was developed to make this adaptation smaller: preserve the pretrained model, then learn only the compact changes required by the new task. It keeps the original matrix fixed and learns only the change using a much smaller representation.

LoRA diagram showing an input x passing through a frozen pretrained weight matrix and a parallel path through trainable matrices A and B, whose outputs are added.
A low-rank update runs alongside the frozen weight matrix. Only A and B are trained. Source: Hu et al., Figure 1.

It fine-tunes an LLM without changing its original weights. For each chosen weight matrix, it learns a small update written as the product of two thin matrices, BB and AA, with a low rank rr. Only those two matrices are trained for each task. So whenever something new needs to be learned, it comes as a small adapter instead of requiring a full copy of the model to be trained.

Full fine-tuning allows updates to flow into every model weight. This gives training broad freedom, but it also requires gradients and optimizer state for the full model and produces another full-sized set of weights for the task.

LoRA changes only the destination of the update. The same examples, loss, and backpropagation are used, but the pretrained weights are marked as frozen. Gradients update the small LoRA parameters instead, so the task is stored as an adapter rather than another copy of the model.

Transformer Layers LoRA Can Change

A transformer carries each token as a list of learned features called a hidden state. Linear layers appear throughout every transformer block, especially inside attention and the feed-forward network. They transform those features using weight matrices.

A typical Llama-style Transformer block contains two main components: self-attention and a feed-forward network (FFN). Self-attention uses q_proj, k_proj, v_proj, and o_proj. The FFN uses gate_proj, up_proj, and down_proj.

Seven projections in a Llama-style block Input hidden states pass through self-attention and the FFN. Attention has query, key, value, and output projections; the FFN has gate, up, and down projections. Input hidden states Self-attention q_proj k_proj v_proj o_proj Feed-forward network (FFN) gate_proj up_proj down_proj Output hidden states
The seven projections in a Llama-style Transformer block. This schematic omits normalization and residual connections.

Each of these seven projections has a weight matrix that LoRA can adapt.

In Attention Projections

MatrixPurpose
q_proj (Query)What information am I looking for?
k_proj (Key)What information can other tokens be matched by?
v_proj (Value)What information do other tokens provide?
o_proj (Output)How do I combine and return the retrieved information?
Attention projections and information flow Queries and keys determine attention weights through scaled dot products and softmax. These weights combine values before the output projection. Query Q Key K Value V Attention weights softmax(QKᵀ / √d) Weighted values Output projection o_proj
Queries and keys determine attention weights; those weights combine the values before the output projection. Causal masking is omitted from the schematic.

Applying LoRA to q_proj changes how the model searches for relevant information. Applying LoRA to v_proj changes the information carried between tokens. This is why query and value projections are common starting points for LoRA. [1]

In FFN Projections

Attention enables tokens to communicate with each other. The FFN processes and transforms each token’s representation independently.

In a Llama-style gated FFN:

A Llama-style gated feed-forward network A hidden state of width 4096 feeds gate and up projections of width 11008. SiLU is applied to the gate output, the branches multiply elementwise, and the down projection returns to width 4096. Hidden state 4096 Gate projection 11008 · SiLU Up projection 11008 × Down projection 4096
A Llama 2 7B-style gated FFN, with example dimensions 4096 → 11008 → 4096.

By applying LoRA to these matrices, you also allow the model to adjust how it transforms its internal features.

LoRA can be attached to selected projections in attention, the feed-forward network, or both. It adds a parallel weight update to those linear layers. The surrounding attention calculation, activation functions, normalization, and residual path remain unchanged.

Suppose you configure LoRA like this:

target_modules=["q_proj", "v_proj"]

Inside every Transformer block, LoRA adds trainable matrices A and B to the query and value projections.

Transformer layer with query, key, and value projections, and a zoomed-in LoRA update path showing the trainable low-rank matrices in magenta alongside a frozen weight matrix.
LoRA applied to attention projections, illustrated by the Q, K, and V matrices. The trainable low-rank matrices are shown in magenta. Source: Clifton Poth, AdapterHub, Figure 2.
Transformer block showing multi-head attention, residual connections, normalization, and a feed-forward network with a LoRA adapter. The adapter combines pretrained weights W with a low-rank path through W A and W B.
LoRA applied to a feed-forward projection, illustrating another possible location for the same low-rank update. Here WA and WB correspond to A and B above. Source: Ammar et al., Figure 2 (CC BY 4.0).

How LoRA Computes an Update

LoRA doesn’t replace what the pretrained model already knows. It learns a small correction to the model’s existing behaviour.

Imagine a pretrained model has a weight matrix WW. When a linear layer receives a hidden state xx, a vector containing information about the input, it computes:

y=Wxy = Wx

Instead of changing WW, LoRA keeps it frozen and trains two smaller matrices, AA and BB.

LoRA adds a learned correction to the original result The same hidden state x goes through the frozen pretrained matrix W and the trainable LoRA update BA in parallel. Their outputs Wx and BAx are added to produce y. Hidden statex Pretrained WFrozen LoRA: BATrainable +y Original result Learned correction WxBAx
The same input goes through two paths, and their results are added together. Only the LoRA matrices A and B are trained.

The first reduces the hidden state to a narrow intermediate width rr. The second restores the original output width.

A reduces the width; B restores the output width The input hidden state x has width d in. The trainable matrix A maps it to Ax of width r. The trainable matrix B maps Ax to the correction BAx of width d out. x A Ax B BAx din Reduce r Expand dout
The LoRA path narrows from the input width to r through A, then expands to the output width through B. Both matrices are trainable.

The new calculation becomes:

y=Wx+BAx\boxed{y = Wx + BAx}
  1. WxWx: what the pretrained model would normally output.
  2. BAxBAx: the correction learned by LoRA.
  3. yy: the final, adapted output.

A LoRA adapter is therefore not a second language model. It is the collection of these small update matrices across the selected layers. Several adapters can share the same frozen base model because each stores only its own corrections.

In the original LoRA formulation, AA is initialized with small random values and BB is initialized to zero. The initial adapter update is therefore zero. [1]

B=0  ⟹  BA=0B = 0 \implies BA = 0

On the first backward pass, BB can receive a gradient because AxAx is generally nonzero. The gradient for AA initially passes through zero-valued BB, so AA starts changing after BB moves away from zero.

Matrix Rank and LoRA

A matrix is a rectangular table of numbers. Its shape tells us how many input features it receives and how many output features it produces. A weight matrix with shape dout×dind_{\text{out}} \times d_{\text{in}} maps a hidden state with dind_{\text{in}} features to one with doutd_{\text{out}} features.1

The rank of a matrix describes how many independent directions its transformation can express. A full-rank matrix can use every available direction. A low-rank matrix is more restricted because some rows or columns can be produced from combinations of others.

Three 2-by-2 matrices transform a square into a parallelogram for rank 2, a line for rank 1, and a point for rank 0. The matrices are [3, 1; 1, 2], [1, 1; 2, 2], and the zero matrix.
  1. Rank 2 (full rank): A 2D square becomes a parallelogram, preserving two independent directions.
  2. Rank 1 (low rank): The square collapses onto a line, leaving just one independent direction.
  3. Rank 0: Everything collapses into a single point, leaving zero independent directions.2

Source: My Datascience Journey, Determinants.

The product BABA below has the same outer shape as the pretrained weight matrix WW, so it can be added to that weight. Its rank cannot exceed the inner dimension rr. This is the bottleneck: the update BABA has at most rr independent output directions.

Multiplication by BB can expand the number of coordinates, but it cannot recreate independent directions lost when passing through the narrow rr-dimensional bottleneck. This is the mathematical reason two smaller matrices form a low-rank update.

LoRA stores a full-shaped update as two smaller matrices A standard linear projection maps x of width d in through W of shape d out by d in to y of width d out. LoRA represents its update as B of shape d out by r times A of shape r by d in. Their product BA has the same shape as W, but rank at most r. A standard linear projection x W y → → din dout × din dout LoRA stores the update as two factors B A ΔW = BA × = rank ≤ r dout × r r × din dout × din
B and A share the inner dimension r. Their product has the same outer shape as W, with rank at most r. The cells illustrate shapes rather than specific parameter values.

Consider a linear layer with 4,096 input features and 4,096 output features. A freely trainable update would contain 4,096×4,096=16,777,2164{,}096 \times 4{,}096 = 16{,}777{,}216 parameters. LoRA sends the update through a much narrower space instead.

With r=8r = 8, the two adapter matrices contain only 65,536 parameters for this layer:

UpdateTrainable parameters
Full update matrix4,096×4,096=16,777,2164{,}096 \times 4{,}096 = 16{,}777{,}216
LoRA matrices AA and BB(8×4,096)+(4,096×8)=65,536(8 \times 4{,}096) + (4{,}096 \times 8) = 65{,}536

That is 65,536/16,777,216×100=0.390625%65{,}536 / 16{,}777{,}216 \times 100 = 0.390625\%, or about 0.39% as many trainable parameters as a full update matrix. The frozen base weights are still present; these counts compare the parameters trained for this layer.

Full update matrix compared with LoRA's factors At rank 8, a 4096 by 4096 full update has 16777216 parameters. LoRA uses A of shape 8 by 4096 and B of shape 4096 by 8, with 65536 parameters in total. Full updateAB versus+ 4,096 × 4,096 8 × 4,096 4,096 × 8 Schematic shapes, not drawn to scale.
Full update parameters
16,777,216
LoRA parameters (A + B)
65,536

At rank 8, LoRA trains 0.391% as many parameters as the full update, or 256× fewer.

Full update: dout × din. LoRA: r × (din + dout).

Choose a projection and change the rank to compare a full update with LoRA's two matrices. These are illustrative layer sizes. Each calculation covers one weight matrix, not an entire Transformer block or model.

Visualization inspired by TensorTonic’s LoRA rank comparison.

Footnotes

  1. A weight matrix transforms a list of numbers from one size into a list of numbers of another size. Suppose din=3d_{\text{in}} = 3 and dout=2d_{\text{out}} = 2. The input has three features, and the output has two. The weight matrix has two rows and three columns:

    W=[123456],x=[102030].W = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}, \qquad x = \begin{bmatrix} 10 \\ 20 \\ 30 \end{bmatrix}.

    Each row of WW produces one output feature:

    Output featureCalculationResult
    First1(10)+2(20)+3(30)1(10) + 2(20) + 3(30)140140
    Second4(10)+5(20)+6(30)4(10) + 5(20) + 6(30)320320

    So the product is:

    Wx=[140320].Wx = \begin{bmatrix} 140 \\ 320 \end{bmatrix}.

    Three input numbers become two output numbers. ↩

  2. The numbers in the blue 2×22 \times 2 grids at the top are the entries of the matrices that control how the shapes below are transformed.

    Each matrix takes a point (x,y)(x,y) and produces a new point (x′,y′)(x',y').

    1. Rank 2: Full rank

    A=[3112]A = \begin{bmatrix} 3 & 1 \\ 1 & 2 \end{bmatrix}

    The numbers tell us:

    x′=3x+yx' = 3x + y y′=x+2yy' = x + 2y

    The two columns, (3,1)(3,1) and (1,2)(1,2), represent two independent directions. That’s why the square becomes a parallelogram rather than collapsing.

    2. Rank 1: Low rank

    A=[1122]A = \begin{bmatrix} 1 & 1 \\ 2 & 2 \end{bmatrix}

    Notice that both columns are identical!

    x′=x+y,y′=2x+2yx' = x + y, \qquad y' = 2x + 2y

    Because y′=2x′y' = 2x', every output point lies on the same line.

    That’s why the square collapses into a line.

    3. Rank 0: Zero rank

    A=[0000]A = \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix}

    Every input becomes:

    (x′,y′)=(0,0)(x',y') = (0,0)

    The entire square collapses into a single point.

    The key idea: The numbers determine how the transformation moves points. The rank tells us how many independent output directions remain. ↩

Bibliography

  1. Edward J. Hu et al., “LoRA: Low-Rank Adaptation of Large Language Models,” arXiv preprint, 2021.