Quantization and Running Models Locally

Updated · 10 min read
hardPython 3.13aiquantizationlocal-modelsint84-bitllm

Quantization stores a model's weights with fewer bits: instead of a 32-bit or 16-bit floating-point number for every weight, it keeps a small whole number, such as 8 bits or 4 bits, plus a scale to turn it back into an approximate weight. The model becomes two to eight times smaller, uses less memory and often runs faster, which is what makes it possible to run large language models on laptops and phones. The cost is a little lost accuracy, which grows quickly when too few bits are used.

Number Formats

FormatDescription
32-bit float (FP32)It is used for training and as the reference; 4 bytes per weight
16-bit float (FP16, BF16)The usual format for storing and running models today; 2 bytes per weight
8-bit integer (INT8)It is used to halve memory again with almost no loss; 1 byte per weight
4-bitIt is used to run models locally; half a byte per weight, with a scale for each small group of weights
Below 4 bitsPossible with special methods, but quality falls fast

Example: Quantizing by Hand

This program quantizes a small piece of a weight matrix to 8, 4 and 2 bits, then turns it back into floats, the way the model uses it.

Python
import numpy as np
 
rng = np.random.default_rng(0)
weights = rng.normal(0, 0.05, size=(4, 6)).astype(np.float32)   # a small piece of a weight matrix
 
def quantize(w, bits):
    """Symmetric quantization, one scale per row: floats -> small whole numbers -> floats."""
    levels = 2 ** (bits - 1) - 1                      # 127 for 8 bits, 7 for 4 bits
    scale = np.abs(w).max(axis=1, keepdims=True) / levels
    q = np.round(w / scale).astype(np.int8)            # what is stored: whole numbers
    return q, q * scale                                # and what the model computes with
 
np.set_printoptions(precision=4, suppress=True)
print("Original first row:", weights[0])
for bits in [8, 4, 2]:
    q, back = quantize(weights, bits)
    error = np.abs(weights - back).mean()
    print(f"\n{bits}-bit stored numbers, first row: {q[0]}")
    print(f"{bits}-bit back to floats:            {back[0]}")
    print(f"average error {error:.5f} ({error / np.abs(weights).mean():.1%} of the average weight)")
Output
Original first row: [ 0.0063 -0.0066  0.032   0.0052 -0.0268  0.0181]
 
8-bit stored numbers, first row: [  25  -26  127   21 -106   72]
8-bit back to floats:            [ 0.0063 -0.0066  0.032   0.0053 -0.0267  0.0182]
average error 0.00008 (0.2% of the average weight)
 
4-bit stored numbers, first row: [ 1 -1  7  1 -6  4]
4-bit back to floats:            [ 0.0046 -0.0046  0.032   0.0046 -0.0274  0.0183]
average error 0.00204 (6.1% of the average weight)
 
2-bit stored numbers, first row: [ 0  0  1  0 -1  1]
2-bit back to floats:            [ 0.     0.     0.032  0.    -0.032  0.032]
average error 0.01495 (44.5% of the average weight)

Explanation:

  • scale is the largest weight in each row divided by the largest whole number allowed: 127 for 8 bits, 7 for 4 bits, 1 for 2 bits. Each weight is divided by the scale and rounded to a whole number. Only those whole numbers and one scale per row are stored.
  • 8 bits keeps the weights almost exactly: an average error of 0.2% of a typical weight.
  • 4 bits is rougher (6.1%): the first row's small weights 0.0063, -0.0066 and 0.0052 all round to the same size, ±0.0046.
  • 2 bits leaves only -1, 0 and 1: most small weights become exactly 0, an error of 44.5%.

Example: Quantizing a Real Model

This program applies the same idea to every weight matrix in the 30 blocks of SmolLM2-135M-Instruct and measures the effect on perplexity (from "Pretraining"; lower is better) and on a short answer. One row uses a separate scale for each group of 32 weights, as real 4-bit formats do.

Fewer bits, smaller model, until the rounding breaks it

The programs in this chapter need pip install fastapi httpx sentence-transformers scikit-learn torch transformers. Several use faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.

Python
import math
 
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
 
name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(name)
text = ("The school library opens at eight in the morning. Students can borrow up to five books "
        "for two weeks, and late returns are charged ten cents a day.")
ids = tokenizer(text, return_tensors="pt").input_ids
 
def load(bits=None, group=None):
    model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32).eval()
    if bits:
        levels = 2 ** (bits - 1) - 1
        with torch.no_grad():
            for layer in model.model.layers.modules():    # every Linear layer in the 30 blocks
                if isinstance(layer, torch.nn.Linear):
                    w = layer.weight
                    rows = w.reshape(-1, group) if group else w   # one scale per row, or per group of weights
                    scale = rows.abs().amax(dim=1, keepdim=True) / levels
                    w.copy_((torch.round(rows / scale) * scale).reshape(w.shape))   # keep only `bits` bits
    return model
 
def perplexity(model):
    with torch.no_grad():
        return math.exp(model(ids, labels=ids).loss.item())
 
def answer(model):
    chat = tokenizer.apply_chat_template([{"role": "user", "content": "What is a library?"}],
                                         add_generation_prompt=True, return_tensors="pt", return_dict=True)["input_ids"]
    out = model.generate(chat, max_new_tokens=20, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    return tokenizer.decode(out[0, chat.shape[1]:], skip_special_tokens=True).strip()
 
model = load()
block_params = sum(m.weight.numel() for m in model.model.layers.modules() if isinstance(m, torch.nn.Linear))
other = sum(p.numel() for p in model.parameters()) - block_params
for bits, group in [(None, None), (8, None), (4, None), (4, 32), (3, None), (2, None)]:
    model = load(bits, group)
    stored = (bits or 32) + (16 / group if group else 0)              # a 16-bit scale for every group
    megabytes = (block_params * stored / 8 + other * 4) / 1e6         # embeddings stay 32-bit here
    label = "32-bit (original)" if bits is None else f"{bits}-bit" + (f", groups of {group}" if group else "")
    print(f"{label:20} {megabytes:4.0f} MB  perplexity {perplexity(model):11,.2f}  {answer(model)[:48]!r}")
Output
32-bit (original)     538 MB  perplexity       39.70  'A library is a collection of books, electronic r'
8-bit                 220 MB  perplexity       41.14  'A library is a collection of books, electronic r'
4-bit                 166 MB  perplexity       69.16  "A library is a wonderful place to live. It's lik"
4-bit, groups of 32   173 MB  perplexity       42.65  'A library is a collection of books, articles, an'
3-bit                 153 MB  perplexity   26,645.57  '. ( PC "\n.\xa0.\n.. ".hesis " 2.'
2-bit                 140 MB  perplexity 87,735,475.35  'ivesosteringivesivesriorssetdefault��rowsinessym'

Explanation:

VersionSizePerplexityAnswer
32-bit original538 MB39.70Correct
8-bit220 MB41.14The same answer
4-bit, one scale per row166 MB69.16Drifts: "a wonderful place to live"
4-bit, groups of 32173 MB42.65Correct again
3-bit153 MB26,645.57Gibberish
2-bit140 MB87,735,475.35Gibberish
  • 8-bit is almost free: perplexity rises only from 39.70 to 41.14, and the answer is word for word the same.
  • 4-bit with one scale per row hurts, because one large weight in a row of 576 forces a big scale and crushes the small weights. Giving each group of 32 weights its own scale fixes most of it (42.65), for a little extra storage. This is what popular 4-bit formats such as GGUF, GPTQ and AWQ do, with further tricks.
  • 3 and 2 bits break the model completely. Rounding this coarse destroys the information the weights carry.
  • The sizes count the 30 blocks at the new precision and keep the embeddings at 32 bits, which is why even 2-bit stays at 140 MB. Real tools usually quantize the embeddings too, and store the original in 16 bits rather than 32.
  • This program rounds the weights and keeps computing in floats, to measure the quality effect simply. Real quantized models store the small integers and use special fast code to compute with them, which also brings the speed gains.

Running Models Locally

ToolWhat it does
llama.cpp and GGUF filesRuns quantized open models on CPUs and GPUs; the basis of many desktop apps
Ollama, LM StudioDesktop apps that download and run quantized models with one command or click
MLXApple's library for running and fine-tuning models on Apple chips
bitsandbytes, torchaoQuantization for PyTorch and Hugging Face models, including QLoRA fine-tuning
vLLM and similar serversFast serving of quantized models on GPUs

A rough rule for memory: parameters × bits ÷ 8 bytes for the weights, plus room for the context. A 7-billion-parameter model needs about 14 GB at 16 bits, but about 4 GB at 4 bits, so it fits on many laptops.

Common Mistakes

Choosing the smallest file without testing. 4-bit is usually the sweet spot; lower often breaks quality.

Forgetting the context memory. Long prompts need memory for the KV cache too; see "Scaling and Context Windows".

Comparing models at different precisions unfairly. A 4-bit bigger model can beat a 16-bit smaller one at the same memory, so compare at equal memory.

Downloading unknown model files. Use trusted sources and safe formats such as safetensors or GGUF; pickle-based files can run code when loaded.

Interview Corner

What is quantization, and what does it trade off?

Storing weights (and sometimes activations) in fewer bits, such as 8 or 4, using a scale to map small integers back to real values. It cuts memory and often speeds up inference, at the cost of some accuracy that grows as bits decrease.

Why do 4-bit formats use group-wise scales?

Because one large weight in a long row forces a large scale that rounds all the small weights to almost nothing. A separate scale for each small group, such as 32 or 128 weights, keeps the rounding error low for a small storage cost.

Practice

Exercise: group size. Change the 4-bit group size from 32 to 8, then to 128. How do the size and perplexity change, and which would you choose?

Check your understanding:

  1. What is stored for each weight in an 8-bit quantized matrix, and what else is stored?
  2. Why did 4-bit with one scale per row do much worse than with groups of 32?
  3. How much memory would a 3-billion-parameter model need for its weights at 4 bits?

Quick check: quantization

4 questions
1What was the perplexity at 8 bits?
2What fixed most of the 4-bit damage?
3What happened at 3 bits?
4About how much memory do a 7-billion-parameter model's weights need at 4 bits?

Key Takeaways

Quick reference

NeedFormula or tool
Quantizeq = round(w / scale), scale = max(abs(w)) / (2 ** (bits - 1) - 1)
Back to floatsw ≈ q × scale
Weight memoryparameters × bits ÷ 8 bytes
Run locallyllama.cpp, Ollama, LM Studio, MLX
Check qualityPerplexity and your evaluation set, before and after

Was this tutorial helpful?

Lesson 162 of 186