Quantization of AI Models: How 8-Bit and 4-Bit Weights Make LLMs Smaller and Faster

Close-up of computer processor chips, illustrating hardware behind AI model quantization

Quantization makes an AI model smaller and faster by storing its weights (and sometimes its activations) with fewer bits, for example as 8-bit or 4-bit integers instead of 16-bit floating-point numbers. Halving the bits roughly halves the memory needed to hold the weights, and because large language models are usually limited by how fast weights move through memory, generation usually gets faster too. The cost is a small rounding error on every weight, which is usually negligible at 8 bits and becomes noticeable at 4 bits and below, depending on the model, the method and the task.

Photo: computer processor chips by Edward Wilders, licensed CC BY-SA 4.0, via Wikimedia Commons.

This guide works through the arithmetic with real numbers, compares the main methods (bitsandbytes, GPTQ, AWQ and GGUF), and ends with a procedure for choosing a precision and checking that the quantized model still does your job.

How quantization works, with a worked example

Quantization maps a range of real numbers onto a small set of integer levels using a scale factor. An 8-bit signed integer has 256 levels (−128 to 127); a 4-bit one has only 16 (−8 to 7). The simplest scheme, called absmax (absolute maximum) scaling, finds the largest absolute value in a group of weights and stretches the group so that value lands on the edge of the integer range.

Take four illustrative weights: 0.413, −1.27, 0.087 and 0.951.

  1. Find the scale. The largest absolute value is 1.27. For INT8 we want it to map to 127, so the scale is 127 / 1.27 = 100.
  2. Quantize. Multiply each weight by 100 and round: 41, −127, 9, 95. These four small integers are what gets stored, plus one scale value for the group.
  3. Dequantize when computing. Divide by the scale: 0.41, −1.27, 0.09, 0.95. The largest error is 0.003.

Now the same four weights at INT4, where the maximum level is 7. The scale becomes 7 / 1.27 ≈ 5.51, the stored integers are 2, −7, 0 and 5, and the reconstructed values are 0.363, −1.27, 0.0 and 0.907. The weight 0.087 has been rounded to zero, and the largest error is now 0.087, almost thirty times larger than at INT8.

One more variation shows the real enemy, which is outliers. Replace −1.27 with −12.7 and quantize to INT8 again. The scale drops to 10, so 0.413 becomes 4 (0.40), 0.087 becomes 1 (0.10) and 0.951 becomes 10 (1.00). One large value has made every small value in its group less precise. That is why modern methods quantize in small groups or blocks, each with its own scale, and why several of them treat outliers specially.

Affine (or zero-point) quantization adds an offset so that ranges not centered on zero, such as activations after a ReLU, use all available levels instead of wasting half of them.

What FP32, BF16, FP8, INT8 and INT4 mean in practice

Each format label states how many bits store one number, and memory for the weights scales directly with it. A quick estimate is parameters × bits ÷ 8 = bytes.

FormatBits per weightWeights for an 8B model (approx.)Typical use
FP323232 GBTraining master weights; rarely used for LLM serving
BF16 / FP161616 GBDefault release precision for most open-weight LLMs
FP8 / INT888 GBProduction serving on recent GPUs; usually close to 16-bit quality
INT4 / 4-bit formats4 (plus scale overhead)4-5 GBLaptops, single consumer GPUs, phones
2-3 bit formats2-32-3 GBExtreme memory limits; quality loss becomes significant

The “plus overhead” matters. The llama.cpp quantize documentation lists Llama-3.1-8B at 4.89 bits per weight and 4.58 GiB for its popular Q4_K_M format, against 16.0 bits and 14.96 GiB for F16, because each block stores scale values alongside the weights. The same table shows text generation speed rising from about 29 to about 72 tokens per second when going from F16 to Q4_K_M, which illustrates the memory-bandwidth effect. The document does not state the hardware used, so treat those speeds as relative, not as numbers to expect on your machine.

Remember that weights are not the only memory cost. The KV cache, which stores attention state for every token in the conversation, grows with context length and with the number of concurrent requests. A model that loads comfortably can still run out of memory on long inputs. The link between context length and memory is covered in context windows.

The main methods compared

Quantization methods differ mainly in whether they need calibration data and in how they protect the weights that matter most. Post-training quantization (PTQ) compresses a finished model without retraining it; quantization-aware training (QAT) simulates low precision during training so the model learns to tolerate it. Most methods you will meet as a practitioner are PTQ.

MethodCalibration data?Common bit widthsKey ideaWhere you meet it
LLM.int8() / bitsandbytesNo, quantizes at load time8 and 4 (NF4)Keeps rare outlier dimensions in 16-bit, the rest in 8-bitHugging Face Transformers, QLoRA fine-tuning
GPTQYes2, 3, 4, 8One-shot quantization using approximate second-order information to compensate errorsPre-quantized GPU checkpoints
AWQYes (activation statistics)4Protects the small share of weights that see large activations by rescaling themPre-quantized checkpoints, edge GPUs
GGUF k-quants and i-quantsOptional importance matrixAbout 2 to 8Block-wise formats for the llama.cpp ecosystemllama.cpp, Ollama, LM Studio, CPU and Apple Silicon

LLM.int8() and bitsandbytes

The LLM.int8() paper showed that large transformers develop systematic outlier features that dominate performance, exactly the problem from the worked example above. Its fix is to multiply those few outlier dimensions in 16-bit and everything else in 8-bit; the abstract reports that more than 99.9% of values still go through 8-bit math while inference memory is halved. The bitsandbytes library implements this and also provides 4-bit loading, which QLoRA later built on with the NF4 data type and “double quantization” of the scale constants themselves.

GPTQ

GPTQ quantizes a model layer by layer and adjusts the remaining weights to compensate for each rounding error, using a small calibration dataset. The authors report quantizing a 175B-parameter model to 3 or 4 bits in about four GPU hours with little accuracy loss. Because the work happens once, you normally download a GPTQ checkpoint someone already produced rather than running it yourself.

AWQ

Activation-aware Weight Quantization starts from the observation that weights are not equally important. The AWQ paper argues that protecting about 1% of salient weights, identified by looking at activation magnitudes rather than weight values, greatly reduces error. Instead of keeping those weights in higher precision, it scales them so they survive rounding, and it needs no backpropagation.

GGUF formats

GGUF is the file format of llama.cpp and the tools built on it. Names such as Q4_K_M, Q5_K_M, Q8_0 or IQ3_M describe the bit width and block scheme. The llama.cpp docs note that an importance matrix (imatrix), computed from sample text, can reduce the accuracy loss of a quantization, and that multimodal projector files should be kept at high precision because shrinking them saves little and hurts output quality. A conversion looks like this:

./build/bin/llama-quantize model-bf16.gguf model-Q4_K_M.gguf Q4_K_M

The Hugging Face quantization overview lists around two dozen supported methods and notes that calibration-based methods are the ones that make extreme 1-2 bit compression usable. It also points to a quantization picker that checks whether a model fits your hardware at each precision, including the KV cache.

Loading a 4-bit model in Transformers

The quickest way to try quantization in Python is on-the-fly loading with bitsandbytes, which needs no pre-quantized checkpoint. The configuration below combines the options documented separately on the Transformers bitsandbytes page; replace the model ID with the one you want.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

model_id = "your-org/your-model"   # placeholder

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",               # NormalFloat4, from QLoRA
    bnb_4bit_compute_dtype=torch.bfloat16,   # math runs in bf16
    bnb_4bit_use_double_quant=True,          # also quantizes the scale constants
)

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    quantization_config=bnb_config,
)

print(model.get_memory_footprint() / 1e9, "GB")

Why each line matters: nf4 uses a 4-bit grid shaped for normally distributed weights rather than evenly spaced levels; the compute dtype controls the precision of the actual matrix math after weights are dequantized; double quantization saves roughly another 0.4 bits per parameter according to the Transformers docs; and get_memory_footprint() lets you confirm the savings instead of assuming them.

Choosing a precision: a step-by-step procedure

The right precision is the lowest one that still passes your own evaluation, on the hardware you actually have. Published perplexity or benchmark numbers are a starting point, not a verdict.

  1. Write down the memory budget. Available VRAM or RAM, minus room for the KV cache at your real context length and concurrency.
  2. Compute the largest precision that fits. Use parameters × bits ÷ 8, then add 10-20% for scales and runtime overhead. If 8-bit fits, start there.
  3. Build a small task-specific test set. Fifty to a few hundred real inputs with known good outputs, covering edge cases. The method for this is in how to evaluate AI models.
  4. Run the full-precision model first to get a baseline score, if you can access it anywhere, even on rented hardware.
  5. Run each candidate quantization on the same set with the same prompts and sampling settings (use temperature 0 or a fixed seed).
  6. Compare per category, not just overall. Quantization damage tends to show up first in arithmetic, exact string reproduction, long-chain reasoning, code and less common languages.
  7. Pick the smallest format whose drop you can accept, then measure real latency and throughput on the target machine.

Likely problems and how to fix them

  • Output becomes repetitive or garbled at 2-3 bits. Move up one level (for GGUF, from Q3 to Q4_K_M or Q5_K_M), or use an imatrix-based quant.
  • JSON or code breaks more often than before. Exact-format tasks are sensitive to small probability shifts. Try 8-bit, or add schema validation with a retry.
  • Out-of-memory errors only on long prompts. The weights fit; the KV cache does not. Reduce the context length or concurrency, or use a runtime that supports KV cache quantization.
  • Quantized model is slower than expected. Some formats need specific kernels; on unsupported hardware the runtime may dequantize on the fly. Check that your GPU and library combination is supported for that method.
  • A vision model’s image understanding degrades. Keep the vision encoder or projector at higher precision and quantize only the language model.

Quantization alongside other compression techniques

Quantization reduces precision; other techniques reduce the number of parameters or the work per token, and they stack. Knowledge distillation trains a smaller student model to imitate a larger teacher, pruning removes weights that contribute little, and a mixture-of-experts architecture activates only part of the network per token. MoE models still need all their experts in memory, which is why they are often quantized aggressively to fit on a single machine.

The common production pattern is to choose or distill the right-sized model first, fine-tune it if needed, and quantize last for deployment. That is how many small language models end up running on laptops and phones.

FAQ

Can I fine-tune a quantized model?

Yes, with adapters. The QLoRA paper (listed in the sources below) freezes the base model in 4-bit and trains small LoRA adapters on top, and the authors report fine-tuning a 65B model on a single 48 GB GPU this way. You do not update the quantized weights themselves.

Does a hosted API model use quantization?

Providers of closed models generally do not publish their serving precision, so you cannot assume either way. With open-weight models you choose the precision yourself, which is one reason to evaluate the exact build you deploy.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top