←Blog

What Is LoRA? How It Works, and When to Use It Instead of RAG or a Bigger Context Window

What Is LoRA? How It Works, and When to Use It Instead of RAG or a Bigger Context Window

If you've spent any time around AI models lately, you've probably seen the word LoRA thrown around. Somebody fine-tuned a model "with a LoRA," somebody else downloaded a LoRA that makes Stable Diffusion draw in a specific art style, and then somebody in the comments says you don't need any of that because you can just use RAG, or just paste everything into a model with a giant context window. So which is it? In this post, I wanna go over what LoRA actually is, how it works (including the math, which is honestly less scary than it looks), when it's the right tool compared to RAG or a bigger context window, and how it fits into both LLMs and image diffusion models.

The problem LoRA solves

A neural network is mostly a big pile of matrices. When you "fine-tune" a model, you take a model that's already been trained on a huge amount of data and keep training it on your smaller, more specific data, so every one of those matrices gets nudged a little bit toward what you want.

The problem is that modern models are enormous. A 7 billion parameter LLM has, well, 7 billion numbers to update. And it's worse than it sounds, because training needs a lot more memory than just the weights. With the Adam optimizer and mixed precision, you're typically storing the weights, the gradients, a full precision copy of the weights, and two optimizer values per parameter. That works out to something like 16 bytes per parameter, so roughly 112 GB for a 7B model before you even count the activations. That's multiple data center GPUs just to fine-tune a "small" model.

And then there's storage. If you fine-tune a model for five different tasks, you now have five full copies of the model, each one the same size as the original.

LoRA, which stands for Low-Rank Adaptation, was introduced in a 2021 paper by Edward Hu and colleagues, and the idea is basically: what if we don't touch the original weights at all, and instead train a tiny add-on that describes how the weights should change?

How it works

Fine-tuning is just adding a matrix

Take one weight matrix in the model and call it W0. Let's say it's d × k, so for a typical layer in a 7B model, that's 4096 × 4096, which is about 16.8 million numbers. However full fine-tuning changes that matrix, you can always write the result as the original plus some difference:

W = W₀ + ΔW

In regular fine-tuning, ΔW is the same size as W0, so you're learning 16.8 million numbers for that one layer. The key insight behind LoRA is that you probably don't need all of that freedom. The paper builds on earlier research showing that when you adapt a big pretrained model to a new task, the useful changes tend to live in a much smaller space than the full matrix. In other words, ΔW has a low "intrinsic rank."

A quick refresher on rank

The rank of a matrix is the number of truly independent directions it contains. A 4096 × 4096 matrix can have rank 4096, but if every row is just some combination of, say, 8 underlying patterns, then its rank is 8, and you're storing way more numbers than you need to describe it.

Here's the useful part: any d × k matrix with rank r can be written as the product of two skinny matrices:

ΔW = B · A

B is d × r   (4096 × 8)
A is r × k   (8 × 4096)

Multiply a 4096 × 8 matrix by an 8 × 4096 matrix and you get back a full 4096 × 4096 matrix, but you only had to store r(d + k) numbers to describe it. For r = 8, that's 65,536 numbers instead of 16,777,216, or about 0.39% of the original.

A large square standing for the 16.8 million numbers in a 4096 by 4096 weight matrix, with a tiny orange square in its corner for the 65,536 numbers in a rank 8 LoRA, and a dashed outline for rank 64.
Drawn to scale: the orange corner is everything a rank 8 LoRA trains for one 4096 × 4096 layer.

