Every Layer← All lessons

Models

A detour beside the weights

LoRA and QLoRA, worked out for Qwen3-32B, and serving many adapters on one model

The lesson From base model to your model fine-tuned every one of the 32.8 billion weights, and paid for it with 524 GB of training state and a full 65.5 GB BF16 model per customer. LoRA, low-rank adaptation, leaves those weights frozen and trains a small pair of matrices beside selected layers instead. This lesson works it out for this site's model: the mathematics of the detour, why it starts as no change at all, what rank and alpha do, which of Qwen3's seven matrices per layer to adapt, how many weights that trains, how much memory it saves, how QLoRA stores the frozen weights in 4 bits, and how adapters are merged or served side by side by vLLM from one copy of the base model.

Chapter 1 of 11

Why not move every weight

What full fine-tuning costs, measured on GPT-3

Full fine-tuning has three costs that grow with the model. Training holds the optimizer's state for every weight, 16 bytes each in mixed precision. Each tuned model is a full copy, so every customer or task adds the model's whole size to storage. And each copy has to be loaded into its own GPU memory to be served, so ten tuned models need ten times the GPUs of one.

The LoRA paper by Hu and colleagues starts from a hypothesis about the change that fine-tuning makes. It supposes that the difference between the tuned weights and the original weights of a large matrix has a low intrinsic rank: that it can be written, very nearly, as the product of two much thinner matrices. So the method freezes the original matrix and trains only the two thin ones, and the paper's experiments then show that this works well for the tasks it tested. The hypothesis is not true of every fine-tuning run. Biderman and colleagues measured the changes made by full fine-tuning on code and mathematics and found their rank 10 to 100 times higher than typical LoRA settings, which is one reason LoRA learned less of those domains in their tests.

The paper's numbers for GPT-3 with 175 billion weights show the scale. Memory during training fell from 1.2 TB to 350 GB, because no optimizer state is kept for the frozen weights. With a rank of 4 on the query and value matrices only, the saved result fell from 350 GB to 35 MB, about 10,000 times smaller. A hundred tuned models cost 350 GB plus 100 × 35 MB, about 354 GB, against 35 TB as full copies. Training was also about 25 percent faster, because no slopes have to be computed for most of the weights.

There is one more property the paper stresses. Once training is done the two thin matrices can be added into the frozen one, and the model runs with no extra work at all.

Chapter 2 of 11

The change as a product of two thin matrices

W0 stays, B × A is added beside it

Take one weight matrix of the model, W0. It turns an input vector of k numbers into an output of d numbers. Fine-tuning would change it to W0 plus some change, ∆W, of the same shape. LoRA writes the change as B times A, where A has r rows and k columns, and B has d rows and r columns. The number r, the rank, is small, often 8 to 64, while k and d are in the thousands. The layer's output becomes W0 times x plus B times A times x. The input is first squeezed by A down to r numbers, then spread by B back out to d numbers, and the result is added to the frozen layer's own output.

Take the query projection of this model, q_proj. It turns the 5,120 numbers of a token's vector into 8,192 numbers, the queries of 64 heads of 128. Its weight matrix holds 8,192 × 5,120 = 41,943,040 numbers. With a rank of 16, A is 16 × 5,120, which is 81,920 numbers, and B is 8,192 × 16, which is 131,072. Together that is 212,992, about half a percent of the matrix beside it.

A toy layer with 2 numbers in and 2 out makes the arithmetic visible. Let W0 be the rows (1, 2) and (0, 1), x be (2, 1), A be the single row (0.3, -0.1) and B the column (0.4, 0.2), with a rank of 1 and a scale of 2. W0x is (4, 1). Ax is 0.5, BAx is (0.2, 0.1), scaled by 2 it is (0.4, 0.2), and the output is (4.4, 1.2).

Chapter 3 of 11

It starts as no change at all

B begins at zero, so the first pass is the base model

The two matrices are initialised differently, and the difference is deliberate. The paper sets A to small random numbers from a Gaussian distribution and B to zeros. PEFT's default, init_lora_weights=True, does the same in spirit, with A drawn from a Kaiming-uniform distribution and B set to zero. Anything multiplied by a zero matrix is zero, so on the first pass B times A times x adds nothing, and the model behaves exactly as the base model does. Training begins from everything the model already knows, and the detour can only move it from there.

The slopes show what happens next. The slope for B depends on A times x, which is not zero, so B moves on the first step. The slope for A passes through B, which is still zero, so A's slope is exactly zero on the first step and A starts to move only once B has. The two matrices then learn together.

