Lesson 7 of 10
Fake quantization with group scales
To store a weight in b bits with a symmetric scheme, pick a scale s and keep the integer q = round(w / s), clipped to [-qmax, qmax] where qmax = 2^(b-1) - 1. The stored model holds q and s; using it means computing q * s.
Fake quantization returns q * s in float directly, so you can measure the accuracy of the quantized model without any integer kernels. That's what harness/quant.py does to YOLO and lab/nn.py:fake_quantize does here.
The scale is shared by a group of consecutive weights: s = max|w in group| / qmax. Smaller groups, more scales, less error.
Implement fake_quantize(w, bits, group) for bits in 2..8, where group=None means one scale for the whole tensor. Group along the flattened tensor; the last group may be shorter.
Your code
Tab indents. Press Esc, then Tab, to leave the editor. Ctrl or Cmd + Enter checks your code.
Pigeon's hint, 1 of 2
Flatten, loop over chunks of group, quantize each with its own scale, reshape back.
Pigeon's hint, 2 of 2
group=None is the same as one group the size of the whole tensor.
import numpy as np
def fake_quantize(w, bits, group=None):
qmax = 2 ** (bits - 1) - 1
flat = w.ravel().astype(float)
g = group or flat.size
out = np.empty_like(flat)
for s in range(0, flat.size, g):
blk = flat[s:s + g]
scale = max(np.abs(blk).max(), 1e-12) / qmax
out[s:s + g] = np.clip(np.round(blk / scale), -qmax, qmax) * scale
return out.reshape(w.shape)
Pigeon's tip
Pigeon's warning
Pigeon's note
Where this is used
- Post-training quantizationRuns hereRound every weight to one of 2^b − 1 evenly spaced levels, symmetric around zero (two levels at 1 bit), after training. No data, no gradients; how fine the scale groups are decides how low b can go.
- Quantization-aware trainingRuns hereKeep training with quantized weights in the forward pass and full-precision weights in the backward pass (the straight-through estimator).
- Quantizing a detectorRuns in the cockpitThe same fake-quantization dial applied to YOLOv8's convolutions, with per-group scales and an optional spared detection head.