Sub topic 9
Quantization: trading precision for memory
Quantization stores a model's weights with fewer bits each. This chapter covers how it works, what it does to memory, speed, and quality, and when to use it. It assumes you know what a parameter is and have read the earlier chapters on model sizes and on estimating memory. You should be able to read short Python.
What quantization does
A model's weights are numbers. Training usually produces them in 16-bit floating point (FP16 or BF16). Quantization maps each weight to a lower-precision value, typically 8-bit or 4-bit integers, plus a small amount of extra data that lets you map the integers back to approximate real values.
The saving is direct. Weight memory is parameter count times bits per weight, divided by 8. A 7-billion-parameter model needs 14 GB at 16-bit, 7 GB at 8-bit, and 3.5 GB at 4-bit. That can decide whether a model fits on a laptop, one consumer GPU, or a cheaper server.
The cost is rounding error. The quantized model is a slightly different model from the original, and you have to check whether the difference matters for your task.
How the rounding works
The simplest scheme is symmetric absmax quantization. You find the largest absolute weight in a group, divide it by the largest integer the format allows, and use the result as a scale. Each weight becomes the nearest integer multiple of that scale.
def quantize_group(weights, bits=4):
qmax = 2 ** (bits - 1) - 1 # 7 for 4-bit signed
scale = max(abs(w) for w in weights) / qmax
q = [max(-qmax - 1, min(qmax, round(w / scale))) for w in weights]
return q, scale
def dequantize_group(q, scale):
return [v * scale for v in q]
weights = [0.12, -0.50, 0.33, 0.05, -0.27, 0.90, -0.04, 0.61]
q, scale = quantize_group(weights, bits=4)
restored = dequantize_group(q, scale)
print("integers:", q)
errors = [abs(a - b) for a, b in zip(weights, restored)]
print(f"max error: {max(errors):.3f}") # about 0.056
# One outlier stretches the scale and flattens everything else.
with_outlier = weights[:5] + [9.0] + weights[6:]
q2, scale2 = quantize_group(with_outlier, bits=4)
print("with outlier:", q2)In the first run the integers are [1, -4, 3, 0, -2, 7, 0, 5] and the largest error is about 0.056. In the second run the 9.0 outlier makes the scale ten times larger, so most small weights round to 0 and their information is lost.
Real systems handle outliers in two ways:
- Small groups. Each group of 32 to 128 weights gets its own scale, so an outlier damages only its own group. The cost is that every group stores a scale, and some formats also store a zero point.
- Protecting important weights. Methods such as AWQ and GPTQ use sample data to decide which weights matter most and adjust the rounding to reduce the error in the model's outputs.
Effective bits per weight
A "4-bit" model is rarely exactly 4 bits per weight. Scales, zero points, and layers kept at higher precision add to the total. Many 4-bit formats come out at 4.5 to 5 bits per weight in practice. Use the file size on disk as your best guide, because it already includes this overhead.
| Precision | Nominal bits | Typical use | Quality risk |
|---|---|---|---|
| FP16 / BF16 | 16 | Reference quality, training, large GPUs | None (baseline) |
| 8-bit (INT8, FP8) | 8 | Servers where memory is tight | Usually small |
| 4-bit (Q4, AWQ, GPTQ, NF4) | about 4.5 to 5 effective | Laptops, single consumer GPUs | Small to moderate, task dependent |
| 3-bit and below | 2 to 3.5 effective | Extreme memory limits | Often noticeable |
Common formats and tools you will meet:
- GGUF is the file format used by llama.cpp and tools built on it, such as Ollama. It offers many variants, named like Q80, Q5KM, and Q4K_M.
- GPTQ and AWQ are 4-bit methods usually run on GPUs in servers such as vLLM.
- bitsandbytes can quantize a model to 8-bit or 4-bit as it loads, which is convenient for experiments.
What quantization does not shrink
Weight quantization reduces the weights. It does not automatically reduce the KV cache, which holds the attention keys and values for every token in the context. The cache grows with context length and with the number of concurrent requests. Activations and the runtime itself also need memory.
def kv_cache_gb(layers, kv_heads, head_dim, context_tokens, bytes_per_value=2):
"""Keys and values (the factor 2) for every layer and token, in GB."""
return 2 * layers * kv_heads * head_dim * context_tokens * bytes_per_value / 1e9
def total_memory_gb(params_billion, bits_per_weight, layers, kv_heads,
head_dim, context_tokens, overhead_gb=1.0):
weights = params_billion * bits_per_weight / 8
cache = kv_cache_gb(layers, kv_heads, head_dim, context_tokens)
return weights + cache + overhead_gb
# A 7B model with 32 layers, 32 KV heads, head size 128, 4096-token context
for label, bits in (("16-bit", 16), ("4-bit (about 4.8 effective)", 4.8)):
total = total_memory_gb(7, bits, 32, 32, 128, 4096)
print(f"{label}: {total:.2f} GB")
# 16-bit: 17.15 GB
# 4-bit (about 4.8 effective): 7.35 GBHere the KV cache is about 2.15 GB. At 4-bit it is a large share of the total, and at a 32,000-token context it would be eight times larger. Models that use grouped-query attention have fewer KV heads, which makes the cache much smaller. Check the model's configuration for its real values. Some servers can also store the cache in 8-bit, which is a separate setting from weight quantization.
Effects on speed
Generating one token at a time is usually limited by how fast the hardware can read the weights from memory, not by arithmetic. Smaller weights mean fewer bytes to read per token, so a 4-bit model often generates tokens faster than the 16-bit version on the same hardware.
Two caveats apply:
- Hardware needs kernels (optimized low-level code) that handle the format. Without them, the runtime converts weights back to 16-bit before use, and you save memory but gain little speed.
- Under heavy batching, the work becomes limited by arithmetic, so the speed benefit shrinks. Memory savings still apply.
Effects on quality
Quality loss depends on the model, the method, and the task. As a rough guide:
- 8-bit is usually hard to tell apart from 16-bit.
- 4-bit with a good method often costs little on general tasks.
- Smaller models tend to lose more from quantization than larger ones. A common practical result is that a larger model at 4-bit beats a smaller model at 16-bit with the same memory budget, but you should verify this for your task.
- Tasks needing exact output show damage first. Examples are strict JSON, code, arithmetic, and long chains of reasoning. Open-ended summaries often hold up better.
Published benchmark numbers for a quantized model are averages over many tasks. Run your own cases, as described in the evaluation chapter. Use the same cases for the 16-bit and quantized versions of the model.
def pass_rate(ask_fn, cases):
passed = sum(1 for c in cases if c["expected"] in ask_fn(c["prompt"]))
return passed / len(cases)
# ask_fp16 and ask_q4 call the same model at two precisions
# print(pass_rate(ask_fp16, cases), pass_rate(ask_q4, cases))Common errors
- Counting only the weights. A model whose 4-bit weights are 4.2 GB can still fail to load on an 8 GB GPU once the KV cache and runtime overhead are added.
- Treating "4-bit" as exactly 4 bits. Use the real file size.
- Comparing the wrong things. Two quantized files labeled 4-bit can differ in quality because of the method, the group size, or the calibration data.
- Assuming a speed-up. Confirm that your runtime has fast kernels for the format on your hardware.
- Quantizing twice. Starting from an already quantized model and quantizing again compounds the error. Start from the original weights.
- Skipping the license check. A quantized copy of a model is still covered by the original license. Redistributing it may have conditions.
Where it fits in the decision
Record the exact model file, quantization method, and runtime version you tested. Changing any of them can change results, so treat each as a new candidate.
Exercise
You want to run a 70-billion-parameter model on a single 24 GB GPU. Estimate the weight memory at 16-bit and at 4-bit with about 4.8 effective bits per weight. Does it fit? What would you try next?
Show answer
At 16-bit, the weights need 70 × 16 / 8 = 140 GB. At 4.8 effective bits they need 70 × 4.8 / 8 = 42 GB. Even at a nominal 4 bits it is 35 GB. None of these fits in 24 GB, and the KV cache and overhead would add more. Options are to use a smaller model such as a 30B-class model at 4-bit (about 18 GB of weights, which leaves little room for the cache), use several GPUs or a larger one, offload some layers to CPU memory at a large speed cost, or use a hosted API. Whichever you choose, check it on your own evaluation cases.
Exercise
A 4-bit file for a 13B model is 7.9 GB. What is its effective bits per weight, and why is it above 4?
Show answer
Effective bits per weight = 7.9 × 8 / 13 ≈ 4.86. It is above 4 because each group of weights stores a scale (and sometimes a zero point), and some layers are kept at higher precision.