Model compression and quantisation
UAT 462 Edge Artificial Intelligence for UAS
Lesson
By the end of this module you will be able to
- Compute the scale and zero-point of asymmetric and symmetric quantisation, and explain why 0.0 must have an exact integer code
- Analyse quantisation error with SQNR and compare per-tensor with per-channel scales
- Choose and check a calibration set and a clipping method for activations that match real operating conditions
- Compute a linear layer in pure integer arithmetic with a fixed-point rescaling multiplier
- Choose between post-training quantisation and quantisation-aware training, and assess pruning, efficient architectures and distillation
Why this matters
From modules 1 and 2, the early layers of a model are limited by the bytes that move, and Sze et al. (2017) note that a DRAM access costs about 200 times the energy of one MAC. Storing weights and intermediate values as 8-bit integers instead of float32 cuts the bytes four times, both stored and moved. WasteNet-S shrinks from about 4.7 MB to 1.18 MB, and many accelerators support only integers (the Edge TPU, for example). But quantisation is not free: it adds error, and done badly it lowers the accuracy of the detector. This module builds on UAT 306 module 5, which taught the symmetric relation and the effect of one outlier. Here we add the asymmetric zero-point, error analysis, per-channel scales, calibration, integer-only arithmetic, quantisation-aware training and other ways to shrink a model.
Affine quantisation
Affine quantisation maps a real value to an integer with , where is the scale and the zero-point. Jacob et al. (2018) define as the value of that corresponds exactly to the real value 0, so that 0 is represented exactly. The reason is that models zero-pad image borders often; if 0 could not be represented exactly, every layer would put distorted values at the borders. The ONNX Runtime documentation gives two formulas: asymmetric and symmetric , which forces .
The LiteRT int8 specification shows that real systems choose differently for weights and activations. Weights are symmetric in with , per-axis or per-tensor. Activations are asymmetric in , per-tensor. The bias is int32 with scale equal to input scale times weight scale and . Weights are forced to so that no run-time cost is spent multiplying the weight’s zero-point by the activation.
Example 1 For non-negative values, what does the symmetric form cost?
A post-ReLU output is never negative, and the largest value seen during calibration is 6.2 (assumed). Compare asymmetric uint8 with symmetric int8: the codes used and the error. Then see what happens to a range that does not include zero.
import numpy as np
# quantisation parameters from a value range: widen it to include zero so that 0.0 has an exact integer code
def qparams(lo, hi, qmin, qmax, symmetric=False):
lo, hi = min(lo, 0.0), max(hi, 0.0)
if symmetric:
scale = max(abs(lo), abs(hi)) * 2 / (qmax - qmin)
return scale, 0
scale = (hi - lo) / (qmax - qmin)
return scale, int(round(qmin - lo / scale))
def quantise(x, scale, zp, qmin, qmax):
return np.clip(np.round(x / scale) + zp, qmin, qmax).astype(np.int32)
def dequantise(q, scale, zp):
return scale * (q - zp)
rng = np.random.default_rng(3)
relu_out = np.minimum(np.abs(rng.normal(0, 1.8, 20000)), 6.2) # post-ReLU output, never negative, largest value seen 6.2 (assumed)
setups = {"asymmetric uint8 [0, 255]": (0, 255, False), "symmetric int8 [-127, 127]": (-127, 127, True)}
for name, (qmin, qmax, sym) in setups.items():
s, z = qparams(0.0, 6.2, qmin, qmax, sym)
q = quantise(relu_out, s, z, qmin, qmax)
err = np.abs(dequantise(q, s, z) - relu_out)
print(f"{name:27s} scale {s:.5f} zero-point {z:4d} codes used {q.min()}..{q.max()} mean |error| {err.mean():.5f} max {err.max():.5f}")
print("0.0 survives a round trip exactly:", dequantise(quantise(np.array([0.0]), *qparams(0.0, 6.2, 0, 255), 0, 255), *qparams(0.0, 6.2, 0, 255))[0] == 0.0)
# a range that excludes zero (assumed [2.0, 6.0]) is widened to include it, which costs some resolution
s_wide, z_wide = qparams(2.0, 6.0, 0, 255)
print(f"range [2, 6] used as [0, 6]: scale {s_wide:.5f} instead of {4 / 255:.5f}")
asymmetric uint8 [0, 255] scale 0.02431 zero-point 0 codes used 0..255 mean |error| 0.00608 max 0.01216
symmetric int8 [-127, 127] scale 0.04882 zero-point 0 codes used 0..127 mean |error| 0.01219 max 0.02441
0.0 survives a round trip exactly: True
range [2, 6] used as [0, 6]: scale 0.02353 instead of 0.01569
The asymmetric form uses all 256 codes, with scale 0.02431 and mean error 0.00608. The symmetric form can use only the positive half (codes 0 to 127) because there are no negative values, so its scale is twice as coarse and its error twice as large (0.01219), which wastes one bit. The value 0.0 returns to exactly 0.0 in both. A range that excludes zero, such as [2, 6], must be widened to include 0, so resolution coarsens from 0.01569 to 0.02353. That is the price of guaranteeing that 0 is exact.
Quantisation error and SQNR
Rounding to the nearest code makes an error of at most half a step, , where . If the error is uniformly distributed its power is and its rms value is (Kester, MT-001). The signal-to-quantisation-noise ratio (SQNR) is signal power divided by error power. For a full-scale sine wave and an ideal -bit converter it is dB (Kester, MT-001): each extra bit improves it by about 6 dB. The formula has a condition: it needs a full-scale sine, and a network’s activations are not a full-scale sine.
Example 2 Does 6.02b + 1.76 apply to activations?
Measure the SQNR of 4-, 6- and 8-bit quantisers on three signals: a full-scale sine, uniform values over the full range, and normal values whose full range equals 4 sigma. Compare with the formula.
import numpy as np
# SQNR of a b-bit quantiser: a full-scale sine, uniform values, and normal values clipped at 4 sigma
def sqnr_db(x, bits, amp):
step = 2 * amp / 2 ** bits
top = 2 ** (bits - 1)
xq = (np.clip(np.floor(x / step), -top, top - 1) + 0.5) * step
return 10 * np.log10(np.mean(x ** 2) / np.mean((xq - x) ** 2))
rng = np.random.default_rng(11)
n = 400_000
sine = np.sin(2 * np.pi * rng.random(n)) # amplitude 1 = half of the full range
uniform = rng.uniform(-1, 1, n)
normal = np.clip(rng.normal(0, 0.25, n), -1, 1) # sigma = 0.25, so the full range is 4 sigma
print("bits | sine measured | 6.02b+1.76 | uniform | 6.02b | normal at 4 sigma | 6.02b-7.27")
for b in (4, 6, 8):
print(f"{b:4d} | {sqnr_db(sine, b, 1):13.2f} | {6.02 * b + 1.76:10.2f} | {sqnr_db(uniform, b, 1):7.2f} | {6.02 * b:5.2f} | {sqnr_db(normal, b, 1):17.2f} | {6.02 * b - 7.27:10.2f}")
bits | sine measured | 6.02b+1.76 | uniform | 6.02b | normal at 4 sigma | 6.02b-7.27
4 | 25.31 | 25.84 | 24.08 | 24.08 | 16.82 | 16.81
6 | 37.62 | 37.88 | 36.15 | 36.12 | 28.87 | 28.85
8 | 49.80 | 49.92 | 48.17 | 48.16 | 40.91 | 40.89
The sine matches within 0.6 dB (closer with more bits). Uniform values give because the signal power is rather than the sine’s (a 1.76 dB difference). Normal values with a full range of 4 sigma give because the signal power is only while the noise is unchanged. So the distribution of the data sets SQNR as much as the number of bits does. Data that clusters in the middle of the range uses fewer codes than you might think, which leads to the calibration and clipping below.
Per-tensor or per-channel scales
After BatchNorm is folded into Conv (module 2), the weights of each output channel have very different widths, because each channel is multiplied by its own . With one scale for the whole tensor, the widest channel sets the scale and most weights of a narrow channel round to 0. A scale per output channel (per-channel) fixes this at the cost of storing one more scale per channel, which the LiteRT weight specification supports (per-axis or per-tensor).
Example 3 Per-tensor against per-channel, how different?
Assumed weights with 64 output channels whose sigma lies between 0.005 and 0.5 (widths differing up to 100 times). Quantise to symmetric int8 in two ways, then measure the relative error of each channel’s weights and of this layer’s output.
import numpy as np
# assumed conv weights with 64 output channels whose widths differ up to 100x (as after folding BatchNorm)
rng = np.random.default_rng(21)
channel_std = np.exp(rng.uniform(np.log(0.005), np.log(0.5), 64))
W = rng.normal(0, 1, (64, 288)) * channel_std[:, None]
x = rng.normal(0, 1, (288, 500))
def quant_sym(W, scale):
return np.clip(np.round(W / scale), -127, 127) * scale
tensor_scale = np.abs(W).max() / 127 # one scale for the whole tensor
channel_scale = np.abs(W).max(axis=1, keepdims=True) / 127 # one scale per output channel
for name, Wq in (("per-tensor", quant_sym(W, tensor_scale)), ("per-channel", quant_sym(W, channel_scale))):
rel = np.linalg.norm(Wq - W, axis=1) / np.linalg.norm(W, axis=1) # relative weight error of each channel
out = np.linalg.norm(Wq @ x - W @ x, axis=1) / np.linalg.norm(W @ x, axis=1)
print(f"{name:11s} weight error: mean {rel.mean() * 100:5.2f} %, worst channel {rel.max() * 100:5.2f} % | output error: mean {out.mean() * 100:5.2f} %, worst {out.max() * 100:5.2f} %")
print(f"narrowest channel std {channel_std.min():.4f}, widest {channel_std.max():.3f}; per-tensor step {tensor_scale:.5f}")
per-tensor weight error: mean 18.53 %, worst channel 80.21 % | output error: mean 18.50 %, worst 81.80 %
per-channel weight error: mean 0.68 %, worst channel 0.91 % | output error: mean 0.68 %, worst 0.91 %
narrowest channel std 0.0050, widest 0.484; per-tensor step 0.01392
Per-tensor, the weight error averages 18.53% and the worst channel is 80.21%, because the single step of 0.01392 is larger than the sigma of the narrowest channel (0.0050), and the layer output goes wrong with it. Per-channel leaves 0.68% on average and 0.91% at worst, about 27 times better, for only 64 extra scale values. This is why real systems use per-channel for convolution weights. If the accelerator supports only per-tensor, check accuracy with special care after folding BatchNorm.
Calibrating activations to the operating conditions
Weights are known exactly at conversion time, but activations depend on the incoming images. The model must be run on a small calibration set to see the value range and fix the scales in advance. The ONNX Runtime documentation separates dynamic quantisation (activation scales computed at run time, costing more but often more accurate) from static (using a calibration set), and recommends dynamic for RNNs and transformer models and static for CNN models. The range methods it supports are MinMax, Entropy and Percentile. TensorRT uses a calibration set to compute a scale per tensor for post-training INT8.
Two questions matter: what should the clipping value be, and does the calibration set represent real conditions? A high clip keeps the spikes but makes the steps coarse; a low clip is fine-grained but throws the spikes away. If those spikes are real signal, throwing them away ruins the result.
Example 4 Calibrate on dawn images but fly at noon
Post-ReLU feature maps from dawn and noon images (simulated). Noon is 1.8 times brighter, and both have occasional spikes six times higher (0.05% of values), assumed to be glare off plastic bags, which is real signal. Test three clipping methods with two calibration sets, then measure SQNR on test images of both conditions.
import numpy as np
# post-ReLU feature maps of dawn and noon images (simulated); noon is 1.8x brighter and has occasional spikes
rng = np.random.default_rng(5)
def activations(scale, n=200_000):
a = np.abs(rng.normal(0, 1, n)) * scale
spikes = rng.random(n) < 0.0005
return np.where(spikes, a * 6, a)
dawn_cal, dawn_test, noon_cal, noon_test = activations(1.0), activations(1.0), activations(1.8), activations(1.8)
def mse_clip(x, clip, levels=256):
step = clip / (levels - 1)
return np.mean((np.clip(np.round(np.minimum(x, clip) / step), 0, levels - 1) * step - x) ** 2)
def choose(cal, method):
if method == "min-max":
return cal.max()
if method == "percentile 99.9":
return np.percentile(cal, 99.9)
grid = np.linspace(0.5, cal.max(), 400) # search for the clip value with the lowest MSE
return grid[np.argmin([mse_clip(cal, c) for c in grid])]
def sqnr(x, clip):
return 10 * np.log10(np.mean(x ** 2) / mse_clip(x, clip))
print(f"{'calibrated on':14s} {'method':16s} {'clip':>6s} {'SQNR dawn':>10s} {'SQNR noon':>10s}")
for cal_name, cal in (("dawn images", dawn_cal), ("noon images", noon_cal)):
for method in ("min-max", "percentile 99.9", "MSE search"):
c = choose(cal, method)
print(f"{cal_name:14s} {method:16s} {c:6.2f} {sqnr(dawn_test, c):8.1f} dB {sqnr(noon_test, c):8.1f} dB")
calibrated on method clip SQNR dawn SQNR noon
dawn images min-max 14.31 35.7 dB 27.1 dB
dawn images percentile 99.9 3.35 21.7 dB 15.3 dB
dawn images MSE search 12.68 35.9 dB 25.9 dB
noon images min-max 27.62 30.2 dB 34.3 dB
noon images percentile 99.9 6.16 26.4 dB 21.0 dB
noon images MSE search 23.61 31.6 dB 33.1 dB
Calibrating on dawn images with min-max gives a clip of 14.31 and 35.7 dB on dawn images, but on noon images it drops to 27.1 dB because real noon values exceed the clip and are cut off. In the other direction, calibrating on noon gives 34.3 dB on noon images but only 30.2 dB on dawn images because the step is coarser than needed. The 99.9th percentile clips at 3.35, which cuts off all the glare and SQNR collapses to 21.7 and 15.3 dB: percentile rules assume spikes are noise, but here they are signal. The MSE search lands close to min-max. The conclusion is that no single rule is always right. The calibration set must include every operating condition (dawn, noon, evening, season), and the task’s own metric (such as the detector’s AP) must be evaluated, not SQNR alone.
Pure integer arithmetic
Once and of every tensor are known, a linear layer can be computed in pure integer arithmetic (Jacob et al., 2018). Products of two int8 values accumulate in an int32 accumulator and an int32 bias of scale is added. The result must then be brought back to the 8-bit range of the output with the multiplier , the one real number left. Jacob et al. found always lies in (0, 1), so it is written with and is stored as a 32-bit fixed-point integer (the int32 nearest to ). The multiplication becomes an integer multiply and a rounding bit shift, with no floating-point unit at all. If the term must be subtracted, which is an extra cost.
Example 5 A 64 to 32 linear layer in pure integers
A uint8 input (non-negative), symmetric int8 weights, an int32 bias and a uint8 output. Compute the accumulator, find and , compare the fixed-point multiply with the floating multiplier, and compare the result with the layer computed in floating point.
import numpy as np
# a 64 -> 32 linear layer in integer arithmetic only: uint8 input (S_x, Z_x), symmetric int8 weights, int32 accumulator
rng = np.random.default_rng(8)
x = np.minimum(np.abs(rng.normal(0, 1.5, 64)), 6.0) # non-negative input (assumed)
W = rng.normal(0, 0.15, (32, 64))
bias = rng.normal(0, 0.1, 32)
S_x, Z_x = 6.0 / 255, 0
S_w = np.abs(W).max() / 127
qx = np.clip(np.round(x / S_x) + Z_x, 0, 255).astype(np.int64)
qw = np.clip(np.round(W / S_w), -127, 127).astype(np.int64)
qb = np.round(bias / (S_x * S_w)).astype(np.int64) # bias is int32 with scale S_x * S_w and zero-point 0
y_float = W @ x + bias
S_y, Z_y = (y_float.max() - y_float.min()) / 255, 0
Z_y = int(round(-y_float.min() / S_y))
acc = qw @ (qx - Z_x) + qb # int8 x int8 products accumulated in int32
acc_expanded = qw @ qx - Z_x * qw.sum(axis=1) + qb # zero-point term written out: an extra cost when Z_x is not 0
print("accumulator range fits int32:", acc.min() > -2 ** 31 and acc.max() < 2 ** 31, "| both forms equal:", np.array_equal(acc, acc_expanded))
M = S_x * S_w / S_y # the single remaining real multiplier
n = 0
while M * 2 ** n < 0.5:
n += 1
M0 = M * 2 ** n # M = M0 * 2^-n with M0 in [0.5, 1)
M0_int = int(round(M0 * 2 ** 31))
product = acc * M0_int
q_fixed = Z_y + ((product + (1 << (30 + n))) >> (31 + n)) # integer multiply, then a rounding bit shift
q_float = Z_y + np.round(acc * M).astype(np.int64)
q_fixed, q_float = np.clip(q_fixed, 0, 255), np.clip(q_float, 0, 255)
err = np.abs(S_y * (q_fixed - Z_y) - y_float)
print(f"M = {M:.6f} = {M0:.6f} x 2^-{n}, M0 as int32: {M0_int}")
print(f"fixed-point vs floating multiplier: max difference {np.abs(q_fixed - q_float).max()} code; output error vs float layer: max {err.max():.4f} = {err.max() / S_y:.2f} steps of S_y = {S_y:.4f}")
accumulator range fits int32: True | both forms equal: True
M = 0.002620 = 0.670753 x 2^-8, M0 as int32: 1440430618
fixed-point vs floating multiplier: max difference 0 code; output error vs float layer: max 0.0386 = 1.12 steps of S_y = 0.0343
The accumulator fits in int32 and the two ways of writing it (with and without the zero-point term) agree. and is the integer 1,440,430,618. The fixed-point multiply differs from the floating multiplier by 0 codes. The error of the output against the floating layer is at most 0.0386, or 1.12 steps of , which comes from quantising the input and the weights, not from the integer arithmetic.
Quantisation-aware training
Post-training quantisation (PTQ) needs no retraining or labels, so it is convenient. Nagel et al. (2021) conclude that for 8 bits it is mostly sufficient, with accuracy close to floating point, while quantisation-aware training (QAT) needs fine-tuning on labelled data but makes lower bit-widths competitive. QAT inserts nodes that simulate quantisation into the training graph. The forward pass uses the rounded weights, and the backward pass sends the gradient straight through the rounding (the straight-through estimator, STE) to update the floating-point weights. Jacob et al. (2018) describe quantising weights before the convolution, tracking activation ranges with exponential moving averages, and, because ranges change quickly early on, disabling activation quantisation at the start of training; the folding of BatchNorm must be simulated too.
Example 6 PTQ against QAT as bits fall
A small two-layer network trained by hand in NumPy on two overlapping classes in 20 dimensions (simulated). Compare PTQ (train in floating point, then round the weights) with QAT (train while rounding the weights every step) at 8, 4 and 2 bits. Two bits has only three levels, .
import numpy as np
# two overlapping classes in 20 dimensions (assumed) and a two-layer network trained by hand
rng = np.random.default_rng(2)
def make(n):
y = rng.integers(0, 2, n)
centre = np.where(y[:, None] == 1, 0.5, -0.5) * np.linspace(1.5, 0.2, 20)
return rng.normal(0, 1, (n, 20)) + centre, y
Xtr, ytr = make(4000)
Xte, yte = make(4000)
def fake_quant(w, bits):
levels = 2 ** (bits - 1) - 1
scale = np.abs(w).max() / levels
return np.round(w / scale) * scale # quantised values, kept as floats
def train(bits=None, epochs=300, lr=0.2):
r = np.random.default_rng(4)
W1, b1 = r.normal(0, 0.3, (20, 16)), np.zeros(16)
W2, b2 = r.normal(0, 0.3, 16), 0.0
q = (lambda w: w) if bits is None else (lambda w: fake_quant(w, bits))
for _ in range(epochs):
A1, A2 = q(W1), q(W2) # forward pass uses the quantised weights
h = np.maximum(Xtr @ A1 + b1, 0)
p = 1 / (1 + np.exp(-(h @ A2 + b2)))
g = (p - ytr) / len(ytr)
gh = np.outer(g, A2) * (h > 0)
W2 -= lr * h.T @ g # STE: pass the gradient straight to the float weights
b2 -= lr * g.sum()
W1 -= lr * Xtr.T @ gh
b1 -= lr * gh.sum(axis=0)
return W1, b1, W2, b2
def accuracy(params, bits=None):
W1, b1, W2, b2 = params
if bits is not None:
W1, W2 = fake_quant(W1, bits), fake_quant(W2, bits)
return np.mean(((np.maximum(Xte @ W1 + b1, 0) @ W2 + b2) > 0) == yte) * 100
fp = train()
print(f"float32 model : {accuracy(fp):.1f} %")
for bits in (8, 4, 2):
qat = train(bits)
print(f"{bits} bit weights: post-training {accuracy(fp, bits):5.1f} %, quantisation-aware {accuracy(qat, bits):5.1f} %")
float32 model : 98.0 %
8 bit weights: post-training 98.0 %, quantisation-aware 98.0 %
4 bit weights: post-training 97.9 %, quantisation-aware 97.8 %
2 bit weights: post-training 92.8 %, quantisation-aware 97.2 %
At 8 and 4 bits both methods are within 0.2 percentage points of the floating-point model, consistent with the conclusion that PTQ is usually enough at 8 bits. At 2 bits PTQ falls to 92.8% while QAT reaches 97.2%, recovering 4.4 points. This is a small model on simulated data to show the mechanism, not a result for the real detector. In real work measure on the group’s validation set, and remember that QAT costs extra training time, so always start with PTQ and use QAT when the accuracy is still short of the criterion.
Other ways to shrink: efficient architectures, pruning and distillation
Quantisation reduces the bits per value. The three methods below reduce the number of values, or let a small model learn from a big one.
Efficient architectures. Howard et al. (2017) use depthwise separable convolution: a depthwise step ( per channel) followed by a pointwise step (). The cost is of the standard convolution, and they report that with kernels it uses 8 to 9 times less computation.
Pruning. Han et al. (2015) train, prune the unimportant connections and retrain, reducing the parameters of AlexNet 9 times and VGG-16 13 times with no loss of accuracy on ImageNet. But zeros in the weights do not make hardware faster by themselves: a dense kernel still multiplies by zero. The pattern must be one the hardware supports, such as 2:4 (keep 2 of every 4 values), which doubles the math throughput of sparse tensor cores (Mishra et al., 2021), or removing whole channels, which cuts work on any hardware.
Distillation. Hinton et al. (2015) let a small model (the student) learn from the soft probabilities of a large model (the teacher), obtained from a softmax at temperature : . Because the gradient magnitudes of the soft targets scale as , they are multiplied by when combined with the hard targets.
Example 7 Shrinking without fewer bits: architecture and three kinds of pruning
Replace the stride-1 3 × 3 convolutions of WasteNet-S with depthwise separable ones and count the MACs. Then prune the weights of one layer (assumed Laplace-distributed, since trained weights tend to peak at zero) in three ways: 50% unstructured, the 2:4 pattern, and removing 25% of the channels. Measure the output error before fine-tuning.
import numpy as np
# (a) replace the stride-1 3 x 3 convolutions of WasteNet-S with depthwise separable ones
layers = [("conv1", 3, 16, 3, 2), ("conv2", 16, 32, 3, 2), ("conv3", 32, 32, 3, 1), ("conv4", 32, 64, 3, 2),
("conv5", 64, 64, 3, 1), ("conv6", 64, 128, 3, 2), ("conv7", 128, 128, 3, 1), ("conv8", 128, 256, 3, 2),
("conv9", 256, 256, 3, 1), ("head", 256, 21, 1, 1)]
size, base, slim = 640, 0, 0
for name, cin, cout, k, s in layers:
out = size // s
standard = out * out * k * k * cin * cout
separable = out * out * (k * k * cin + cin * cout) # depthwise k x k per channel, then pointwise 1 x 1
base += standard
slim += separable if (s == 1 and k == 3) else standard
size = out
print(f"MACs {base / 1e9:.3f} G -> {slim / 1e9:.3f} G (x{base / slim:.2f}); per-layer ratio 1/N + 1/9 = {1 / 256 + 1 / 9:.3f} for N = 256")
# (b) prune 50 % of the weights in two ways and 25 % of the output channels, then look at the output error
rng = np.random.default_rng(9)
W = rng.laplace(0, 1, (64, 288)) * rng.lognormal(0, 0.5, (64, 1)) # trained weights tend to peak at zero, so a Laplace distribution is assumed
x = rng.normal(0, 1, (288, 500))
def rel(Wp):
return np.linalg.norm(Wp @ x - W @ x) / np.linalg.norm(W @ x) * 100
unstructured = np.where(np.abs(W) >= np.quantile(np.abs(W), 0.5), W, 0.0)
groups = np.abs(W).reshape(64, 72, 4)
keep = np.argsort(groups, axis=2)[:, :, 2:] # keep the 2 largest of every 4 values (the 2:4 pattern)
mask = np.zeros_like(groups, dtype=bool)
np.put_along_axis(mask, keep, True, axis=2)
two_four = np.where(mask.reshape(64, 288), W, 0.0)
norms = np.linalg.norm(W, axis=1)
channel_pruned = W.copy()
channel_pruned[norms <= np.quantile(norms, 0.25)] = 0.0 # drop the 25 % of channels with the smallest norm
for name, Wp, saved in (("unstructured 50 %", unstructured, "0 % (zeros are still multiplied)"), ("2:4 pattern", two_four, "50 % on hardware with 2:4 support"),
("25 % channels removed", channel_pruned, "25 % on any hardware")):
print(f"{name:22s} nonzero {np.count_nonzero(Wp) / Wp.size * 100:5.1f} % output error {rel(Wp):5.1f} % | dense kernel saves {saved}")
MACs 1.462 G -> 0.637 G (x2.30); per-layer ratio 1/N + 1/9 = 0.115 for N = 256
unstructured 50 % nonzero 50.0 % output error 14.9 % | dense kernel saves 0 % (zeros are still multiplied)
2:4 pattern nonzero 50.0 % output error 28.3 % | dense kernel saves 50 % on hardware with 2:4 support
25 % channels removed nonzero 75.0 % output error 24.0 % | dense kernel saves 25 % on any hardware
Depthwise separable convolution cuts the MACs from 1.462 G to 0.637 G (2.30 times) by changing just four layers (each by at ). Unstructured pruning has the smallest error (14.9%) but a dense kernel saves nothing because it still multiplies the zeros. The 2:4 pattern has an error of 28.3% but saves 50% on hardware that supports it. Channel removal has an error of 24.0% and saves 25% on any hardware. These errors are before retraining, which helps a lot (Han et al., 2015). The lesson: choose the pruning pattern for what the target hardware can exploit.
Example 8 Distillation: what does temperature reveal?
The teacher is sure it is a waste pile, but garden waste is closer than bare soil (assumed logits 6.0, 4.0 and 0.5). Look at the probabilities at and and compute the student’s combined loss.
import numpy as np
# distillation: softmax at temperature T makes the wrong-class probabilities visible
classes = ["waste pile", "garden waste", "bare soil"]
logits = np.array([6.0, 4.0, 0.5]) # the teacher is sure of a waste pile, but garden waste is closer than soil (assumed)
def softmax(z, T):
e = np.exp((z - z.max()) / T)
return e / e.sum()
for T in (1, 4):
print(f"T = {T}:", {c: round(float(p), 3) for c, p in zip(classes, softmax(logits, T))})
student = np.array([2.0, 1.0, 0.2])
T = 4
soft_loss = float(np.sum(softmax(logits, T) * (np.log(softmax(logits, T)) - np.log(softmax(student, T))))) * T * T
hard_loss = float(-np.log(softmax(student, 1)[0]))
alpha = 0.7
print(f"soft (KL x T^2) {soft_loss:.3f}, hard cross-entropy {hard_loss:.3f}, total {alpha * soft_loss + (1 - alpha) * hard_loss:.3f}")
T = 1: {'waste pile': 0.878, 'garden waste': 0.119, 'bare soil': 0.004}
T = 4: {'waste pile': 0.538, 'garden waste': 0.326, 'bare soil': 0.136}
soft (KL x T^2) 0.876, hard cross-entropy 0.427, total 0.741
At the teacher gives waste pile 0.878, garden waste 0.119 and bare soil only 0.004, almost a single answer. At it is 0.538, 0.326 and 0.136, which shows clearly that garden waste resembles a waste pile more than soil does. This hidden knowledge is what a hard label (“waste pile”) lacks. A student that learns from both together ( on the soft target) gets a combined loss of 0.741.
Module lab
Lab: quantise the group’s model and measure the effect on accuracy
- Quantise the group’s ONNX model to static INT8 with ONNX Runtime using a calibration set of at least 100 images that includes both dawn and evening images, then compare file size, time (after warm-up, report p50 and p95) and accuracy (AP on the validation set) with the original model.
- Change the range method (MinMax, Entropy, Percentile) and compare accuracy. Record which is best for the group’s data and why.
- Calibrate on images of one condition only (for example dawn only) and test on another condition. Report the accuracy lost.
- Compare per-channel with per-tensor scales (if the tool supports it) and look at the accuracy difference.
- Use the code of Example 5 to compute the multiplier and of one layer of the group’s model and check that the fixed-point multiply matches the floating one.
- If the accuracy after PTQ is below the criterion, reduce what can be reduced first (enlarge the calibration set, skip layers sensitive to quantisation), then consider QAT or distillation. Record the result of every step.
The work of this module is desk work, with no flying.
Common mistakes
Watch out
- Calibrating on images of one condition and using the model in several; values beyond the range are clipped
- Using a percentile rule to clip spikes without checking whether they are signal or noise
- Using a symmetric range for non-negative values, losing one bit
- Using one scale for a whole weight tensor after folding BatchNorm, so narrow channels round to zero
- Reporting only SQNR or file size without measuring the metric of the real task
- Pruning without a pattern and expecting a speed-up, when a dense kernel still multiplies zeros
- Jumping to QAT and skipping PTQ, though PTQ is usually enough for 8 bits
- Forgetting that on some x86-64 CPUs the U8S8 form can saturate; try reduce_range or U8U8, as the ONNX Runtime documentation says
Summary
- , and 0.0 must have an exact integer code. Weights use the symmetric form; activations may use the asymmetric one; a symmetric range for non-negative values wastes one bit
- SQNR rises about 6 dB per bit, but applies to a full-scale sine; data clustered mid-range gets less
- Per-channel scales for weights help a lot when channel widths differ; the calibration set must represent every operating condition, and the task metric must be measured
- Pure integer: int8 products accumulate in int32, then are rescaled with in fixed point
- Start with PTQ at 8 bits and use QAT for low bit-widths or short accuracy; pruning must match what the hardware can use, and distillation transfers knowledge a hard label lacks
Check your understanding
- The range is quantised to uint8 asymmetrically. Find the scale and the zero-point.
- What is the SQNR of an ideal 6-bit quantiser with a full-scale sine?
- A model has 4.2 million parameters. How much memory does it need stored as float32, int8 and 4-bit?
- The whole weight tensor has a maximum absolute value of 0.5, and one channel has a maximum absolute value of 0.04. With symmetric int8 per tensor, how many levels does that channel use, against per channel?
- , , . Find , and .
Answers
- and
- dB
- float32 MB, int8 4.2 MB, 4-bit 2.1 MB
- Per tensor the step is and the channel uses about , so codes to , 21 levels. Per channel the step is and about all 255 levels are used
- ; times gives 0.8192, which is in , so and (as an int32 about )
Key formulas
| Affine relation | |
| Asymmetric and symmetric scale | |
| Output rescaling multiplier | |
| SQNR of a b-bit quantiser |
Key references
- Jacob, B., Kligys, S., Chen, B., Zhu, M., Tang, M., Howard, A., Adam, H., & Kalenichenko, D. (2018). Quantization and training of neural networks for efficient integer-arithmetic-only inference. In 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 2704–2713). link
- Microsoft. Quantize ONNX models. ONNX Runtime documentation. link
- Google. 8-bit quantization specification. LiteRT documentation. link
- Nagel, M., Fournarakis, M., Amjad, R. A., Bondarenko, Y., van Baalen, M., & Blankevoort, T. (2021). A white paper on neural network quantization. arXiv:2106.08295. link
- Kester, W. Taking the mystery out of the infamous formula, "SNR = 6.02N + 1.76dB," and why you should care (Tutorial MT-001). Analog Devices. link
- Sze, V., Chen, Y.-H., Yang, T.-J., & Emer, J. S. (2017). Efficient processing of deep neural networks: A tutorial and survey. Proceedings of the IEEE, 105(12), 2295–2329 (arXiv:1703.09039). link
- Han, S., Pool, J., Tran, J., & Dally, W. J. (2015). Learning both weights and connections for efficient neural networks. In Advances in Neural Information Processing Systems 28 (arXiv:1506.02626). link
- Mishra, A., Latorre, J. A., Pool, J., Stosic, D., Stosic, D., Venkatesh, G., Yu, C., & Micikevicius, P. (2021). Accelerating sparse deep neural networks. arXiv:2104.08378. link
- Howard, A. G., Zhu, M., Chen, B., Kalenichenko, D., Wang, W., Weyand, T., Andreetto, M., & Adam, H. (2017). MobileNets: Efficient convolutional neural networks for mobile vision applications. arXiv:1704.04861. link
- Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the knowledge in a neural network. arXiv:1503.02531. link
- NVIDIA. NVIDIA TensorRT documentation. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results