One scale for a whole layer sinks MobileNetV1 from 70.9% to 0.1% at 8 bits. A scale per channel lifts it to 59.1%. Training through the rounding brings it to 70.7%.
Learn how to shrink a trained network's numbers to a few bits without wrecking it: where to put the scales, how far to clip, how to round, and how to train around the damage.
Pick how many numbers share one scale, then drag the bit width down. Watch which channels break first. Then we build, piece by piece, the integer layer, the three granularities, range clipping, rounding, the straight-through trick, one-bit weights and a search for the best bits per layer.
You need the idea of a weight matrix (a table of numbers a layer multiplies by) and a little Python for the code. We build the rest from zero.
Based on Lecture 6 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Course page and lecture slides. Every idea is re-taught here in our own words and devices. It follows Lecture 5 and leads into Lecture 7.
Illustrative: eight output channels of eight made-up weights each. The largest weight per channel runs from 0.08 to 6.0, a 75 times spread, in the spirit of the lecture's MobileNetV2 depthwise layer (more than 100 times). Quantization is symmetric. Each bar is the size of the error as a share of that channel's own weights.
Chapter 0
See why a trained network keeps its accuracy only if you choose the scales, the range and the rounding with care
A small camera sits on a farm gate. Its chip has 256 KB of memory. Your trained network has five million weights, each a 32-bit float. That is 20 MB, 80 times too big.
Quantization stores each number as a small integer on a short ruler of marks. Fewer bits cost less memory, less energy for each read and smaller multipliers. Each bit you drop also adds error.
| Bits per weight | Memory for 5 million weights | Fits in 256 KB? |
|---|---|---|
| 32 (float) | 20 MB | No, 80 times too big |
| 8 | 5 MB | No |
| 4 | 2.5 MB | No |
| 1 | 0.625 MB | No: the camera also needs pruning (Lectures 3 and 4) and a smaller design (Lecture 7) |
Lecture 5 gave two ways to store a weight as a small integer. K-means quantization stores the index of the nearest entry in a codebook, a short list of real values (Deep Compression, Han et al., ICLR 2016). Linear quantization spaces the marks evenly, so the integer itself carries the value.
| Method | What the chip stores | What the chip computes |
|---|---|---|
| Floating point | 32-bit float weights | Floating-point arithmetic |
| K-means | Integer indexes, plus a float codebook | Floating-point arithmetic, after a lookup |
| Linear | Integer weights, plus a scale and a zero point | Integer arithmetic |
Blue dots are the real weights. Warm ticks are the values you can store. Each dot snaps to the nearest tick. Switch the method, then lower the bits.
The sixteen weights are the 4 by 4 matrix from the lecture's example (2.09, −0.98, 1.48, 0.09 and so on). Error is the Frobenius norm, the square root of the sum of squared gaps. The linear ruler is asymmetric: S = (rmax − rmin) / (qmax − qmin). Storage counts one 32-bit float per centroid, one 32-bit scale and one zero point of the same bit width.
At 2 bits K-means usually has the lower error, because its marks follow the data. Linear still wins on a small chip, because the chip multiplies its integers directly. This lecture fits that even ruler to the data.
How far can it go? On the slide's AlexNet plot, pruning plus quantization keeps its accuracy down to about 4 percent of the original size. Quantization alone starts to slip below about 8 percent.
Symptom: you quantize a trained model to 8 bits and its accuracy falls off a cliff. Measure: MobileNetV1 drops from 70.9 percent to 0.1 percent with one scale for each tensor (Chapter 7). Fix: a toolbox with one tool for each cause, in the order below.
The lecture has five parts. Post-training quantization (PTQ) quantizes a finished float model with no retraining. Quantization-aware training (QAT) trains with the rounding in the loop.
Chapter 1
Follow one tiny layer through the integer pipeline and see where the scales and the zero point go
A cashier's till holds only whole cents. She stores 437, not 4.37, and remembers once that one unit is one cent. A quantized layer works the same way.
Call the real number you want to store r and the stored integer q. Call the real gap between two neighbouring integers the scale S. Call the integer that stands for real zero the zero point Z.
r equals S times, open bracket, q minus Z, close bracket.
Subtract the zero point Z from the stored integer q. Multiply by the scale S. The result is the real value r.
The lecture's 2-bit example has S = 1.07 and Z = −1. The stored q = 1 gives r = 1.07 × (1 − (−1)) = 2.14. The original weight was 2.09, so the error is 0.05.
To choose S and Z, stretch the integer range over the real range. The lecture's 4 by 4 matrix runs from −1.08 to 2.12, and at 2 bits q runs from −2 to 1.
A layer computes Y = WX + b. The weights W, the input X, the bias b and the output Y each get their own scale and zero point. Write every term through its own rule:
The slide makes three choices, then solves for the output integer qY:
q-Y equals S-W S-X over S-Y, times, open bracket, q-W q-X plus q-bias, close bracket, plus Z-Y.
Multiply the integers q-W and q-X and add up the products. Add q-bias. Multiply the sum once by the rescale factor, round, and add Z-Y.
Made-up toy: q-W = (2, −1) and q-X = (5, 7) give 10 − 7 = 3. With q-b = 10 and Z-X = 3, q-bias = 10 − 3 × 1 = 7. The rescale is 0.02 × 0.05 / 0.005 = 0.2. So q-Y = 0.2 × 10 + 1 = 3, which reads back as 0.005 × (3 − 1) = 0.010. Float math also gives 0.010.
Each row is one step of the chip. Warm numbers are integers. The last row turns the result back into a real number and compares it with float math.
Toy numbers made up for this lesson: two weights, one output. The ruler gaps are chosen so the arithmetic is easy to follow. The real layer does the same steps over hundreds of inputs. Output is clamped to the signed 8-bit range.
pythonimport numpy as np def quantized_linear(qX, qW, qb, SW, SX, SY, ZX, ZY, bits=8): # qX (n_in,) int, qW (n_out, n_in) int, qb (n_out,) int32 q_bias = qb - ZX * qW.sum(axis=1) # folded once, offline acc = qW.astype(np.int32) @ qX.astype(np.int32) + q_bias # 32-bit accumulator qY = np.round(acc * (SW * SX / SY)) + ZY # rescale, then zero point return np.clip(qY, -2**(bits-1), 2**(bits-1) - 1).astype(np.int8)
Symptom: every output sits too high by the same amount. Measure: in the toy, use qb = 10 as qbias. The sum becomes 13, the rescale gives 2.6, and qY = 4, which reads 0.015, not 0.010. Fix: always fold ZX times the weight sum into the bias.
Chapter 2
Watch a quiet channel vanish when a loud channel sets the ruler, then see why more scales fix it
A school measures every student with one ruler. The tallest is 190 cm, so the marks are 10 cm apart. A 98 cm kindergartner reads as 100 cm, give or take.
Post-training quantization must choose S and Z for every tensor. The slide splits the job into three topics: granularity (how many numbers share one scale), range clipping (how far the ruler reaches) and rounding. Chapters 2 to 4 cover granularity.
Per-tensor quantization gives the whole weight tensor one scale. It is symmetric, so Z = 0, and the largest absolute weight sets the reach. The slide's verdict: it works well for large models, and accuracy drops for small ones.
The cause is outlier channels. A convolution weight has shape (co, ci, kh, kw), and each of the co output channels is one filter. In MobileNetV2's first depthwise-separable layer, the slide shows channel ranges that differ by more than 100 times. A depthwise convolution gives each channel its own small filter, so nothing pulls the ranges together.
Take three channels whose largest weights are 0.3, 0.5 and 30, at 8 bits, so qmax = 127.
Blue dots are the quiet channel's weights. Purple marks are the storable values. Raise the loud channel's size and watch the marks spread apart.
Illustrative: the quiet channel's largest weight is 0.30. The loud channel's largest weight is 0.30 times the number you choose. Quantization is symmetric. The 75 times default echoes the lecture's MobileNetV2 plot, where ranges differ by more than 100 times.
At 75 times and 8 bits, the shared marks sit 0.177 apart. The quiet channel lies within ±0.30, so its weights snap to five values. Per channel packs the marks 75 times closer.
pythonimport numpy as np def scales(W, bits=8, per_channel=False): # W (co, ci, kh, kw) float qmax = 2 ** (bits - 1) - 1 if per_channel: return np.abs(W).max(axis=(1, 2, 3)) / qmax # (co,) one scale per output filter return np.abs(W).max() / qmax # scalar, one for the tensor def fake_quant(W, S, bits=8): qmax = 2 ** (bits - 1) - 1 S = np.reshape(S, (-1, 1, 1, 1)) if np.ndim(S) else S return np.clip(np.round(W / S), -qmax, qmax) * S
Symptom: the quantized model runs, and its predictions are noise. Measure: MobileNetV1 falls from 70.9 percent in float to 0.1 percent after INT8 PTQ with asymmetric per-tensor scales. Fix: keep the outlier, because it is a real weight, and give each output channel its own scale (next chapter).
Chapter 3
Quantize the lecture's 4 by 4 matrix to 2 bits both ways, and count exactly where the error goes
A tailor can cut every suit from one pattern, or measure each customer. Per-channel quantization measures: each output channel, one row of W, gets a scale from its own largest absolute weight.
The slide quantizes a 4 by 4 matrix at 2 bits, symmetric. Then qmax = 21 − 1 = 1, so the only integers are −1, 0 and 1.
| Scope | Row 2 scale | Row 2 integers | Row 2 read back | Whole-matrix error |
|---|---|---|---|---|
| Per tensor | 2.12 (the tensor's largest) | 0, 1, 0, 0 | 0, 2.12, 0, 0 | 2.28 |
| Per channel | 1.92 (the row's largest) | 0, 1, 0, −1 | 0, 1.92, 0, −1.92 | 2.08 |
The cell −1.03 is the difference. Divided by 2.12 it gives −0.49 and rounds to 0. Divided by 1.92 it gives −0.54 and rounds to −1.
How far is the read-back matrix from W? Call the weight in row i and column j Wij, its stored integer qij, and its row's scale Si. The slide measures the gap with the Frobenius norm:
The Frobenius norm of W minus S circle-dot q-W equals the square root of the sum over i and j of, W-i-j minus S-i q-i-j, squared.
Read each cell back as S-i times q-i-j. Subtract it from W-i-j and square the gap. Add all 16 squares and take the square root.
From the slide: the squared gaps add to 5.22 per tensor and 4.32 per channel. The square roots are 2.28 and 2.08, so per channel cuts the error by about 9 percent.
Large numbers are what comes back after quantizing. Small numbers are the original. Warmer cells have more error. The purple number on the right is the row's scale.
The matrix is the one in the lecture's per-channel example. At 2 bits the totals are the lecture's 2.28 (per tensor) and 2.08 (per channel). The other bit widths are computed here with the same rule.
The gain is small here because the four rows have similar ranges, 1.87 to 2.12. It grows with the spread, as in Chapter 2.
Inside one output, the chip sums qW times qX over the inputs. A weight scale belongs to the output row, so it multiplies the finished sum once. A scale for each input channel would sit inside the sum: one float multiply per product. So weights get a scale per output channel, activations one per tensor.
The extra scales are cheap. A 3 by 3 convolution with 128 inputs and 256 outputs has 294,912 weights, 294,912 bytes at 8 bits. Its 256 float scales add 1,024 bytes, or 0.35 percent.
pythonimport numpy as np W = np.array([[2.09, -0.98, 1.48, 0.09], [0.05, -0.14, -1.08, 2.12], [-0.91, 1.92, 0.0, -1.03], [1.87, 0.0, 1.53, 1.49]]) qmax = 2 ** (2 - 1) - 1 # 1 at 2 bits S_t = np.abs(W).max() / qmax # 2.12, a scalar S_c = np.abs(W).max(axis=1, keepdims=True) / qmax # (4, 1): 2.09, 2.12, 1.92, 1.87 for S in (S_t, S_c): q = np.clip(np.round(W / S), -qmax, qmax) print(np.linalg.norm(W - S * q)) # 2.28, then 2.08
Symptom: one channel's outputs come out as not-a-number values. Measure: a row whose largest weight is 0 gets S = 0, and the division fails. Fix: clamp the scale to a tiny positive number such as 1e−8.
Chapter 4
Trade accuracy against storage by choosing a group size, and see how two-level scales keep the bill small
One large weight in a row of 4,096 wastes the ruler for the other 4,095. In a group of 16, it wastes it for 15. Group quantization (per-vector quantization) splits each row into groups of, say, 16 or 128 weights, each with its own scale.
The slide's reason is hardware. NVIDIA Blackwell GPUs support micro-tensor scaling for FP4, and their FP4 tensor core gives 2 times the peak throughput of the FP8, FP6 and INT8 cores. Four-bit numbers are fast, and they only work with fine scales.
The chip stores every scale. The effective bit width is the bits per weight plus the scale bits divided by the group size.
| 4-bit weights, 16-bit float scale for every | Effective bits per weight |
|---|---|
| 128 weights | 4 + 16/128 = 4.125 |
| 16 weights | 4 + 16/16 = 5 |
| 1 weight | 4 + 16/1 = 20, worse than the 16-bit float you started with |
VS-Quant (per-vector scaled quantization, Dai et al.) makes most scales cheap. Call the expensive floating-point scale, stored once for a tensor or a channel, γ. Call the small integer scale stored for each vector Sq. The rule becomes:
r equals gamma times S-q times, open bracket, q minus Z, close bracket.
Multiply the coarse scale gamma by the group's integer S-q. That is the group's gap between marks. Multiply it by q minus Z.
With made-up numbers gamma = 0.01, S-q = 12, q = −5 and Z = 0: r = 0.01 × 12 × (−5) = −0.6. The slide's cost: a 4-bit S-q for every 16 weights gives 4 + 4/16 = 4.25 effective bits.
More levels multiply in more scales, each with its own group size and data type. In the MX formats (Rouhani et al.) every scale is a power of two, so applying it is a bit shift. In a type name, S is a sign bit, E an exponent bit and M a mantissa bit.
| Approach | Element | Level 0 scale | Level 1 scale | Effective bits |
|---|---|---|---|---|
| Per-channel INT4 | INT4 | FP16, per channel | none | 4 |
| VSQ | INT4 | UINT4 per 16 | FP16 per channel | 4 + 4/16 = 4.25 |
| MX4 | S1M2 (3 bits) | E1M0 per 2 | E8M0 per 16 | 3 + 1/2 + 8/16 = 4 |
| MX6 | S1M4 (5 bits) | E1M0 per 2 | E8M0 per 16 | 5 + 1/2 + 8/16 = 6 |
| MX9 | S1M7 (8 bits) | E1M0 per 2 | E8M0 per 16 | 8 + 1/2 + 8/16 = 9 |
Thin purple lines mark group borders. Every weight is stored in 4 bits. Pick a group size, then pick a float scale or a two-level scale.
Illustrative: 64 made-up weights, 61 of them small and 3 large outliers about 8 times bigger. Elements use symmetric 4-bit values. The two-level mode follows the VS-Quant rule: one float γ for the whole vector, and each group stores an integer from 1 to 15 times γ. Effective bits are 4 plus scale bits divided by group size.
At groups of 2 the error is lowest, but a 16-bit scale costs 8 extra bits per weight. The 4-bit integer scale costs 2.
pythonimport numpy as np def group_quant(w, g, bits=4, scale_bits=None): # w (n,), n divisible by g qmax = 2 ** (bits - 1) - 1 G = w.reshape(-1, g) # (n/g, g) s = np.abs(G).max(axis=1, keepdims=True) / qmax # one float scale per group if scale_bits: # two-level: gamma * integer k = 2 ** scale_bits - 1 gamma = s.max() / k s = gamma * np.clip(np.round(s / gamma), 1, k) q = np.clip(np.round(G / s), -qmax, qmax) return (q * s).reshape(-1), bits + (scale_bits or 16) / g # values, effective bits
Symptom: the model is accurate and no smaller than FP8. Measure: 4-bit weights with a 16-bit scale for each pair cost 4 + 8 = 12 bits. Fix: use a larger group, or store the scales in fewer bits, as VSQ and MX do.
Chapter 5
Compare four ways to pick the range of an activation, and see why cutting off a few extreme values can lower the error
Weights are fixed after training. Activations, the numbers between layers, change with every input, so you measure their range before deployment, in one of two ways.
Track the range with an exponential moving average (EMA). Call the largest value seen in training step t r(t), the running estimate r̂(t), and the blending weight α.
r-hat at step t equals alpha times r at step t, plus one minus alpha, times r-hat at step t minus one.
Take alpha of the new maximum r and one minus alpha of the old estimate r-hat. Add them. That is the new r-hat.
With made-up maxima 4.4, 3.8, 9.0 and 4.1, alpha = 0.1 and a start of 4.0, r-hat goes 4.04, 4.016, 4.51, 4.47. A plain maximum would jump to 9.0 and stay there.
Run a few calibration batches through the trained float model and record each layer's activations. Pick a threshold T. Values beyond T are cut to T: clipping error. Values inside snap to marks T / qmax apart: rounding error. A higher T means less clipping error and more rounding error.
| How to pick T | What it does | Source on the slides |
|---|---|---|
| Mean of min and max | Averages each sample's min and max over the batches | Distiller |
| Minimize MSE | Picks the T with the smallest mean squared error between X and its quantized copy Q(X). For a Laplace curve with scale b, the best T is 2.83 b, 3.89 b and 5.03 b at 2, 3 and 4 bits. Estimate b from calibration data | Banner et al., NeurIPS 2019 |
| OCTAV | Finds the MSE threshold on real data by Newton-Raphson. At int4: ResNet-50 75.84 (float 76.07), MobileNet-V2 70.88 (71.71), BERT-Large 87.09 (91.00) | Sakr et al., ICML 2022 |
| Minimize KL | Picks the T that loses the least information, below | TensorRT, Migacz 2017 |
Call the float activation histogram P, the quantized one Q, and the histogram bins xi. The KL divergence measures how much information Q loses:
D-K-L of P parallel Q equals the sum over i of P of x-i, times the log of P of x-i over Q of x-i.
For each bin, divide the float share P by the quantized share Q and take the log. Weight it by P. Add over the bins.
With made-up shares P = (0.5, 0.3, 0.2) and Q = (0.4, 0.4, 0.2): 0.5 ln 1.25 + 0.3 ln 0.75 + 0 = 0.112 − 0.086 = 0.025 nats.
Bars count how many activations have each size. The purple line is the threshold T. Everything right of it is clipped. Compare Min/Max with the two error-minimizing methods.
Illustrative: 20,000 signed values from a Laplace curve with scale b = 1, drawn with a fixed seed. Quantization is symmetric with qmax = 2bits−1 − 1. The KL search is a simplified version of the TensorRT recipe (1,024 bins, merged into qmax levels). The slide's closed form for 4 bits is 5.03 b. The numeric sweep here may land a little differently, because the rounding grid is not identical.
pythonimport numpy as np class EMAObserver: # Type 1: during training def __init__(self, alpha=0.1): self.a, self.r = alpha, None def update(self, x): # x: one batch of activations m = float(np.abs(x).max()) self.r = m if self.r is None else self.a * m + (1 - self.a) * self.r def best_clip_mse(x, bits, n=200): # Type 2: calibration, MSE sweep qmax = 2 ** (bits - 1) - 1 best = (np.inf, None) for T in np.linspace(np.abs(x).max() / n, np.abs(x).max(), n): S = T / qmax err = np.mean((x - np.clip(np.round(x / S), -qmax, qmax) * S) ** 2) best = min(best, (err, T)) return best[1] # the threshold T
Symptom: accuracy is fine on the test set and poor in the field. Measure: the calibration images had no night scenes, so T came out too low and field activations clip. Fix: calibrate on a few hundred samples like deployment, and check accuracy after clipping.
Chapter 6
Learn why rounding every weight to its nearest mark can lose to a smarter choice, and read the INT8 scorecard that results
Four friends split a bill of 51.00 dollars, 12.75 each. Each rounds to the nearest dollar, 13, and the table pays 52.00. Each friend rounded well, and the total is wrong.
A layer adds up weight times input, so its rounding errors add up too. The slide's point: the best rounding for each weight is not the best rounding for the whole tensor.
AdaRound (Nagel et al., 2020) rounds each weight down to ⌊w⌋ or up to ⌈w⌉, to rebuild the layer's output. Call the weights W and a calibration input x. Call a trainable variable of W's shape V, and h(V) its soft up-or-down choice, squashed into (0, 1).
The argmin over V of the squared Frobenius norm of, W x minus the rounding of floor W plus h of V, times x, plus lambda times f-reg of V.
Floor every weight, add h of V, and multiply by x. Compare with the float output W x. Change V to shrink the squared gap while the penalty forces firm choices.
The slide's weights are 0.3, 0.5, 0.7 and 0.2, with a made-up x = (1.0, −0.6, 0.5, 0.8), so W x = 0.51. Nearest, h = (0, 1, 1, 0), gives −0.10, a squared gap of 0.372. The choice (0, 0, 1, 0) gives 0.50, a squared gap of 0.0001.
Blue bars are the float products w × x and their sum. Warm bars are the same with your rounding. Press a weight to flip it between down (0) and up (1).
Toy numbers: the four weights are the slide's; the input (1.0, −0.6, 0.5, 0.8) is made up for this lesson. A real layer has one input per calibration sample and AdaRound fits all of them at once. Here one input keeps the arithmetic readable, so the search can fit it too well. The marks are whole numbers.
The weight 0.5 sits halfway, so only the sum can choose its side. A real layer has millions of weights, so AdaRound trains V with gradient steps, one layer at a time. It changes only each weight's side, so the slide calls it almost post-training.
The slide tests two INT8 setups. Cells are the change in top-1 accuracy.
| Network | Setup A | Setup B |
|---|---|---|
| Weights | Symmetric, per tensor | Symmetric, per channel |
| Activations | Symmetric, per tensor, KL range | Asymmetric, per tensor, EMA range |
| GoogleNet | −0.45% | 0% |
| ResNet-50 | −0.13% | −0.6% |
| ResNet-152 | −0.08% | −1.8% |
| MobileNetV1 | not reported | −11.8% |
| MobileNetV2 | not reported | −2.1% |
Large networks lose under 1 percent. MobileNetV1 loses 11.8 percent even with per-channel weights. The slide's guess: smaller models have less representational capacity.
pythonimport numpy as np, itertools def best_rounding(w, x, S=1.0): # w (n,) floats, x (n,) one input, tiny n only lo = np.floor(w / S) target = w @ x best = None for up in itertools.product([0, 1], repeat=len(w)): # 2^n choices of down or up q = (lo + np.array(up)) * S err = abs(q @ x - target) if best is None or err < best[0]: best = (err, up) return best print(best_rounding(np.array([.3, .5, .7, .2]), np.array([1, -.6, .5, .8]))) # err 0.01, up = (0, 0, 1, 0)
Symptom: more calibration data barely helps MobileNetV1. Measure: PTQ changes the rulers and the roundings but never the weights. Fix: let the weights move, with quantization-aware training (next chapter).
Chapter 7
Keep a float shadow of every weight, round it on the way forward, and pretend the rounding is not there on the way back
A radio dial clicks between stations. A small turn changes nothing you can hear, so a rule that follows the sound never turns the knob.
Quantization-aware training (QAT) trains or fine-tunes with the quantized weights and activations in the loop. It matters most at 4 bits and fewer. Fine-tuning a trained float model usually beats training from scratch.
QAT keeps a full-precision shadow copy of the weights W. Each forward pass does fake quantization: it rounds W onto the ruler and reads it back, Q(W) = SWqW. Activations get the same; conv, batch norm and ReLU stay in full precision. Only the quantized weights ship.
Training needs the gradient gW: how the loss L changes with W. The chain rule splits it into the loss's slope at the rounded weight Q(W) and the rounding's own slope.
g-W equals d-L by d-W, which equals d-L by d-Q-of-W, times d-Q-of-W by d-W, which is zero.
Multiply the loss's slope at Q of W by the staircase's slope, which is zero. So g-W is zero and W never moves.
In the device's toy, L = (Q(w) − 0.5)2 and Q(w) = 0 at w = 0.05. So d-L by d-Q = 2 × (0 − 0.5) = −1, and g-W = −1 × 0 = 0.
The straight-through estimator (STE; Hinton's 2012 course, Bengio 2013) treats the quantizer as the identity on the way back, slope 1:
In the toy, gW = −1, so a step with learning rate 0.05 moves w from 0.05 to 0.10. STE is biased, but small pushes add up until Q(w) steps.
The staircase is Q(w). The blue dot is the float shadow w. The warm dot is what the layer sees. Each press of Step applies one gradient update.
Toy: loss = (Q(w) − 0.5)2, marks every 0.25, w clamps to ±0.75. Left: STE moves w by the learning rate times 2 (Q(w) − 0.5). Middle: the same step goes to the rounded value, which re-rounds. Right: the true slope, 0.
With STE, Q(w) steps to 0.25 once w passes 0.125, then to 0.5 past 0.375. Update the rounded weight instead and each 0.05 step, under half a mark, rounds back. The float shadow keeps the small steps.
| Network | Float | PTQ, asymmetric per-tensor | PTQ, symmetric per-channel | QAT, asymmetric per-tensor | QAT, symmetric per-channel |
|---|---|---|---|---|---|
| MobileNetV1 | 70.9% | 0.1% | 59.1% | 70.0% | 70.7% |
| MobileNetV2 | 71.9% | 0.1% | 69.8% | 70.9% | 71.1% |
| NASNet-Mobile | 74.9% | 72.2% | 72.1% | 73.0% | 73.0% |
pythonimport torch def fake_quant(w, scale, bits=8): # w: the float shadow weight (any shape) qmax = 2 ** (bits - 1) - 1 q = torch.clamp(torch.round(w / scale), -qmax, qmax) * scale # forward: on the grid inside = (w.abs() <= qmax * scale).to(w.dtype) return w * inside + (q - w * inside).detach() # backward: gradient passes where unclipped w = torch.nn.Parameter(torch.tensor(0.05)) opt = torch.optim.SGD([w], lr=0.05) for step in range(30): loss = (fake_quant(w, 0.25, bits=3) - 0.5) ** 2 opt.zero_grad(); loss.backward(); opt.step() # w moves; its rounded value follows
Symptom: some shadow weights drift out of range and never return. Measure: at w = 1.4 with a ruler that ends at 0.75, Q(w) stays 0.75, yet plain STE still passes the gradient. Fix: zero the gradient outside the range, as the code's mask does.
Chapter 8
Replace multiplies with sign flips and bit counts, and measure what binary and ternary weights cost in accuracy
Can quantization go to 1 bit? Binary and ternary quantization stores each weight in 1 or 2 bits and computes with bit operations.
Take the slide's weights (8, −3, 5, −1) and input (5, 2, 0, 1): 40 − 6 + 0 − 1 = 33, from four multiplies. With weights of ±1 it is 5 − 2 + 0 − 1 = 2, with no multiplies: about 32 times less memory and 2 times less compute.
Make the inputs ±1 too. Then a product is +1 when the signs agree, else −1. Store +1 as bit 1 and −1 as bit 0. XNOR gives 1 for equal bits, and popcount counts the 1 bits in a word. With n terms and A agreements, the sum is A − (n − A) = 2A − n:
y-i equals minus n, plus popcount of W-i xnor x, shifted left by one.
XNOR the weight bits with the input bits. Count the ones with popcount. Double the count with a shift and subtract n.
The slide's bits: 1010 xnor 1101 = 1000, so popcount is 1. y = −4 + (1 « 1) = −2, the same as 1 − 1 − 1 − 1. The slide counts about 32 times less memory and 58 times less compute.
Press a sign to flip it between plus one and minus one. The first row of numbers is the product of each pair. The bottom row is the XNOR of the two bits.
The default signs are the slide's example, which gives −2. A real chip packs 32 or 64 such bits into one word, so one XNOR and one popcount replace 32 or 64 multiplies.
Sign has zero slope almost everywhere, so BinaryConnect (Courbariaux et al., 2015) trains a float copy with the straight-through trick. XNOR-Net (Rastegari et al., 2016) restores magnitude with one scale α, the average absolute weight. On the lecture's matrix α = 1.05, and the squared error falls from 9.28 to 9.24.
| Rule | How a weight r becomes q | Cost |
|---|---|---|
| Sign | +1 if r is 0 or more, else −1 | 1 bit |
| Stochastic | BinaryConnect: +1 with probability p = min(max((r + 1)/2, 0), 1), else −1 | 1 bit; the hardware must make random bits |
| Ternary (TWN) | rt above Δ, 0 within ±Δ, −rt below −Δ. Δ = 0.7 × mean |r| = 0.73; rt = mean |r| of the 11 survivors = 1.5 | 2 bits: the smallest whole width for 3 values |
| Trained ternary (TTQ) | As TWN, with two learned scales, wp above and wn below | 2 bits |
Large numbers are what comes back. Small numbers are the original. Pick a rule. For ternary, slide the cutoff factor.
The matrix is the lecture's example. Errors are squared Frobenius norms, as on the slide: 9.28 for sign only and 9.24 with the scale 1.05. The cutoff factor only applies to ternary; the lecture's value is 0.7. Sign of zero is taken as +1.
| Method (AlexNet, ImageNet top-1 change) | Weights | Activations | Change |
|---|---|---|---|
| BinaryConnect | 1 bit | 32 bits | −21.2% |
| BWN (binary weights, with a scale) | 1 bit | 32 bits | 0.2% |
| BNN (both binary, no scales) | 1 bit | 1 bit | −28.7% |
| XNOR-Net (both binary, with scales) | 1 bit | 1 bit | −12.4% |
ResNet-18 top-1 on the slides: 69.6 percent in float, 60.8 BWN, 65.3 TWN and 66.6 TTQ.
pythonimport numpy as np def binarize(W): # W (co, ci) float B = np.where(W >= 0, 1.0, -1.0) return B, np.abs(W).mean() # signs, and alpha = ||W||_1 / n def ternarize(W, k=0.7): delta = k * np.abs(W).mean() keep = np.abs(W) > delta rt = np.abs(W)[keep].mean() # mean of the weights that survive return np.sign(W) * keep, rt def xnor_dot(bw, bx): # bw, bx: 0/1 arrays of the same length n agree = 1 - (bw ^ bx) # XNOR return -len(bw) + (agree.sum() << 1) # -n + popcount << 1 print(xnor_dot(np.array([1,0,1,0]), np.array([1,1,0,1]))) # -2
Symptom: a network fine with 1-bit weights falls apart with 1-bit activations. Measure: on AlexNet, +0.2 percent (BWN) becomes −28.7 percent (BNN). Fix: scales on both sides, as in XNOR-Net (−12.4 percent), or wider activations.
Chapter 9
Spend a fixed memory budget unevenly across layers, and see why the search must ask the real hardware
Uniform quantization gives every layer the same bits, 8 for weights and 8 for activations in the slide's picture. Mixed-precision quantization lets each layer choose: the slide's three layers get 4/5, 6/7 and 5/4 bits (weights/activations).
Layers differ in sensitivity, how much the output changes when you round that layer. They also differ in cost, the memory or time that each bit takes. A bit is a bargain where sensitivity is high and cost is low.
The choices explode. With 1 to 8 bits for weights and for activations, one layer has 8 × 8 = 64 choices, and n layers have 64n. For 20 layers that is about 1.3 × 1036.
HAQ (hardware-aware automated quantization, Wang et al., CVPR 2019) lets an actor-critic agent search. At each layer it sees a state that describes the layer and takes an action, the bit widths. A reward scores the finished model. A hardware accelerator (BitFusion edge, BISMO edge or cloud) runs each choice and sends back direct feedback.
A formula guesses the cost; the chip measures it. These accelerators handle one bit per cycle, so fewer bits in a weight or an activation means fewer cycles.
Each row is a layer: its parameters, then its bit width as filled cells, then its share of the noise. Drag a slider to change a layer. Press Search to let a greedy rule spend the budget.
Illustrative toy: parameters (millions) 0.05, 0.4, 1.2, 2.4 and 1.0; made-up sensitivities 8, 4, 2, 1 and 3. Noise is the sum of sensitivity times 4 to the power of minus bits, times 100, because each extra bit cuts rounding noise power by 4. Memory is parameters times bits over 8. This is a weight-only memory budget. HAQ searches weights and activations and uses real hardware feedback.
Uniform 4 bits uses 2.525 MB with a noise score of 7.03. The search keeps 2.525 MB and finds (8, 7, 4, 3, 5) with noise 2.67, 2.6 times lower. Brute force over the toy's 16,807 settings agrees. At 64n it cannot, so HAQ learns.
On MobileNetV1, read from the slide's latency plot: at about 45 ms HAQ reaches 67.4 percent against 62.4 for uniform. At 58 ms it is 70.6 against 67.0, and at 70 ms 71.2 against 70.5. HAQ also leads under size and energy limits.
pythonimport numpy as np params = np.array([.05, .4, 1.2, 2.4, 1.0]) # millions of weights per layer (toy) sens = np.array([8, 4, 2, 1, 3]) # made-up sensitivities size = lambda b: (params * b / 8).sum() # MB noise = lambda b: (sens * 4.0 ** -b).sum() * 100 def greedy(budget): b = np.full(len(params), 2) while True: # add the bit with the best noise cut per MB gain = [sens[i] * (4.0 ** -b[i] - 4.0 ** -(b[i] + 1)) / (params[i] / 8) if b[i] < 8 and size(b + np.eye(len(b), dtype=int)[i]) <= budget + 1e-9 else -1 for i in range(len(b))] i = int(np.argmax(gain)) if gain[i] < 0: return b b[i] += 1 print(greedy(size(np.full(5, 4)))) # [8 7 4 3 5]
Symptom: the model is half the size and no faster. Measure: size, latency and energy each get their own plot and their own best bits. Fix: name the cost you care about, and measure it on the target chip.
Chapter 10
Review the numbers, the terms and the code, then pick a recipe for the model in front of you
Post-training quantization makes three choices: granularity (per tensor, per channel or per group), range (min/max, EMA, MSE or KL) and rounding (nearest or AdaRound). When that is not enough, as for MobileNetV1 at 59.1 percent, quantization-aware training fake-quantizes on the way forward and passes the gradient straight through on the way back. Binary and ternary weights replace multiplies with sign flips, XNOR and popcount. Across layers, a hardware-aware search such as HAQ picks the bits.
| What | Number | Why it matters |
|---|---|---|
| 2-bit example matrix: S and Z | S = 1.07, Z = −1 | Zero maps to q = −1 and stays exact (Ch 1) |
| Integer layer, toy | qY = 3, Y = 0.010 | Integer path matches float math (Ch 1) |
| Skipping the zero-point constant | 0.015 against 0.010 | 50 percent too high (Ch 1) |
| Accumulator width, 8-bit inputs, 512 terms | about 25 bits | The sum needs a 32-bit accumulator (Ch 1) |
| Per-tensor scale with a 30 outlier, 8 bits | S = 0.236; 0.1 rounds to 0 | The loud channel erases the quiet one (Ch 2) |
| 2-bit matrix error | 2.28 per tensor, 2.08 per channel | Per channel is better, mildly here (Ch 3) |
| VSQ, 4-bit values, 4-bit scale per 16 | 4.25 effective bits | Count the scales in the width (Ch 4) |
| MX4, MX6, MX9 | 4, 6 and 9 effective bits | Shared power-of-two scales (Ch 4) |
| Optimal Laplace clip, 2, 3, 4 bits | 2.83 b, 3.89 b, 5.03 b | Clipping beats min/max at low bits (Ch 5) |
| OCTAV at 4 bits (float to INT4) | ResNet-50 76.07 to 75.84; BERT-Large 91.00 to 87.09 | Good clipping holds large models (Ch 5) |
| Rounding, slide's four weights | error 0.61 nearest, 0.01 best | Round for the layer (Ch 6) |
| QAT on a K-means codebook | centroids 2.00, 1.50, 0.00, −1.00 become 1.96, 1.48, −0.04, −0.97 | Summed cluster gradients update the shared values (Ch 7) |
| MobileNetV1, float 70.9% | 0.1 per-tensor, 59.1 per-channel PTQ, 70.7 QAT | Training recovers the loss (Ch 7) |
| XNOR plus popcount, 4 terms | −4 + (1 « 1) = −2 | Bit counts replace multiplies (Ch 8) |
| AlexNet, both sides binary | BNN −28.7%, XNOR-Net −12.4% | Scales matter (Ch 8) |
| ResNet-18 top-1 | 69.6 float, 60.8 BWN, 65.3 TWN, 66.6 TTQ | More values, better accuracy (Ch 8) |
| Mixed-precision design space | 64n; 6420 is about 1.3 × 1036 | Search needs a learned agent (Ch 9) |
| Term | Meaning | Ch |
|---|---|---|
| Scale S, zero point Z | The gap between marks; the integer that means real zero | 1 |
| qbias, rescale | The folded constant; the factor SWSX/SY | 1 |
| Per-tensor, per-channel, group | How many weights share one scale | 2 to 4 |
| Effective bit width | Bits per weight, scales included | 4 |
| VS-Quant, MX | Two-level scales; shared power-of-two exponents | 4 |
| Calibration, EMA | Measuring activation ranges on sample data; a running average of them | 5 |
| Clipping, KL divergence, MSE | Cutting the tail; information loss; squared error | 5 |
| AdaRound | Choosing round up or down to match the layer output | 6 |
| QAT, fake quantization, shadow weights | Training with rounding in the forward pass; float copy that gets the updates | 7 |
| Straight-through estimator | Backward pass treats the quantizer as the identity | 7 |
| XNOR, popcount | Equal-bit test; number of 1 bits | 8 |
| BWN, BNN, XNOR-Net, TWN, TTQ | Binary weights; both binary; scaled both binary; ternary; trained ternary | 8 |
| Mixed precision, HAQ | Bits per layer; the hardware-aware actor-critic search | 9 |
The whole lecture fits in a few lines of NumPy and PyTorch. Shapes are in the comments.
pythonimport numpy as np, torch def qparams(r_min, r_max, bits): # affine: r = S (q - Z) qmin, qmax = -2 ** (bits - 1), 2 ** (bits - 1) - 1 S = (r_max - r_min) / (qmax - qmin) return S, int(round(qmin - r_min / S)) def sym_quant(W, bits, axis=None): # W (co, ci); axis=1 gives per-channel scales (co, 1) qmax = 2 ** (bits - 1) - 1 S = np.abs(W).max(axis=axis, keepdims=True) / qmax return np.clip(np.round(W / S), -qmax, qmax), S def quantized_linear(qX, qW, qb, SW, SX, SY, ZX, ZY): # qX (ci,), qW (co, ci) acc = qW.astype(np.int32) @ qX + (qb - ZX * qW.sum(1)) # 32-bit accumulator (co,) return np.round(acc * SW.reshape(-1) * SX / SY) + ZY def best_clip_mse(x, bits, n=200): # activation range by MSE sweep qmax = 2 ** (bits - 1) - 1; m = np.abs(x).max() err = lambda T: np.mean((x - np.clip(np.round(x / (T / qmax)), -qmax, qmax) * (T / qmax)) ** 2) return min(np.linspace(m / n, m, n), key=err) def fake_quant(w, scale, bits): # QAT: forward on the grid, backward = STE qmax = 2 ** (bits - 1) - 1 inside = (w.abs() <= qmax * scale).to(w.dtype) q = torch.clamp(torch.round(w / scale), -qmax, qmax) * scale return w * inside + (q - w * inside).detach() def xnor_dot(bw, bx): # bits in {0, 1}, same length n return -len(bw) + ((1 - (bw ^ bx)).sum() << 1)
Run these on the worked examples and you get S = 1.07 and Z = −1 for the 2-bit matrix. You also get 2.08 for its per-channel error, qY = 3 for the toy layer, and −2 for the XNOR sum.
Lecture 5 introduced the ruler: K-means and linear quantization. Lecture 7 turns to a different lever: searching for architectures that need fewer numbers to begin with. Mixed precision is already a search, so it will feel familiar.
This lesson follows Lecture 6 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The slides, schedule and other lectures are on the course page. The ideas are re-taught here in our own words, with our own devices and toy numbers (marked as illustrative).
Papers the slides cite, for scales and ranges: Han et al. (ICLR 2016), Jacob et al. (CVPR 2018) and the data-free quantization paper (ICCV 2019). Also Banner et al. (NeurIPS 2019), Migacz (2017), Krishnamoorthi (2018), Sakr et al. (ICML 2022), Dai et al. and Rouhani et al. For rounding and training: Nagel et al. (2020), Hinton et al. (2012) and Bengio (2013). For low bits and search: Courbariaux et al. (2015, 2016), Rastegari et al. (2016), Li et al. (2016), Zhu et al. (2017) and Wang et al. (CVPR 2019).
Now press Teach and explain, from memory, why a float shadow weight lets a rounded weight learn, and why a per-channel scale can sit outside the integer sum. Then go back to the layer at the top and drag the bits down once more.