Suppose a pretrained language model already understands invoices, but you want it to return invoice fields in a specific JSON format. Fine-tuning can teach it that format. Full fine-tuning makes every model weight eligible to change. For a model with billions of weights, training may need memory for the weights, their gradients, and extra numbers tracked by the optimizer. Saving a separate version for every task also takes space.
Does adapting a pretrained model require changing every weight independently? Low-Rank Adaptation, or LoRA, answers by freezing the pretrained weights and learning a smaller set of parameters. This is a form of parameter-efficient fine-tuning (PEFT). The learned change can still touch every entry in a weight matrix. What changes is how many independent directions those entries can describe. Matrix rank lets us count those directions.
What matrix rank measures
A column tells you where a matrix sends one input direction. Every possible output is a mix of those columns. If one column can be built from the others, it adds no new direction. Rank counts how many independent columns there are. Counting independent rows gives the same number. Two directions are independent if neither is a multiple of the other.
In F below, the first column points right and the second points up, so the outputs still cover a plane. In R, both columns point in the same direction. Inputs [1, 0] and [0, 1] both become [1, 2]. That transformation cannot tell the two inputs apart. F has rank 2 and is full-rank. R has rank 1 and is rank-deficient, meaning its rank falls below the smaller of its row and column counts.
import numpy as np
F = np.array([[2, 0], [0, 1]])
R = np.array([[1, 1], [2, 2]])
print(np.linalg.matrix_rank(F), np.linalg.matrix_rank(R))
print(R @ [1, 0], R @ [0, 1])2 1 [1 2] [1 2]
See the foundations in How Linear Algebra Powers Neural Networks
Two small matrices can make a large one
Let M have m rows and n columns. If its rank is at most r, we can write M as the product BA, with B having shape m × r and A having shape r × n. Think of B as a collection of up to r directions. Each column of A tells us how to combine those directions to make the matching column of M. That construction also explains the rank limit. No column of BA can point outside the space covered by the columns of B.
M = BA (m × r)(r × n) → m × n rank(BA) ≤ r
Try a 4 × 2 matrix B and a 2 × 4 matrix A. The first two columns of A select one direction each. The third adds the directions, and the fourth subtracts the second from the first. This fills the 4 × 4 result with numbers, but its columns still come from the same two independent directions.
import numpy as np
B = np.array([[1, 0], [0, 1], [1, 1], [2, 1]])
A = np.array([[1, 0, 1, 1], [0, 1, 1, -1]])
M = B @ A
print(M)
print(M.shape, np.linalg.matrix_rank(M))[[ 1 0 1 1] [ 0 1 1 -1] [ 1 1 2 0] [ 2 1 3 1]] (4, 4) 2
This factorization is exact because M already has rank 2. If M had rank 4 and we insisted on r = 2, BA could only approximate it. Truncated singular value decomposition (SVD) is one way to approximate an existing matrix by keeping its strongest directions. LoRA learns its two factors directly from a task’s training data.
What LoRA trains
Take one pretrained layer with a weight matrix W₀. Its shape is d_out × d_in, where d_in is the number of input features and d_out is the number of outputs. In full fine-tuning, every entry can change. We can describe the result as W₀ + ΔW, where ΔW is the difference between the final and original weights.
With LoRA, W₀ stays frozen. A maps the input into r intermediate numbers, and B maps those numbers back to d_out outputs. The scale α/r controls the strength of this extra contribution, where α is a setting chosen when configuring training. For these equations ΔW means the unscaled product BA, so the change actually added to W₀ is (α/r)ΔW. We leave out biases to focus on the weights.
ΔW = BA A: r × d_in B: d_out × r y = W₀x + (α/r) B(Ax)
- Full fine-tuningTrain each entry of W₀
- LoRAFreeze W₀ · Train A and B
The rank limit applies to the update. W₀ can be full-rank, and the adapted weight matrix can stay full-rank too. For example, adding [[1, 0], [0, 0]] to the 2 × 2 identity matrix gives [[2, 0], [0, 1]]. The update has rank 1, and the result has rank 2.
Count the trainable parameters
Full fine-tuning trains one number per entry of W₀. In LoRA, A contains r × d_in trainable numbers and B contains d_out × r. Add the two counts to find the number of parameters trained for this layer.
P_full = d_out × d_in P_LoRA = r(d_in + d_out)
For a 4096 × 4096 weight matrix, full fine-tuning trains 16,777,216 parameters. At rank 8, LoRA trains 65,536. That is 0.390625% of the full count, or 256 times fewer trainable parameters for this one matrix. For a whole model, the result depends on which layers receive adapters and whether anything else is trained.
Training still needs the base weights and the intermediate values used to calculate gradients, called activations. It also still runs the original layer in the forward pass. Freezing its weights saves memory for their gradients and optimizer state, but total training memory and compute will fall by different amounts. Measure them for your actual setup.
Try the parameter calculator
Start with rank 8, then increase the rank and watch the adapter count grow. For a square matrix with side length d, the two counts are equal when r = d/2. For a rectangular matrix, the break-even rank is d_in × d_out divided by their sum. Below that point the adapter saves parameters. Above it, the two factors together use more entries than the original matrix.
0.390625% of the full parameter count. Full / LoRA ratio: 256×.
Run a LoRA forward pass in NumPy
Use a layer with three inputs and two outputs. Set r = 1 and α = 2. A first turns [2, 1, 3] into the single number −1. Then B expands it to [−1, 2]. Scaling gives [−2, 4], which we add to the base output [5, 4] to get [3, 8]. The chosen factor values stand in for values learned during training.
- A compresses xAx = [−1]
- B expands the resultB(Ax) = [−1, 2]
- Scale and add the base[5, 4] + [−2, 4] = [3, 8]
import numpy as np
W0 = np.array([[1, 0, 1], [0, 1, 1]])
x = np.array([2, 1, 3])
A = np.array([[1, 0, -1]])
B = np.array([[1], [-2]])
r, alpha = 1, 2
scale = alpha / r
base = W0 @ x
adapted = base + scale * (B @ (A @ x))
print(base, adapted)
print(np.allclose(adapted, (W0 + scale * (B @ A)) @ x))[5 4] [3. 8.] True
Check the shapes from right to left. Ax has one entry and B(Ax) has two, so it can be added to W₀x. The final line checks that calculating the update separately gives the same result as adding the update to the weight matrix first. This example runs the forward pass. Training would also need examples, a loss function, and optimizer steps.
How the adapter starts learning
A common starting point is to give A small random values and set B to zero. The product BA is then zero, so the model starts with the same outputs as the pretrained model. During training, a loss measures how far predictions are from the target. Backpropagation computes how changing A and B would affect that loss. The optimizer updates the factors while W₀ stays fixed.
import numpy as np
rng = np.random.default_rng(42)
A = rng.normal(0, 0.01, size=(2, 3))
B = np.zeros((4, 2))
print((B @ A).shape, np.count_nonzero(B @ A))(4, 3) 0
Changing an entry in B can alter the output immediately because A already produces nonzero values for typical inputs. At initialization, changing A alone has no effect because B is zero. After B changes, gradients can flow into A too. If both factors start at zero, changing either factor alone still leaves a product of zero, so both first-order gradients are zero and ordinary gradient-based training cannot get started.
Why a small update can be enough
A pretrained model has already learned many patterns. For invoice extraction, it may already recognize dates, currency values, and JSON syntax. Adaptation might only need to make a few combinations of existing features more useful for this task. A large model has many ways to change its weights, and some changes may have overlapping effects. That gives a reason to try a lower-dimensional update.
Hu and colleagues reported that LoRA matched or exceeded full fine-tuning in several settings they tested. That is evidence for the approach on those tasks. It does not establish that all useful updates have low rank. Increasing rank gives the adapter more room to change the model, but the data, chosen layers, and training settings also affect results. Compare ranks on held-out examples before deciding whether extra capacity is useful.
Truncated SVD starts with a known matrix and seeks an approximation to it. LoRA starts with trainable factors and optimizes the task loss. It never needs a full fine-tuning run to obtain a dense update first, and it may learn a different update from the one you would get by compressing a dense result.
Where LoRA fits in a Transformer
In an attention block, learned projections create queries, keys, and values. Queries and keys help decide which positions to attend to. Values provide the information to combine. An output projection then mixes the results. Each of those projections uses a weight matrix, so each is a possible place for a LoRA adapter. The projections in the feed-forward block are also candidates.
- Token featuresInput to attention
- Input projectionsQ, K, V · adapters here
- AttentionMix value vectors
- Output projectionO · adapter here
- Feed-forward blockExpansion and contraction · adapters here
Which matrices you adapt depends on the architecture and the task. Some models store the query, key, and value projections together. Some configurations adapt only a subset of projections. Check the model’s module names and the PEFT configuration, then compare a narrow target set with a broader one if you have enough training budget. Adding more target modules increases the total adapter parameter count.
Merge the adapter for inference
If you plan to serve one adapter, you can add its learned weight update to W₀ once. The merged layer then needs only its usual matrix multiplication for each input. A compatible runtime can avoid the extra adapter calculations on each request. Keeping the base and adapters separate instead can make it easier to switch between tasks without rebuilding a merged weight matrix each time.
W_merged = W₀ + (α/r)BA y = W_merged x
- UnmergedW₀x + (α/r) B(Ax)
- MergedW_merged x
import numpy as np
W0 = np.array([[1, 0], [0, 1]], dtype=float)
A, B = np.array([[1, -1]]), np.array([[2], [1]])
x = np.array([3, 1])
scale = 0.5
unmerged = W0 @ x + scale * (B @ (A @ x))
merged = (W0 + scale * (B @ A)) @ x
print(merged, np.allclose(unmerged, merged))[5. 2.] True
The expressions agree in exact arithmetic. Floating-point implementations can differ slightly because the operations occur in a different order. Quantized weights store numbers at lower precision. Depending on the format and library, merging may require dequantizing and requantizing or may be unavailable. Check the served model’s quality after merging, especially if it will run at a lower precision.
What to tune and what to measure
Start by deciding what good adaptation looks like on examples held out from training. Try a small rank and choose specific layers. If quality stalls, test a higher rank, a wider set of modules, or a different learning rate. Compare runs carefully because changing rank can also change α/r. A bigger adapter can help when the task demands a larger change, and can waste capacity when the task is already well served.
For the invoice example, test the adapter on layouts it never saw during training. Score whether the JSON parses, whether the extracted fields match the source, and whether the model invents values when a field is missing. Compare against the frozen model on the same examples. A higher rank is only useful if it improves the failures you care about or gives you another measurable benefit. Keep the evaluation set fixed so changes to the adapter are easier to interpret.
Track peak memory and training time alongside validation quality. Trainable parameter counts leave out base weights, activations, and other runtime costs. QLoRA tackles one of those costs by keeping the frozen base model in 4-bit form while training LoRA adapters. The rank idea is the same. Quantizing the base changes how its weights are stored during training.
The takeaway
Matrix rank counts independent directions. Factoring an update as BA limits those directions to at most r, while still letting that update change a large weight matrix. LoRA turns that property into an engineering choice: train two small factors, reuse the pretrained weights, and test whether the capacity you saved is worth the trade-off on your task.
References
- LoRA: Low-Rank Adaptation of Large Language ModelsHu et al. · Original paper
- Hugging Face PEFT · LoRAConfiguration, initialization, and adapter options
- NumPy · Matrix rankHow NumPy estimates rank with singular values
- QLoRA: Efficient Finetuning of Quantized LLMsDettmers et al. · Original paper