(If you remember SVD from linear algebra, this is the same idea. The best rank-r approximation of any matrix comes from keeping its top r singular values, and that's also a product of skinny matrices. LoRA just skips the decomposition step and learns the skinny matrices directly.)

It's a lot easier to get a feel for this with a matrix you can actually look at. A grayscale image is just a matrix of brightness values, so here's a 96 × 96 one. Drag the slider to rebuild it from only its top r singular vectors, which is the same thing as storing it as a 96 × r matrix times an r × 96 matrix, exactly like B and A:

Interactive: a picture with structure is nearly all there by rank 8. Switch to random noise and it isn't, because noise has no structure to compress.

That's the whole bet LoRA makes. The change fine-tuning needs to make to a weight matrix is more like the picture than the noise, so a small rank captures most of it.

The LoRA forward pass

So LoRA freezes W0 completely and only trains A and B. For an input vector x, the layer's output becomes:

h = W₀x + (α / r) · B(Ax)
Diagram of the LoRA forward pass. The input x goes through the frozen 4096 by 4096 matrix W0 on the top path. On the bottom path, A squeezes x down to r numbers and B expands them back to 4096; that result is scaled by alpha over r and added to W0 x to give the output h.
The input takes two paths: the frozen matrix does what it always did, and the skinny trained path adds a correction.

A few things worth pointing out here:

  • The parentheses matter. You compute Ax first, which squeezes the input down to just r numbers, and then B expands it back out. You never actually build the full 4096 × 4096 ΔW during training, which is a big part of why it's cheap.
  • α / r is a scaling factor. α (alpha) is a hyperparameter you pick, and dividing by r means you can change the rank without having to completely retune your learning rate. You'll see configs like r=16, alpha=32 all the time, which just means the update gets scaled by 2. (There's a follow-up called rsLoRA that argues you should divide by √r instead, which works better at higher ranks.)
  • The initialization is clever. A starts out as small random numbers, but B starts out as all zeros. That means BA = 0 at the start, so before any training happens, the model behaves exactly like the original. Training starts from the pretrained model, not from some randomly broken version of it.

That last point has a fun side effect if you look at the gradients. If δ is the gradient of the loss with respect to the layer's output h, then by the chain rule:

∂L/∂B = (α / r) · δ (Ax)ᵀ
∂L/∂A = (α / r) · Bᵀ δ xᵀ

Since B is all zeros at the start, the gradient for A is zero on the very first step. Only B learns at first, and once B is no longer zero, A starts learning too. The random A basically acts as a starting set of directions, and B learns how much of each direction to use.

Here's what that looks like in an actual (tiny) training run. B starts out blank, so BA is blank too, and then both fill in as gradient descent fits BA to a rank 3 target:

A toy run: it fits a 48 × 48 update directly instead of training a whole model, but every frame is the real state of A, B and BA at that step.

Merging: zero extra cost at inference

This is my favorite part. Once you're done training, B and A are just numbers, so you can multiply them out and fold them right back into the original weight:

W_merged = W₀ + (α / r) · BA

Now you have a regular matrix the same size as before, and the model runs at exactly the same speed as the original. There's no extra layer, no extra latency, nothing. Or you can keep the adapter separate, which lets you swap different LoRAs in and out of the same base model on the fly.

Here's all of that in a few lines of NumPy, so you can see it actually works:

import numpy as np

rng = np.random.default_rng(0)
d, k, r, alpha = 4096, 4096, 8, 16

W0 = rng.standard_normal((d, k)) / np.sqrt(k)  # frozen pretrained weight
A = rng.standard_normal((r, k)) * 0.01         # small random init
B = np.zeros((d, r))                           # zeros, so BA = 0 at the start
scale = alpha / r

def forward(x):
    # x is (k,). Never builds the d x k update; goes through the r-wide bottleneck.
    return W0 @ x + scale * (B @ (A @ x))

print(f"full matrix params: {d * k:,}")
print(f"LoRA params:        {r * (d + k):,} ({r * (d + k) / (d * k):.2%})")

x = rng.standard_normal(k)
print("starts identical to base model:", np.allclose(forward(x), W0 @ x))

# Pretend training moved B, then merge the adapter into the weight.
B = rng.standard_normal((d, r)) * 0.01
W_merged = W0 + scale * (B @ A)
print("merged weight gives same output:", np.allclose(forward(x), W_merged @ x))
print("rank of the update:", np.linalg.matrix_rank(B @ A))
full matrix params: 16,777,216
LoRA params:        65,536 (0.39%)
starts identical to base model: True
merged weight gives same output: True
rank of the update: 8

What that buys you

Scale that up to a whole model and the numbers get pretty wild. If you put rank 8 LoRAs on just the query and value projections of every attention layer in a Llama 2 7B model (32 layers, two 4096 × 4096 matrices each), you're training about 4.2 million parameters instead of 7 billion. That's around 0.06% of the model. The original paper reported that on GPT-3 175B, LoRA cut the number of trainable parameters by 10,000 times and GPU memory use by about 3 times, and a saved adapter was around 35 MB instead of a 350 GB checkpoint.

Memory is where it really pays off, because the frozen weights don't need gradients or optimizer state. Only the tiny A and B matrices do. Then QLoRA took it further by storing the frozen base model in 4-bit precision while training the LoRA in higher precision, which let people fine-tune a 65B model on a single 48 GB GPU. That's a big reason why so many fine-tuned open models exist now: you can do this on one rented GPU, or even a gaming card for smaller models.

The original paper also found that surprisingly small ranks worked well, sometimes even r = 1 or 2. These days most people apply LoRA to all the linear layers in the model rather than just the attention ones, and pick a rank somewhere between 8 and 64.

LoRA vs RAG vs a bigger context window

Ok, so here's where people get confused, because all three of these get pitched as ways to "make the model know about your stuff." But they actually change completely different things:

  • A bigger context window changes what the model can see for one request. You paste your docs into the prompt, the model reads them, and when the request is over, it forgets all of it.
  • RAG (Retrieval-Augmented Generation) changes what the model sees too, it's just smarter about it. Instead of pasting everything, you search your documents (usually with embeddings and a vector database) and only put the most relevant chunks into the prompt.
  • LoRA changes the model itself. It changes how the model behaves, every time, without you having to put anything in the prompt.

A good way to think about it: context and RAG are like handing someone a reference book during an exam. LoRA is like sending them to a training course before the exam. The training course is great for teaching skills and habits, but it's a pretty unreliable way to make someone memorize a phone book.

LoRA is surprisingly bad at teaching facts

This is the part that trips a lot of people up. It seems like if you want a model to know about your company's internal docs, you'd fine-tune it on them. But research keeps showing that's not a great idea. A 2024 study found that fine-tuning models on knowledge they didn't already have made them learn it slowly, and made them more likely to hallucinate in general. And the aptly named "LoRA Learns Less and Forgets Less" found that LoRA in particular learns less from new domains than full fine-tuning does (although, as the title says, it also messes up less of what the model already knew).

There are also practical problems. Facts change, and every time yours do, you'd have to retrain. And a fine-tuned model can't tell you where it learned something, while a RAG system can point straight to the document it pulled from.

So when do you use which?

If you need...Use
The model to answer from a small set of docs, occasionallyContext window
Answers from a big or frequently changing knowledge baseRAG
Citations, or answers that depend on who's askingRAG
A specific output format, style, tone, or voice every timeLoRA
A narrow task done reliably (classifying, extracting, tool calling)LoRA
A small model to do what a big model does with a long promptLoRA
Lots of different behaviors served from one base modelLoRA (multiple adapters)

Some more specific rules of thumb:

Just use the context window when your info fits comfortably, you aren't making a ton of requests, and you want something working today. Context windows are huge now, and prompt caching makes re-sending the same big prompt a lot cheaper than it used to be. Don't build a vector database for 40 pages of docs. That said, models do get worse at using information buried in the middle of really long contexts (there's a well known paper about this literally called "Lost in the Middle"), and you pay for every one of those tokens on every request.

Use RAG when your knowledge base is too big to paste in, changes often, needs permissions (different users can see different docs), or needs citations. It's also the only one of the three where updating the model's knowledge is as easy as updating a database row.

Use LoRA when the problem is how the model responds, not what it knows. If you've got a 2,000 token system prompt full of "always respond in this JSON format, never do X, write like Y" and the model still messes it up sometimes, that's a great candidate. A LoRA bakes that behavior in, so your prompts get shorter and your output gets more consistent. It's also the move when you want a small, cheap, fast model to do one narrow task as well as a much bigger model. Keep in mind that LoRA requires access to the model weights, so if you're using a hosted model through an API, you generally can't do this yourself. Some providers offer fine-tuning as a service, but you don't get the weights back.

And they aren't mutually exclusive. One of the strongest setups is a LoRA that teaches a model how to use retrieved documents well (stay grounded, ignore irrelevant chunks, cite its sources), plus RAG to supply the actual facts. There's a paper called RAFT that does exactly this.

LoRA for LLMs in practice

If you want to try it, the Hugging Face PEFT library is what most people use. Wrapping a model is only a few lines:

from peft import LoraConfig, get_peft_model

config = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    task_type="CAUSAL_LM",
)
model = get_peft_model(base_model, config)
model.print_trainable_parameters()

From there you train it like any other model, and the output is a small adapter file you can either load on top of the base model or merge into it. Serving tools like vLLM can even load many LoRA adapters on top of a single copy of the base model at the same time, so you can have a different adapter for each customer or each task without needing a separate GPU for each one.

The biggest thing to get right is your data. A few hundred to a few thousand really good examples of exactly the input and output you want will beat tens of thousands of mediocre ones. Since LoRA is mostly teaching behavior, your examples are the spec.