The frozen weights are handled differently from the trained ones. The backward pass still runs through the whole model, because the slopes have to travel from the loss down through every layer to reach the detours in the lower layers. But for the frozen weights no slope is stored, no master copy is kept and no optimizer averages exist. The optimizer is given only the A and B matrices. That is where the memory saving comes from, and it is also why training is faster: computing a layer's input slopes is needed, and computing its weight slopes, half of the backward work and a third of the whole step, is skipped.

Chapter 4 of 11

Rank and alpha

How wide the detour is, and how loud

Two settings define every LoRA adapter. The rank, r, is the width of the detour: the number of values the input is squeezed into between A and B. A higher rank gives the adapter more weights and more capacity to express a change, and costs proportionally more memory and storage. The LoRA paper found that very small ranks were enough for its tasks: on GPT-3, adapting the query and value matrices, a rank of 4, and even 1, did well.

Alpha, lora_alpha in PEFT, sets how strongly the detour's output is added. The detour's output is multiplied by alpha divided by r before it is added to the frozen path. The paper explains why it is written this way. With Adam, tuning alpha is roughly the same as tuning the learning rate, so the authors set alpha to the first rank they tried and did not tune it. The paper says that dividing by r helps reduce the need to retune other settings when the rank changes. It does not hold the detour's loudness fixed. The rsLoRA paper by Kalajdzievski later showed that with alpha divided by r, the update shrinks as the rank grows, so raising the rank can make the adapter learn more slowly. That is the reason for use_rslora, below.

In PEFT the defaults are r = 8 and lora_alpha = 8, a scale of 1. A common recipe of r = 16 with lora_alpha = 32 gives a scale of 2. The QLoRA paper used r = 64 with alpha 16, a scale of 0.25, and reported that the rank mattered little for its results once LoRA was applied to all layers. PEFT also offers use_rslora, rank-stabilised LoRA, which divides by the square root of r instead of r, so r = 64 with alpha 16 gives 16 ÷ 8 = 2.

The last common setting is lora_dropout, which randomly zeroes some inputs to the detour during training to reduce overfitting. PEFT's default is 0.0. QLoRA used 0.1 for models up to 13 billion weights and 0.05 for 33 and 65 billion.

Chapter 5 of 11

Which matrices get a detour

Seven linear layers per block, and the choice between two of them and all

Each of Qwen3-32B's 64 blocks has seven weight matrices, and PEFT names them by the module names in the model's weight files. In attention there are q_proj, 5,120 to 8,192, k_proj and v_proj, each 5,120 to 1,024, because the model has only 8 key-value heads of 128, and o_proj, 8,192 back to 5,120. In the feed-forward layer there are gate_proj and up_proj, each 5,120 to 25,600, and down_proj, 25,600 to 5,120. The embedding table, the output head and the small norm weights are not linear layers of a block.

The target_modules setting in LoraConfig chooses which of these get a detour. It takes a list of names, or the string all-linear, which selects every linear layer except the output layer. Left unset, PEFT chooses by architecture.

The two classic choices come from the two papers. The LoRA paper adapted only the query and value matrices in most of its experiments, and found that adapting both was better than adapting one with a higher rank for the same budget. The QLoRA paper found the opposite emphasis: the most important setting was how many layers were adapted, and LoRA on all linear layers of each block was needed to match full 16-bit fine-tuning. The PEFT docs follow it and suggest all-linear when the aim is to match full fine-tuning.

The feed-forward matrices are where most of this model's weights are, 25.2 billion of 31.2 billion in the blocks, so leaving them out leaves most of the model unadaptable. Adding them costs far fewer trained weights than their size suggests, because the cost is r times the sum of the two sides of a matrix, while the matrix itself holds their product.

Chapter 6 of 11

Counting the trained weights

r × (in + out) per matrix, times 64 blocks

Each adapted matrix adds r × (in + out) trained weights: r × k for A and d × r for B. With that rule the whole adapter can be counted for this model.

At r = 16, q_proj and o_proj each add 16 × 13,312 = 212,992. k_proj and v_proj each add 16 × 6,144 = 98,304. gate_proj, up_proj and down_proj each add 16 × 30,720 = 491,520. A block with only q_proj and v_proj adapted gets 311,296 trained weights, and 64 blocks make 19,922,944. That is 0.061 percent of 32,762,123,264. A block with all seven adapted gets 2,097,152, and 64 blocks make 134,217,728, which is 0.41 percent. At r = 64 on all seven the count is four times higher, 536,870,912, or 1.64 percent.

The adapter is saved on its own, as the A and B matrices of every adapted layer plus a small config file. At 2 bytes a weight, the query-and-value adapter at r = 16 is 39.8 MB, the all-linear one at r = 16 is 268 MB, and the all-linear one at r = 64 is 1.07 GB. The base model is 65.5 GB at the same precision, so even the largest of these is under 2 percent of it.

