Sub topic 9
Quantization basics for fine-tuning
Quantization stores a model's weights in fewer bits. In LoRA fine-tuning it is mainly a way to make the frozen base model smaller. This chapter explains how quantization works and where it loses accuracy. It also covers what it saves and which settings matter. The next chapters use these ideas for QLoRA.
This chapter assumes you know what a weight matrix is and how floating-point types differ in size. It also assumes you have a LoRA adapter set up, as in the earlier chapters on PEFT.
Why quantization matters here
LoRA already removes most of the cost of training, because only the small adapter matrices get gradients and optimizer states. What remains is the frozen base model, which still has to sit in GPU memory. A 7B-parameter model in 16-bit precision needs about 14 GB for its weights alone. That is before activations, the adapter, and its optimizer states.
Quantization attacks that remaining cost. If the frozen weights take 4 bits each instead of 16, the base model shrinks to roughly a quarter of its size. Because the base weights are never updated, rounding them once does not interfere with gradient updates. The adapter trains in higher precision and can partly compensate for the rounding error.
Number formats you will meet
| Format | Bits per value | Typical use |
|---|---|---|
| float32 | 32 | Default dtype of many checkpoints, master weights |
| bfloat16 | 16 | Training and inference on recent GPUs, wide range |
| float16 | 16 | Training and inference, narrower range, may overflow |
| int8 | 8 | Quantized weights, 256 levels |
| 4-bit (int4, NF4, FP4) | 4 | Quantized weights, 16 levels |
bfloat16 and float16 are both 16-bit floats. bfloat16 keeps the same exponent range as float32 and has fewer precision bits, so it rarely overflows. Float16 has more precision bits but a small range.
You can check the effect of dtype on a real model. This loads the same model twice and prints how many gigabytes of weights each copy uses.
import torch
from transformers import AutoModelForCausalLM
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
full = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32)
print("float32:", round(full.get_memory_footprint() / 1e9, 2), "GB")
del full
half = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)
print("bfloat16:", round(half.get_memory_footprint() / 1e9, 2), "GB")The second number is about half the first. If you do not pass torch_dtype, the weights are loaded in float32 by default, which wastes memory for fine-tuning.
How quantization works
The basic scheme is absmax (absolute-maximum) quantization. You pick a scale so that the largest weight magnitude maps to the largest integer level. Then you divide every weight by the scale and round.
For a signed n-bit integer, the largest level is qmax = 2^(n-1) - 1. That is 127 for 8 bits and 7 for 4 bits. The steps are:
- Compute
scale = max(|w|) / qmax. - Store
q = round(w / scale), clamped to the integer range. - To use the weight, compute
w_hat = q * scale. This is dequantization.
The difference w - w_hat is the quantization error. Rounding makes the error at most half a step, which is scale / 2. A larger scale means coarser steps and larger error.
Why one scale per tensor fails
A single outlier weight inflates the scale for the whole tensor. Every other weight then falls into only a few levels, and many round to zero. Large language models are known to have outlier values, so this problem is real.
The fix is blockwise quantization. You split the tensor into small blocks, such as 64 values, and give each block its own scale. An outlier then only damages its own block. The following script shows the difference.
import torch
torch.manual_seed(0)
def quantize_blockwise(w, block=64, bits=4):
qmax = 2 ** (bits - 1) - 1
blocks = w.reshape(-1, block)
scale = blocks.abs().amax(dim=1, keepdim=True) / qmax
q = torch.clamp(torch.round(blocks / scale), -qmax, qmax).to(torch.int8)
return q, scale
def dequantize_blockwise(q, scale, shape):
return (q.float() * scale).reshape(shape)
w = torch.randn(4096) * 0.02 # typical small weights
w[100] = 5.0 # one outlier
for block in (4096, 64): # 4096 = one scale for the whole tensor
q, scale = quantize_blockwise(w, block=block, bits=4)
w_hat = dequantize_blockwise(q, scale, w.shape)
err = (w - w_hat).abs().mean().item()
print(f"block={block:5d} mean abs error={err:.5f}")With one scale for all 4096 values, the outlier forces a large step size and most small weights collapse to zero. With 64-value blocks, only the block containing the outlier suffers, and the printed error drops sharply. The storage cost of blocks is one extra scale per block, which is small.
Storage overhead and the memory arithmetic
Blockwise scales are not free. With a block size of 64 and a 32-bit float scale per block, the scales add 32 / 64 = 0.5 bits per weight. A "4-bit" model therefore uses about 4.5 bits per weight. Double quantization, used by QLoRA, quantizes the scales themselves to 8 bits in groups of 256. This brings the overhead down to about 0.127 bits per weight.
Here is the weight memory for a 7B-parameter model:
| Storage | Bits per weight | Approximate weight memory |
|---|---|---|
| float32 | 32 | 28 GB |
| bfloat16 | 16 | 14 GB |
| int8 | 8 | 7 GB |
| 4-bit with double quantization | about 4.13 | about 3.6 GB |
These numbers cover the base weights only. Training also needs memory for activations, the LoRA parameters and their gradients, optimizer states, and the CUDA context. Quantization does not shrink activations, so long sequences and large batches can still run out of memory. Gradient checkpointing and smaller batch sizes address that part.
NF4: a 4-bit format shaped for weights
Plain 4-bit integers space their 16 levels evenly. Pretrained weights are not evenly distributed. They cluster near zero and look roughly like a normal distribution. Evenly spaced levels waste resolution in the sparse tails.
NormalFloat 4 (NF4) places its 16 levels at quantiles of a standard normal distribution instead. Each level then covers about the same share of the weights. Each block is first scaled by its absmax to the range [-1, 1], and each value is mapped to the nearest NF4 level. In the QLoRA paper, NF4 gave better results than plain int4 and FP4 at the same size. The format only works well if weights really are close to normal, which holds well enough for most transformer layers.
Quantization at training time
Storing the base weights in 4 bits does not mean computing in 4 bits. The flow for each linear layer is:
Three points follow from this flow.
- The quantized weight is dequantized on the fly, usually one layer at a time, into the compute dtype. That dtype is chosen separately and is commonly bfloat16.
- The base weights receive no gradient and no optimizer state. Gradients still flow through the dequantized values back to earlier adapters, so the backward pass uses the base weights too.
- Dequantizing adds work to every forward and backward pass. Training a quantized model is therefore usually somewhat slower than training the same model in 16-bit, even though it uses less memory.
Gotchas
- Quantization is lossy and permanent for that copy. The rounding error stays in the stored weights. If you later merge a LoRA adapter into a quantized base, you merge into the rounded values. For a clean merged model, merge into a 16-bit copy of the base instead. The chapter on merging covers this.
- Hardware support. The bitsandbytes library, which implements 8-bit and 4-bit loading in transformers, expects a CUDA GPU in the standard setup. On a CPU-only machine or some other backends, the loading code in this tutorial will fail or fall back to different tooling.
- Quality loss differs by task. Small models and tasks that need precise reasoning or exact numbers can lose more accuracy from 4-bit rounding than chat-style tasks do. Always compare against a 16-bit baseline on your own held-out data.
- Wrong compute dtype. If the compute dtype is float16 and activations overflow, you get NaN losses. bfloat16 avoids this on GPUs that support it. If the compute dtype is left at float32, training still works, but it is slower and uses more memory than necessary.
- Do not confuse the two precisions. "4-bit model" describes how the frozen weights are stored. The adapter weights, gradients, and optimizer states are still in 16-bit or 32-bit.
- Prequantized checkpoints. Some Hub models are already quantized, for example in GPTQ or AWQ formats. These are mainly for inference, and training a LoRA adapter on them needs format-specific support. Start from the original 16-bit checkpoint when you want the standard path.
What comes next
You now have the pieces QLoRA combines: blockwise absmax scaling, the NF4 level layout, double quantization of scales, and on-the-fly dequantization into a higher-precision compute dtype. The next chapter turns them into a working configuration with bitsandbytes and PEFT.
Exercise
A tensor of 4096 weights contains one value of 5.0, and all other weights have magnitude below 0.1. You quantize it to 4 bits (qmax = 7) with one absmax scale for the whole tensor. What is the step size, and why do most other weights become zero? How does using blocks of 64 change this?
Show answer
The scale is 5.0 / 7, about 0.71, so each integer level represents a step of about 0.71. Any weight with magnitude below half a step, about 0.36, rounds to zero. All weights below 0.1 therefore become zero. With blocks of 64, only the block containing the outlier has this large scale. The other 63 blocks compute their scale from their own maximum, which is below 0.1, so their step sizes are below about 0.014. Those weights keep useful resolution.
Exercise
A 13B-parameter model is stored with 4-bit blockwise quantization, block size 64, and a 32-bit float scale per block, with no double quantization. Roughly how many gigabytes do the weights take? Why will the training run still need more GPU memory than that figure?
Show answer
Bits per weight are 4 + 32/64 = 4.5. Total bits are 13e9 × 4.5 = 58.5e9, which is about 7.3 GB. Training also needs memory for activations (which grow with batch size and sequence length), the LoRA adapter weights, their gradients and optimizer states, the dequantized layer being used at each step, and CUDA overhead. Quantization does not reduce any of these except the base weight storage.