AlgoViz

What quantization does to a weight

medium 7 min

A trained layer contains real-valued parameters represented at finite precision.

Video lesson · Chapter 1 of 4

Four bits on a measuring bench

0:00 / 4:41

Theory

Read or listen first. About 2 min.

What it is

A trained layer contains real-valued parameters represented at finite precision. Quantization replaces values with a smaller set of representable levels. In a simple uniform scheme, divide a weight by a scale, add a zero point if needed, round and clip to the allowed integer range. To approximate the original value, subtract the zero point and multiply by the scale. Kernels can unpack or combine these representations during computation.

Why it exists

A coarse scale covers large magnitudes while losing distinctions between nearby small weights. A fine scale preserves small differences but clips outliers. Different layers or groups can use their own scales, at a metadata cost. Weight precision, activation precision, accumulator precision and KV-cache precision are independent choices. A four-bit weight file does not imply four-bit arithmetic or memory for the entire system.

Fit a small weight and an outlier on four bits

Weight sample → Integer code (original weights). Integer code → Reconstructed values (codes and scale). Reconstructed values → Quality comparison (approximation error). Weight sample → Quality comparison (reference output)
Weight sample → Integer code (original weights). Integer code → Reconstructed values (codes and scale). Reconstructed values → Quality comparison (approximation error). Weight sample → Quality comparison (reference output)

Inside this chapter

Chapter sources
Uniform quantization and clipping
With a signed four-bit toy codebook from −8 to 7, scale 0.1 and zero point 0, 0.26 maps to index 3 and reconstructs as 0.3. An outlier can round to an index beyond the codebook, at which point clipping creates additional error. Production GGUF K-quants use more elaborate block layouts.

Uniform quantisation lays a ruler over the weights: the scale is the spacing between marks and the bit width fixes how many marks exist. Each weight snaps to the nearest mark, so rounding error is at most half the spacing. Values beyond the last mark are clipped to it, and that error can be much larger. Choosing the scale is therefore a trade between resolution for typical weights and range for outliers.

Example. For 1.04, the rounded index would be 10. Clip to 7 and reconstruct 0.7. The absolute error is 0.34.

Another example. In a layer where nearly all weights lie within ±0.7 but a few reach 1.5, a scale chosen for the bulk clips those few heavily, and those large weights are often the ones that matter most.

Signed 4-bit codes, scale 0.1, zero point 0

Weight ww / sRoundedClipped to [-8, 7]ReconstructedError
0.262.6330.300.04
-0.53-5.3-5-5-0.500.03
1.0410.41070.700.34
Rounding costs at most half a step (0.05). Clipping has no such bound.
Calibration and group scales
In post-training quantization a representative calibration set can reveal activation ranges or weights that particularly affect layer outputs. GPTQ approximates layer reconstruction error; AWQ uses activation information to protect salient weights. Quantization-aware training instead accounts for quantization effects while updating parameters.

Calibration answers which weights and ranges actually matter for typical inputs. GPTQ quantises a layer's weights one by one and adjusts the remaining ones to compensate for the error introduced, minimising the change in the layer's output. AWQ looks at activation magnitudes to find salient channels and rescales them so they lose less precision. Group scales give each small block of weights its own scale, so one outlier only harms its own group, at the price of storing more scales.

Example. Calibrating only on short English chat can hide errors for long code or non-English documents. Evaluate those slices against the unquantized reference.

Another example. A team quantises a coding model using chat transcripts as calibration data. Code completion quality drops noticeably while chat looks fine; recalibrating with a mix that includes code recovers much of the loss.

Post-training quantisation with calibration
  1. 1Calibration setrepresentative prompts
  2. 2Run reference layerrecord activations
  3. 3Find what mattersranges and salient weights
  4. 4Choose scalesper group, protect salient
  5. 5Compare slicesversus unquantised outputs

If the calibration set misses a domain, the scales are not tuned for it.

Formats, loaders and compute
GGUF is a container. Q4_K_M is a mixed quantization preset associated with llama.cpp; its actual file size includes block metadata, tensors at different precisions and model metadata. A bitsandbytes four-bit load uses another representation and compatible kernels. Check device and engine support before assuming artifacts are interchangeable.

A format is a contract between the file and the code that reads it: how blocks are laid out, where scales live, which tensors stay at higher precision. Q4_K_M, for example, mixes precisions across tensors, so its average bits per weight is above four and its file size includes metadata. Before switching formats, check the engine supports that format on your device, then re-run quality checks, since the quantisation method itself differs.

Example. An AWQ checkpoint and a GGUF containing four-bit tensors are not drop-in replacements just because both descriptions say “4 bit.”

Three things called 4-bit

Each format needs a loader and kernels that understand it. They are not drop-in swaps.
Memory and throughput
Divide parameter count times nominal bits by eight for an ideal weight-only payload. Add scales, residual higher-precision tensors, runtime scratch space, KV cache, concurrency and operating-system headroom. Quantized kernels may save memory bandwidth but can add conversion costs.

The formula gives a floor, not a requirement. Real files add scales and keep some tensors such as embeddings at higher precision; the runtime adds KV cache that grows with context and concurrency, plus scratch buffers and operating-system headroom. Speed can improve because decoding is often limited by how fast weights stream from memory, and smaller weights stream faster, but unpacking them costs compute, so measure tokens per second rather than assuming.

Example. Eight billion parameters need an ideal 4 GB at four bits or 16 GB at sixteen bits, in decimal units. Neither number is a guaranteed device requirement.

Another example. An 8B model at 4 bits fits a 6 GB laptop GPU on paper. With a 4,096-token context and the desktop using some memory, the runtime may need to offload layers to CPU.

Ideal weight payload

bytes=N×b88×109×48=4 GB8×109×168=16 GB\text{bytes}=\frac{N\times b}{8}\qquad \frac{8\times10^{9}\times 4}{8}=4\,\text{GB}\qquad \frac{8\times10^{9}\times 16}{8}=16\,\text{GB}
Decimal gigabytes. Add scales, higher-precision tensors, KV cache, scratch space and headroom.
QLoRA and NF4
A frozen quantized backbone can supply weights to a higher-precision computation while small trainable adapters learn the task update. NF4 uses a different set of representable levels from this uniform integer example. Track base weights, adapter gradients and optimizer state separately.

QLoRA stores the base model in 4-bit NF4, a format whose levels are spaced to suit roughly normally distributed weights. During each forward pass the needed weights are dequantised to a higher-precision compute type, and small low-rank adapter matrices add a learned correction. Gradients flow back through the frozen base to the adapters, so only the adapters need gradients and optimiser state. Activations still take memory, especially with long sequences.

Example. Increasing adapter rank leaves the frozen four-bit weights intact but grows the trainable state. Lowering the base precision alone does not eliminate training activations.

Frozen 4-bit base, trainable adapters

The base never changes; only the adapters and their optimiser state are trained.

How it works

Step through the idea, or press Play.

Step 1 of 4

Weight sample. Inspect 0.26 and 1.04

Understand it

Worked example

Fit a small weight and an outlier on four bits

  1. 1

    Inspect 0.26 and 1.04

    These two weights share a toy group. The first lies inside the fine codebook range and the second exceeds it.

  2. 2

    Scale 0.1 gives codes 3 and 7

    Round 2.6 to 3. Round 10.4 to 10 and clip to the maximum signed index of 7.

  3. 3

    0.30 and 0.70

    Reconstruct with the stored scale. The errors are 0.04 and 0.34, so the outlier dominates these two local errors.

  4. 4

    Try a scale of 0.2

    Codes become 1 and 5, reconstructing 0.2 and 1.0. Errors become 0.06 and 0.04. Evaluate the whole layer and downstream tasks before choosing a production format.

Quantize and reconstruct

q=clip(round(w/s)+z,qmin⁡,qmax⁡),w^=s(q−z)q=\mathrm{clip}(\mathrm{round}(w/s)+z,q_{\min},q_{\max}),\qquad \hat w=s(q-z)
Here s is positive and z is the integer zero point. The worked signed example sets z to zero.

Follow the handoffs

A coarse scale covers large magnitudes while losing distinctions between nearby small weights. A fine scale preserves small differences but clips outliers. Different layers or groups can use their own scales, at a metadata cost. Weight precision, activation precision, accumulator precision and KV-cache precision are independent choices. A four-bit weight file does not imply four-bit arithmetic or memory for the entire system.

Same two weights, two scales

ScaleCodes for 0.26 and 1.04ReconstructedErrorsTotal error
0.13 and 7 (clipped)0.30 and 0.700.04 and 0.340.38
0.21 and 50.20 and 1.000.06 and 0.040.10
The coarser scale removes clipping but loses resolution on the small weight.

Fine scale (0.1)

  • Steps of 0.1 keep small weights accurate
  • Maximum rounding error 0.05
  • Good when there are no outliers

Coarse scale (0.2)

  • Steps of 0.2 blur nearby small weights
  • Maximum rounding error 0.10
  • Reaches 1.4 before clipping

Summary

The whole topic in one minute.

The number of codes remains fixed. Changing the scale spreads them farther apart.

A coarse scale covers large magnitudes while losing distinctions between nearby small weights. A fine scale preserves small differences but clips outliers. Different layers or groups can use their own scales, at a metadata cost. Weight precision, activation precision, accumulator precision and KV-cache precision are independent choices. A four-bit weight file does not imply four-bit arithmetic or memory for the entire system.

Sources