🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Quantization: 4-bit, 8-bit and FP16 Trade-Offs

đŸŸĸ Free Lesson

Quantization: 4-bit, 8-bit and FP16 Trade-Offs

Quantization ComparisonFP3232-bit floatSize: 100%Speed: 1xQuality: BestTraining/ReferenceFP1616-bit floatSize: 50%Speed: 2xQuality: ExcellentStandard trainingINT88-bit integerSize: 25%Speed: 3-4xQuality: GoodProduction inferenceINT44-bit integerSize: 12.5%Speed: 4-6xQuality: AcceptableEdge deployment

Why a 7B model does not need 14 GB of memory

The first time you try to serve a 7-billion-parameter model on a single consumer card you hit a wall that has nothing to do with speed: the weights alone do not fit. At 16-bit precision the checkpoint is about 14 GB, and that is before you allocate KV cache for the context window, activations for the forward pass, and any CUDA workspace the kernels want. Quantization attacks the largest term in that sum directly, by storing each weight in fewer bits.

A 32-bit float spends its 32 bits on a sign, an exponent, and 23 bits of mantissa, giving a huge dynamic range that neural weights do not use. Weights in a trained transformer typically live in a narrow band around zero with a short tail of outliers. Squeeze that distribution into 8 bits or 4 bits and most values survive with small error; the outliers are what force clever schemes. The payoff is roughly linear: half the bits, half the memory, and — because memory bandwidth, not arithmetic, dominates autoregressive decoding — close to a proportional speed-up in tokens per second.

How a weight gets squeezed into fewer bits

Quantization is a rounding scheme with a scale factor. You pick a range you are willing to represent, map it onto a grid of 256 levels for 8-bit or 16 levels for 4-bit, and keep the scale so you can invert the mapping. Symmetric quantization centres the grid on zero and uses one scale; asymmetric quantization adds a zero point so that ranges not centred on zero waste fewer levels.

python
import torch

def quantize_symmetric(weight: torch.Tensor, bits: int = 8):
    qmax = 2 ** (bits - 1) - 1            # 127 for int8, 7 for int4
    scale = weight.abs().max() / qmax
    q = torch.clamp(torch.round(weight / scale), -qmax - 1, qmax)
    return q.to(torch.int8), scale

def dequantize(q: torch.Tensor, scale: float) -> torch.Tensor:
    return q.float() * scale

w = torch.randn(4096, 4096) * 0.02
for bits in (8, 4):
    q, s = quantize_symmetric(w, bits)
    err = (dequantize(q, s) - w).abs().mean()
    print(f"{bits}-bit mean absolute error: {err.item():.6f}")

Run that and the error grows roughly six-fold from 8-bit to 4-bit. Small per-weight error is tolerable because the forward pass averages millions of them; what hurts is when a handful of outlier channels absorb the entire error budget, which is exactly why the better 4-bit methods special-case outliers instead of treating every weight equally.

Post-training quantization versus QAT

There are two families of technique, and choosing between them is mostly a question of whether you can afford a training run.

PropertyPost-training (PTQ)Quantization-aware (QAT)
Extra data neededSmall calibration setFull training corpus
Extra computeMinutes to hoursroughly one extra epoch
Typical accuracy loss0–2 percentunder 0.5 percent
Works on released checkpointsYesNo, you need training access
Best fit8-bit, most 4-bit use4-bit with tight tolerances, small models

Most production teams use PTQ almost exclusively, because modern 4-bit formats such as NF4 were designed around the statistics of pretrained weights and lose very little without any retraining. QAT earns its cost in two situations: aggressive 4-bit or 2-bit targets on small models where there is no redundancy to absorb the error, and integer-only hardware such as mobile NPUs that cannot execute floating-point arithmetic at all.

Loading a 4-bit model in practice

For LLMs the bitsandbytes library has become the default path, and the Hugging Face integration is three lines of configuration.

python
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

nf4 = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",          # normal-float 4, matched to weight statistics
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,     # quantize the quantization constants too
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization_config=nf4,
    device_map="auto",
)

# Computation still happens in bfloat16; only storage is 4-bit.
model.generate(**tokenizer("Summarise the plot of Hamlet.", return_tensors="pt").to("cuda"),
               max_new_tokens=80)

The detail worth internalising is that storage precision and compute precision are separate knobs. NF4 stores weights in 4 bits but performs the matrix multiply in bfloat16, decompressing on the fly. That is why the speed-up comes from reading less memory rather than from doing cheaper arithmetic.

Picking a format for the hardware you actually own

Formats are not interchangeable; each one is optimised for a different machine.

FormatBitsTypical quality lossWhere it shines
FP16 / BF1616NoneTraining, reference inference
INT8 (dynamic)8NegligibleServer GPUs, batch inference
NF4 (bitsandbytes)4SmallSingle-GPU fine-tuning and serving
GPTQ4SmallFast GPU inference, pre-quantized repos
AWQ4Very smallThroughput-sensitive GPU serving
GGUF Q4_K_M4SmallCPU and laptop inference via llama.cpp
INT4 / W4A164ModerateMobile and edge NPU deployment