An adapter fits only the base checkpoint it was trained beside. Its matrices are corrections to particular weights, and on any other model, even another release of the same size, they would add the corrections to the wrong numbers. A quantized copy of the same checkpoint, in 8 or 4 bits, holds approximately the same weights, so the adapter still applies there, as it does in the serving and QLoRA chapters below. Each weight is rounded a little differently in that copy, so the outputs can shift slightly from what the adapter produced in training, and a quality check on the copy that will actually serve is worth running.

Chapter 7 of 11

Memory to train it

The frozen model in 16 bits, and 16 bytes only for the detour

Now the memory for training with an adapter. The frozen weights are only read, so they are held once, in bfloat16, and need no master copy, no slope and no optimizer state. For this model that is 65.5 GB. The trained weights are held with the full mixed-precision set: a 16-bit copy, a 32-bit master copy, a slope and AdamW's two averages, 16 bytes each. For the all-linear adapter at rank 16 that is 134,217,728 × 16 bytes, 2.15 GB.

Together that is about 67.7 GB of model state, against 524 GB for full fine-tuning, which is about 13 percent. The sizes here are in decimal gigabytes, 10⁹ bytes. An 80 GB H100 holds 80 GiB, 80 × 2³⁰ bytes, about 85.9 GB in the same units. So the model state fits on one H100 with about 18 GB to spare, less a gigabyte or so for the CUDA context and the allocator. The activations still need that room: the backward pass runs through every layer, and the input of each adapted layer is needed to compute its A's slope. The logits are easy to forget. For every position the output head writes one score per vocabulary entry, 151,936 of them, so a window of 4,096 tokens has 4,096 × 151,936 scores: about 1.2 GB in bfloat16 and 2.5 GB if they are turned to 32 bits for the loss, plus their slope of the same size. With activation checkpointing on, as TRL's SFTConfig does by default, and windows of 1,024 or 2,048 tokens, a single H100 can train this adapter. Without checkpointing, or with long windows, it can't.

The optimizer settings change with the method. Since only new weights are learned, starting from zero, the TRL docs suggest a learning rate of about 1 × 10⁻⁴ for adapters, five times the 2 × 10⁻⁵ default for full fine-tuning.

The saving is in the optimizer state and the slopes, which were 14 of the 16 bytes per weight. The cost of reading and running the whole base model stays. Every training step still does a forward pass through all 32.8 billion frozen weights.

Chapter 8 of 11

QLoRA: the frozen weights in 4 bits

NF4, double quantization and paged optimizer state

The frozen weights are never updated, so they do not need 16 bits of precision for storage, only for arithmetic. QLoRA, by Dettmers and colleagues, stores them in 4 bits and trains a LoRA adapter on top. Whenever a frozen weight is used, its block is converted back to bfloat16 and the matrix multiply runs in 16 bits. The slopes flow through the dequantized weights into the adapters as before.

The 4-bit format is NormalFloat, NF4. Trained weights are roughly normally distributed around zero, and NF4's 16 values are placed so that each is used about equally often for such a distribution. Weights are quantized in blocks of 64, each block with its own scale constant in 32 bits. That constant adds 32 ÷ 64 = 0.5 bits per weight. Double quantization quantizes the constants too, into 8-bit floats in blocks of 256, which brings the overhead down to 8 ÷ 64 + 32 ÷ (64 × 256) = 0.127 bits. A weight then costs 4.127 bits. Paged optimizers, the third idea, move optimizer state to CPU memory when the GPU runs short, which absorbs the memory spikes of long sequences.

For this model, assume the 64 blocks' linear layers, 31,205,621,760 weights, are stored in NF4 and the embedding table, output head and norms stay in bfloat16. The linear layers take 31.2 billion × 4.127 ÷ 8 = 16.1 GB, and the rest takes 3.1 GB, so the frozen model is about 19.2 GB. With the 2.15 GB adapter, the model state is about 21.4 GB. The paper reported finetuning a 65 billion model in under 48 GB where 16-bit fine-tuning needed over 780 GB, and that NF4 with LoRA on all linear layers matched 16-bit fine-tuning in its tests.

Chapter 9 of 11

Merging an adapter into the weights

Add B × A into W0 and the detour is gone

A trained adapter can be served in two ways. The first is to merge it. Since the adapted layer computes W0 times x plus the scale times B times A times x, and both terms are linear in x, the two can be combined into a single matrix: W equals W0 plus the scale times B times A. That matrix has exactly the shape of W0. Replace W0 with it in every adapted layer and the result is an ordinary model again, with no extra matrices and no extra work per token. This is the property the LoRA paper stresses: no added inference latency.

In the toy layer the scaled product of B and A is the matrix with rows (0.24, -0.08) and (0.12, -0.04). Added to W0 it gives rows (1.24, 1.92) and (0.12, 0.96). Multiplying that by x = (2, 1) gives (4.40, 1.20), the same output the detour gave.

In PEFT the call is merge_and_unload(). The docs point out that it is not an in-place operation: it returns the merged model, and the returned value is what must be used and saved. Once merged, the adapter can't be separated again without the original weights.

Merging gives up the reason for using LoRA in the first place. The merged model is a full 65.5 GB copy, specific to one adapter, and needs its own GPU memory to serve. It is the right choice when one adapter will serve all the traffic on a set of GPUs. When many adapters share a base model, keeping them apart is better. An adapter trained with QLoRA is usually merged into a 16-bit copy of the base, since the merged weights would be changed again by quantizing them back to 4 bits.

Chapter 10 of 11

Serving many adapters on one base

vLLM loads the base once and picks the adapter per request

The second way to serve an adapter is to keep it apart. The base model is loaded into GPU memory once, the adapters sit beside it, and each request says which adapter it wants. vLLM supports this directly. The server is started with --enable-lora and given adapters by name with --lora-modules, in the form name=path. Each adapter then appears in GET /v1/models next to the base model, and a request selects it by putting its name in the model field, exactly as it would choose a model.

vLLM runs the base weights for every request in a batch together and applies each request's own detour to it. Several engine settings bound this. --max-loras, 1 by default, is how many different adapters can be in a single batch. At the default every batch uses one adapter at most, and requests for other adapters wait for a later batch. For a batch to mix requests for different adapters, --max-loras has to be raised, and each slot it adds reserves GPU memory for one adapter of the largest rank allowed. --max-lora-rank, 16 by default, is the largest rank the server accepts, so an adapter trained at rank 64 needs it raised to 64. --max-cpu-loras sets how many adapters are kept in host memory, ready to be swapped in.

Adapters can also be added and removed while the server runs. With the environment variable VLLM_ALLOW_RUNTIME_LORA_UPDATING set to True, a POST to /v1/load_lora_adapter with a lora_name and a lora_path loads one, and /v1/unload_lora_adapter removes it.

The arithmetic is the reason to do this. One worker holds the base once, 34.3 GB in the official FP8 build this factory serves, Qwen3-32B-FP8. Most of its weights take 1 byte there, and some layers stay at higher precision. A hundred query-and-value adapters at rank 16 are about 4 GB. A hundred all-linear adapters at rank 16 are 26.8 GB, which is why only some are kept on the GPU at a time and the rest wait in host memory.

Chapter 11 of 11

Routing to a worker that has the adapter

To the factory an adapter is one more model name

Seen from outside the worker, an adapter is a model name. That has consequences for every layer in front of the GPUs. The AI gateway that checks which keys may use which models now checks adapter names too, so that one customer can't call another customer's adapter. And the endpoint picker that chooses a worker for each request has a new thing to consider: whether a worker already has the requested adapter loaded.

With three workers and dozens of adapters, not every worker holds every adapter on its GPU. A request sent to a worker that has its adapter ready starts at once. One sent elsewhere waits while the adapter is loaded from host memory or from storage, and may push another adapter out. So a picker that knows which adapters each worker holds can prefer the worker that has the one requested, as long as that worker is not overloaded.

The KV cache adds a second reason. The keys and values that attention stores for a prompt are computed through the adapted layers, so the same prompt under two adapters gives two different sets. A cached prefix computed for one adapter is no use to a request for another. Requests for the same adapter and the same system prompt gain most from going to the same worker.

The last check is the template. An adapter fine-tuned with a changed chat template must be served with that template, or every request is rendered differently from the conversations it learned on.

What to keep

Small trained matrices, one shared model

LoRA freezes the model and trains a pair of thin matrices beside chosen layers, so that each adapted layer computes W0x plus alpha over r times BAx. B starts at zero, so training starts from the base model. For Qwen3-32B at rank 16 the query and value matrices alone take 19.9 million trained weights and all 448 linear layers take 134 million, under half a percent of the model, saved as files of 40 MB to 268 MB. Training state falls from 524 GB to about 68 GB, and to about 21 GB with QLoRA's 4-bit frozen weights. An adapter can be merged into a full model with no cost per token, or kept apart and served by vLLM beside one copy of the base, chosen by name in each request and routed to a worker that holds it.