LoRA for diffusion models

LoRA was written with language models in mind, but it absolutely took over the image generation world. Diffusion models like Stable Diffusion and Flux are also mostly made of big matrices, especially the attention layers, and the first popular LoRA implementation for Stable Diffusion showed up at the end of 2022. Now it's the standard way people teach image models new things.

The math is identical. You freeze the model and add low-rank BA updates to the attention layers. In a diffusion model, the cross-attention layers are where the text prompt gets connected to the image, so a LoRA there can tie a new word (like a made-up trigger word for your character) to a new visual concept. Some variants, like LoCon from the LyCORIS project, also add low-rank updates to the convolution layers to capture more texture and detail.

Common uses:

  • A specific character, person, or product. Train on 15 to 50 images of the same subject, and the model can generate it in new poses and scenes.
  • An art style. Train on a consistent set of images in that style.
  • Concepts or fixes, like better hands, a certain kind of lighting, or a specific camera look.

The nice thing for image models is the file size. A full Stable Diffusion checkpoint is several gigabytes, while a LoRA is usually somewhere between a few megabytes and a couple hundred, depending on rank. And because each LoRA is just a set of additive updates, you can stack several at once and control how strongly each one is applied by changing the scale factor. Something like 0.8 of your character LoRA plus 0.5 of a watercolor style LoRA. They won't always play nicely together, since two adapters can fight over the same weights, but it often works surprisingly well.

Do RAG and context windows matter for diffusion models?

Mostly no, but it's not as black and white as "they don't apply."

First, the reason they mostly don't apply: a diffusion model doesn't really have a "context window" in the LLM sense. It has a text encoder that turns your prompt into a fixed set of embeddings, and in Stable Diffusion 1.5 and SDXL, the CLIP text encoder only reads the first 77 tokens (UIs work around this by splitting longer prompts into chunks, but that's a workaround). Newer models that use a T5 text encoder, like SD3 and Flux, accept a few hundred tokens. But even with a longer prompt, the bigger problem is that words are a lossy way to describe images. You can't describe your dog in enough detail that the model draws your dog and not just a dog that roughly matches. There's no paragraph of text that will get you that. And standard text-to-image pipelines don't have a retrieval step, so there's no obvious place for RAG to plug in. So for "make the model draw this specific thing," LoRA (or similar training methods like DreamBooth and textual inversion) has been the go-to for a reason.

But here's where it gets less clear cut:

  • Images can be context too. Adapters like IP-Adapter let you feed a reference image into a diffusion model alongside the prompt, so it picks up the style or subject of that image without any training. Newer image editing models, like Flux.1 Kontext, take reference images as input directly. That's basically the image version of "just put it in the context window." It's faster and requires no training, but in my opinion it's usually less faithful than a well-trained LoRA when you need a subject to look the same across lots of images.
  • Retrieval-augmented diffusion exists. Research projects like retrieval-augmented diffusion models (from the same research group behind Stable Diffusion) and Google's Re-Imagen look up related images from a database and condition on them while generating. It's not something you'll find in your typical Stable Diffusion setup, but the idea is real. And you could build a simple version yourself by searching for reference images and feeding them into an IP-Adapter.
  • Multimodal models blur the line. Some newer models generate images from within an LLM-style architecture and accept reference images in the conversation, so "context" there means pretty much the same thing it does for text.

So the more accurate version is this: for diffusion, the job that context and RAG do for LLMs (giving the model information at generation time instead of training it in) is handled by image conditioning, not text. The same tradeoff still applies. Conditioning is quick and flexible, while LoRA is more consistent and costs nothing extra at generation time once it's trained.

Wrapping up

LoRA is one of those ideas that seems almost too simple to work. Freeze the model, learn the change as the product of two skinny matrices, and fold it back in when you're done. But it's a big reason fine-tuning went from something only big labs could afford to something you can do on one GPU in an afternoon.

The main thing to remember is that LoRA, RAG, and context windows aren't really competing with each other. If the problem is what the model knows, give it the information at request time with the context window or RAG. If the problem is how the model behaves, train it with LoRA. And if you need both, use both. For image models, LoRA is still the go-to for teaching the model something new, with reference image conditioning playing the role that context plays for LLMs.

#Discussion · 0 comments

Leave a comment

By submitting a comment, you verify that you agree to our Privacy Policy and Terms of Service.