A useful rule of thumb: stay at 8-bit when accuracy is the product, drop to 4-bit when memory is the constraint, and only go below 4 bits when the alternative is not running the model at all.

Measuring what you actually lost

A quantized model that "still works" on a handful of prompts is not evidence of anything. Measure perplexity and task accuracy against the floating-point baseline before you ship, then measure latency again, because quantization sometimes speeds up prefill while leaving decode unchanged.

python
import time, math, torch

def evaluate(model, tokenizer, texts, max_len=512):
    model.eval()
    losses = []
    with torch.no_grad():
        for text in texts:
            ids = tokenizer(text, return_tensors="pt",
                            truncation=True, max_length=max_len).input_ids.to(model.device)
            losses.append(model(ids, labels=ids).loss.item())
    ppl = math.exp(sum(losses) / len(losses))

    ids = tokenizer("The history of container shipping", return_tensors="pt").input_ids.to(model.device)
    torch.cuda.synchronize()
    start = time.perf_counter()
    for _ in range(20):
        model.generate(ids, max_new_tokens=64, do_sample=False)
    torch.cuda.synchronize()
    return ppl, (time.perf_counter() - start) / 20

for name, m in [("fp16", baseline), ("nf4", quantized)]:
    perplexity, latency = evaluate(m, tokenizer, held_out_texts)
    print(f"{name}: perplexity={perplexity:.2f} latency={latency:.2f}s")

Compare perplexity deltas rather than absolute numbers. A rise of a few percent in perplexity on general text is usually invisible to users, while a jump on your domain corpus is a red flag that the calibration data never covered it.

The dimensions that do not appear in the model card

Bit-width gets all the attention, yet two other choices often decide whether a deployment succeeds. The first is granularity: per-channel scales quantize each output channel of a weight matrix separately, which handles layers with wildly different magnitudes far better than one global scale per tensor. Per-tensor quantization is cheaper to store and noticeably worse on the first and last layers of a network, which is why many pipelines keep those two layers at higher precision and quantize everything between them.

The second is what happens outside the weights. KV cache precision sets how much memory context consumes, and at long windows it dominates the footprint — a model with 4-bit weights and a 16-bit cache can spend more on attention history than on the model itself. Activation precision matters separately again: storing weights in 4 bits while computing in 8 bits behaves very differently from computing in 4 bits, and only the latter unlocks integer-only accelerators.

KnobCheap settingSafe settingWho notices
Weight granularityper tensorper channelQuality on odd layers
KV cache16-bit8-bit with quantized writeLong-context capacity
Compute dtype8-bit16-bitNumerical stability
First and last layerquantizedkept at 16-bitOutput quality

Treat these as a configuration surface you benchmark together. Changing one in isolation rarely tells you anything, because the interaction between them is where the regressions hide.

Where aggressive quantization goes wrong

The failures are consistent enough to predict. Outlier channels — a small number of activation dimensions with far larger magnitude than the rest — carry disproportionate influence, and naive rounding starves them; AWQ exists specifically to protect them. Perplexity can look fine while long-form reasoning degrades, because a single wrong token early in a chain collapses the answer, so run reasoning benchmarks too, not just loss. Small models degrade faster than large ones: a 3B model quantized to 4 bits loses proportionally more than a 70B model, since the larger model has redundancy to absorb the noise. And context length interacts with quantization, because KV cache precision is a separate decision from weight precision and often the one that limits your window.

Common Mistakes

Shipping a 4-bit model after checking three prompts by eye

Fix: Compare perplexity and task accuracy against the FP16 baseline on held-out data before any release.

Assuming lower bits always mean faster generation

Fix: Benchmark tokens per second on your own hardware; dequantization overhead can cancel the bandwidth win on some kernels.

Quantizing a 3B model to 4 bits because it worked on a 70B model

Fix: Scale the bit-width to model size; small models need 8-bit to stay reliable.

Ignoring KV cache precision

Fix: Set cache dtype explicitly; an FP32 cache can quietly use more memory than the quantized weights saved.

Best Practices

  • Calibrate PTQ on a few hundred samples from the deployment distribution, not on generic text.
  • Keep one FP16 copy of every model as the evaluation reference and roll-back target.
  • Prefer NF4 with double quantization for training, and GPTQ or AWQ for high-throughput serving.
  • Re-run the full evaluation suite whenever you change quantization format, not only when you change weights.

Key Takeaways

  • Quantization stores weights in fewer bits, and because decoding is memory-bandwidth bound, smaller weights usually mean faster generation too.
  • PTQ needs only a calibration set and covers most use cases; QAT costs a training run and buys accuracy at very low bit-widths.
  • Storage precision and compute precision are independent: NF4 stores in 4 bits while computing in bfloat16.
  • Format choice follows hardware — bitsandbytes and GPTQ for GPUs, GGUF for CPUs, integer formats for edge accelerators.
  • Always benchmark perplexity and task accuracy against the floating-point baseline; eyeballing outputs misses silent degradation.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement