Store a network's weights in 2 bits, not 32, and a layer shrinks 3.2 times. The catch is which few values you keep, and whether the math can stay in integers.
Learn how a network keeps its weights in fewer bits, the two main ways to choose the values it keeps, and why one of them lets the arithmetic itself run on integers.
Pick a method, then drag the bit slider. Watch the weights snap onto fewer and fewer values, and watch the size and the error move. Then we build, piece by piece, the number formats, the codebook, and the scale and zero point.
You need a little arithmetic (what a bit is, what a matrix times a vector does) and a little Python for the code. We build the rest from zero.
Based on Lecture 5 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture 5 slides. Every idea is re-taught here in our own words and devices. It follows Lecture 4, Pruning II and leads into Lecture 6, Quantization II.
The sixteen weights are the 4 by 4 example from the lecture slides. At 2 bits the K-means codebook is the slide's (−1, 0, 1.5, 2) and the linear scale and zero point are the slide's (1.07, −1). Other bit widths are computed live here. Sizes count the indices or integers plus the codebook, or plus one 32-bit scale and one zero point.
Chapter 0
See why a smaller number is cheaper to add and multiply, and meet the plan for the whole lecture
You point your phone at a plant and a small network names it. Behind that blink the chip did millions of additions and multiplications, and each one drew current from the battery. What does one piece of arithmetic cost, and can we make it cheaper?
A computer stores a number as a row of bits, switches that are 0 or 1. A 32-bit adder is a circuit 32 switches wide; an 8-bit adder is a quarter as wide. The lecture's table is from Mark Horowitz's ISSCC 2014 talk, for a 45 nm chip at 0.9 V. Its unit is the picojoule (pJ), a millionth of a millionth of a joule.
| Operation | Energy (pJ) |
|---|---|
| 8-bit integer add | 0.03 |
| 32-bit integer add | 0.1 |
| 16-bit float add | 0.4 |
| 32-bit float add | 0.9 |
| 8-bit integer multiply | 0.2 |
| 32-bit integer multiply | 3.1 |
| 16-bit float multiply | 1.1 |
| 32-bit float multiply | 3.7 |
An 8-bit integer add costs 30 times less than a 32-bit float add, as the slide's arrow says. For multiplies the slide marks 16 times; our own division, 3.7 / 0.2, gives about 18. Two more gaps matter later: a multiply costs far more than an add, and a float costs more than an integer of the same width.
Slide 4 asks how to make deep learning more efficient. The table's answer is quantization. It forces values that could be almost any number onto a short list of allowed numbers, so each needs fewer bits. This lecture covers the number formats, then two methods: K-means-based quantization and linear quantization. Binary and ternary quantization wait for Quantization II.
A multiply-add is one multiply then one add, the basic step of every layer. A layer with 1,000 inputs and 1,000 outputs does 1,000,000 of them per pass. In FP32 each costs 3.7 + 0.9 = 4.6 pJ, so a pass costs 4.6 microjoules. In INT8 each costs 0.2 + 0.03 = 0.23 pJ: 20 times less.
Each bar is the energy of one multiply-add in a format. Pick a format, then drag the slider to set how many multiply-adds the network does.
Energies from the lecture's table. One multiply-add is one multiply plus one add of the same format, our own simplification. Memory traffic is not counted, so a real chip spends more.
At 1,000 million multiply-adds, FP32 costs about 4.6 millijoules and INT8 about 0.23. The price is accuracy: squeezing a float into 8 bits changes the number. The rest of the lecture is about changing it as little as possible.
Chapter 1
Read a row of eight bits three different ways, then slide a decimal point into it
A row of eight switches means nothing alone. You choose how to read it. Slide 5 calls the reading rules numeric data types.
Each switch has a place value that doubles from the right: 1, 2, 4, up to 128. An unsigned integer adds the place values of the switches that are up, so 00110001 = 32 + 16 + 1 = 49. Eight bits count from 0 to 255.
Weights can be negative. Sign-magnitude spends the leftmost bit on the sign, so 10110001 is −49. Its flaw: 00000000 and 10000000 both mean zero. Two's complement, the standard on nearly every chip, keeps every switch a place value but makes the leftmost one negative. Call the number of bits n, and the bit in place i (0 or 1) bi.
Value equals minus b n-minus-one times two to the n minus one. Then add the sum over i from zero to n minus two of b-i times two to the i.
If the leftmost bit b n-minus-one is up, start at minus 128. Add the place value 2 to the i of every other bit b-i that is up.
The lecture's 11001111 with n = 8: −128 + 64 + 8 + 4 + 2 + 1 = −49. Read as unsigned, the same switches give 207.
Eight bits then hold −128 to 127 with one zero. One adder circuit serves signed and unsigned numbers: on an 8-bit counter, 5 + 253 wraps to 2, and 253 is the pattern for −3.
Press the bit buttons to flip them, left bit first. Then choose a reading. The boxes show each switch's place value and what it adds.
The fixed-point reading puts the decimal point 4 bits from the right and uses two's complement for the integer part, as on slide 7. The two examples 00110001 and 11001111 are the lecture's.
Try 10000000: negative zero in sign-magnitude, −128 in two's complement.
A fixed-point number is an integer with an agreed decimal point inside it. Slide 7 puts the point 4 bits from the right, so 00110001 reads 49 × 2−4 = 49 × 0.0625 = 3.0625. Every value is a multiple of 0.0625, from −8 to 7.9375. More fraction bits give a finer step and less range.
Carry this forward: an integer times a fixed real step. Linear quantization in Chapter 7 turns that step into a tunable scale.
The failure is overflow. Symptom: in INT8, 127 + 1 gives −128. Measure: 01111111 + 00000001 = 10000000, off by 256. Fix: add in a wider integer, or clamp at 127. Chapter 10 does both.
Chapter 2
Open a 32-bit float, read its three fields, and find where zero, tiny numbers and infinity hide
Scientific notation writes 9.11 × 10−31: the digits and the scale sit apart. A floating-point number does the same in binary, with a layout fixed by IEEE 754. Its 32-bit form, FP32, has three fields.
One bit is the sign. Eight bits are the exponent, an unsigned integer from 0 to 255. Twenty-three bits are the fraction (the mantissa), a value from 0 to just under 1. A normal number has an exponent field that is not 0.
Value equals minus one to the sign, times one plus fraction, times two to the exponent minus one hundred twenty-seven.
Read the fraction bits as halves, quarters, eighths and add 1. Subtract 127 from the exponent field and raise 2 to that power. Multiply the two, and apply the sign.
Slide 8's 0 01111101 00010000000000000000000: sign 0, exponent 125, fraction 2−4 = 0.0625. Value = 1.0625 × 2125−127 = 0.265625.
With a hidden 1, no normal number can be zero (slide 9). So exponent field 0 marks a subnormal number: no hidden bit, and a fixed scale.
Value equals minus one to the sign, times fraction, times two to the one minus one hundred twenty-seven.
Multiply the bare fraction by 2 to the minus 126. An all-zero fraction now gives 0, with a +0 and a −0.
Only the last bit up: 2−23 × 2−126 = 2−149, about 1.4 × 10−45. All bits up: (1 − 2−23) × 2−126, one step below the smallest normal, 2−126, so there is no gap.
Exponent field 255 holds ±∞ (zero fraction) and not-a-number, NaN (any other fraction), the answer to 0 / 0. Slide 15 calls the many NaN patterns "much waste" and promises to revisit them in FP8.
| Exponent field | Fraction is 0 | Fraction is not 0 |
|---|---|---|
| 0 | ±0 | subnormal |
| 1 to 254 | normal number | |
| 255 | ±∞ | not-a-number |
Set the three fields with the controls, or press a preset. The 32 boxes show the bits. Colors mark the fields: sign in yellow, exponent in purple, fraction in warm.
The fraction slider moves in steps of 1/64. The presets set all 23 bits exactly, including the subnormal and special cases of slides 10 to 15.
Press "infinity", then "not-a-number": only the fraction differs. In code, Python's struct hands you the raw bits.
pythonimport struct def fields(x): b = struct.unpack(">I", struct.pack(">f", x))[0] return b >> 31, (b >> 23) & 0xFF, b & 0x7FFFFF sign, exp, frac = fields(0.265625) # (0, 125, 524288) value = (-1)**sign * (1 + frac / 2**23) * 2**(exp - 127)
The failure is a counter that stops counting. Symptom: adding 1 to an FP32 counter freezes it near 16.8 million. Measure: at 224 = 16,777,216 the gap between neighbours is 224−23 = 2, so +1 rounds back. Fix: count in an integer or a wider type.
Chapter 3
Trade exponent bits for fraction bits and watch range and precision move in opposite directions
A float format splits a fixed budget of bits. Slide 17 puts it in one line: exponent width sets the range, fraction width sets the precision. Range is how large and how small a number can be; precision is how close two neighbours sit.
| Format | Exponent bits | Fraction bits | Total bits |
|---|---|---|---|
| IEEE FP32 | 8 | 23 | 32 |
| IEEE FP16 | 5 | 10 | 16 |
| Google Brain Float, BF16 | 8 | 7 | 16 |
FP16 is precise but tops out at 65,504. BF16 keeps FP32's 8 exponent bits, and so its range, with only 7 fraction bits. The bias is 2e−1 − 1 for e exponent bits: 15 for FP16, 127 for BF16.
Slide 18 decodes the FP16 pattern 1100011100000000:
Slide 19 encodes 2.5 in BF16: 2.5 = 1.25 × 21, so the exponent field is 1 + 127 = 128 = 10000000 and the fraction is 0100000. The answer is 0100000000100000.
Slide 20 adds two 8-bit formats from Nvidia. E4M3 (4 exponent, 3 mantissa bits) has no infinity and spends one pattern, S.1111.111, on NaN. Its largest value is S.1111.110 = 1.75 × 215−7 = 448. E5M2 keeps infinity and NaN, reaches S.11110.11 = 1.75 × 230−15 = 57,344, and serves gradients in the backward pass, where range matters most.
The top bar splits the bits into sign, exponent and fraction. The line below is the format's range on a log scale. Pick a format, then drag the value along that line.
Largest values: FP32 and BF16 about 3.4 × 1038, FP16 65,504 (from the formula), E4M3 448, E5M2 57,344 (slide 20). The gap near a value is 2 to the power (its exponent minus the fraction bits).
FP16 at 1,000: neighbours sit 0.5 apart. Slide to 100,000 and the marker turns red, because past 65,504 the value becomes infinity. BF16 holds it, with a gap of 512.
At 4 bits there are 16 patterns (slide 21). The 4-bit floats split the three non-sign bits in different ways. The slide marks E2M1 and E3M0 as having no infinity and no NaN.
| Format | Positive values | Spacing |
|---|---|---|
| INT4 | 0 to 7 (and −1 to −8) | steps of 1 |
| FP4 E1M2 | 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5 | even |
| FP4 E2M1 | 0, 0.5, 1, 1.5, 2, 3, 4, 6 | fine near 0, wide at the top |
| FP4 E3M0 | 0, 0.25, 0.5, 1, 2, 4, 8, 16 | each value doubles |
Each dot is a number the format can store. Switch formats and watch the dots bunch up near zero or spread out.
Values follow slide 21. The floats use bias 2e−1 − 1 and the subnormal rule, which reproduces the slide's lists. +0 and −0 count as one number.
The failure is overflow. Symptom: training prints NaN after a gradient spike. Measure: a gradient of 70,000 passes FP16's 65,504 and becomes infinity, and infinity minus infinity is NaN. Fix: use more exponent bits, as in BF16 or E5M2.
Chapter 4
Snap many values onto a few, store the few once, and count exactly how many bytes that saves
A paint-by-number kit keeps 16 pots of paint and a pot number for each patch. Slide 22's 16-colour cat photo does this, a trick called palettization. We do the same with weights.
Quantization constrains an input from a continuous or otherwise large set of values to a discrete set (slide 22). The gap between a value and its level is the quantization error. With levels d apart, no value lands more than d / 2 away.
The blue curve is the smooth signal. The warm steps are what you keep. The yellow bars are the error. Drag the bits.
A made-up wave between −1 and 1, quantized to evenly spaced levels. The device measures the error live. The shape matches slide 22; the numbers are ours.
Each added bit halves the step, so it halves the largest error.
Slides 23 and 24 sort the methods by what they keep and what they compute:
| Method | Stored weights | Arithmetic |
|---|---|---|
| Original | 32-bit floats | floating-point |
| K-means-based | integer indices plus a floating-point codebook | floating-point |
| Linear | integers | integer |
| Binary and ternary | 1 or 2 bits | next lecture |
Slide 26 notes that 2.09, 2.12, 1.92 and 1.87 could share 2.0. K-means finds such values: guess k centres, give each weight to the nearest, move each centre to the mean of its weights, repeat. The centres are centroids, and their list is the codebook (Deep Compression, Han et al., ICLR 2016).
For slide 25's 4 by 4 block with k = 4, the codebook is 2.00, 1.50, 0.00 and −1.00, numbered 3 down to 0. Each weight becomes a 2-bit index: 2.09 becomes 3, which decodes to 2.00, an error of 0.09. The largest error in the block is 0.14 (slide 28).
Call the weight count M and the index width N bits.
Ratio equals thirty-two M, over N M plus thirty-two times two to the N, which is about thirty-two over N.
Count the original bits, 32 per weight. Count the new bits, N per index plus 32 per centroid. Divide the first count by the second.
Slide 28: M = 16, N = 2 gives 512 / (32 + 128) = 3.2, so 64 bytes become 20. With M = 1,000,000 and N = 4 the ratio is 8.0.
Blue is the original, warm the indices, purple the codebook. Set the weight count and the index bits.
The 16-weight, 2-bit example is slide 28's. Other settings follow the formula. Bars share one scale.
Drag M toward a million: the codebook bar vanishes and the ratio nears 16.
The failure sits at small M. Symptom: a tiny layer quantized to 4 bits grows. Measure: M = 16 and N = 4 need 64 bits of indices plus 512 bits of codebook, 72 bytes against 64. Fix: share one codebook across a big tensor.
pythonimport numpy as np def kmeans_quantize(w, bits, iters=20): k = 2**bits c = np.quantile(w, (np.arange(k) + 0.5) / k) # k starting centroids for _ in range(iters): idx = np.abs(w[:, None] - c[None, :]).argmin(1) # nearest centroid per weight c = np.array([w[idx == j].mean() if (idx == j).any() else c[j] for j in range(k)]) idx = np.abs(w[:, None] - c[None, :]).argmin(1) return idx.astype(np.uint8), c # indices (N bits each) + codebook w_hat = c[idx] # decode: a table lookup
Chapter 5
Give every weight in a cluster the same nudge, and see the spikes that quantization leaves in a histogram
A little retraining after snapping wins accuracy back (slides 29 and 30). Training needs one gradient per weight: how the loss changes if that weight moves a little. But weight i is a copy of centroid k(i). Move the centroid and all its weights move, so its gradient is the sum of theirs.
Call centroid number k ck, the step size (the learning rate) η, and the gradient for weight i ∂L/∂wi.
c-k becomes c-k minus eta times the sum, over every i whose index is k, of d L by d w-i.
Group the gradients by index. Add each group. Multiply the sum by eta and subtract it from that group's centroid c-k.
Slide 30 with eta = 1: centroid 3 owns gradients −0.03, 0.12, 0.02 and −0.07, sum 0.04, so 2.00 becomes 1.96. The other sums, 0.02, 0.04 and −0.03, give 1.48, −0.04 and −0.97.
Above: slide 29's gradients. Only the centroids change; the indices stay, so the file size stays.
Each square is a weight, coloured by cluster, with its gradient inside. The right side shows the four centroids before and after. Drag the learning rate, or untie the weights.
The gradients, indices and centroids are slides 29 and 30. A learning rate of 1 reproduces the slide's result. That the loss then falls is the paper's measurement, not this toy's.
Press "Untie the weights": 16 weights take 16 values, and the 3.2 times saving is gone.
Does it work? Slides 31 to 33 plot AlexNet's ImageNet accuracy loss against model size after compression. Reading the plot, quantization alone stays within about half a point down to about 8 percent of the original size. Pruning plus quantization holds near zero loss down to about 3 percent.
Slide 34 is a histogram of one layer's weights, a count per narrow slice of value: two smooth humps near −0.025 and +0.025. After quantization (slide 35) they become spikes, one per centroid. After retraining (slide 36) the spikes barely move.
Blue is a toy layer of 2,000 weights. Press the second button to snap every weight to the nearest centroid and drag the bits.
A made-up layer: 2,000 weights from two bell curves at −0.025 and 0.025. K-means runs live. Retraining is not simulated.
The failure is silent untying. Symptom: after fine-tuning, the file is no longer smaller. Measure: count the distinct values in the weight tensor; thousands instead of 16 means the weights came untied. Fix: update the centroids only, then rebuild the weights by index lookup each step.
pythong = np.bincount(idx, weights=grad.ravel(), minlength=k) # group by index and sum c = c - lr * g # one update per centroid w = c[idx].reshape(grad.shape) # rebuild the tied weights
Chapter 6
Stack three tricks, give common symbols short codes, and shrink AlexNet from 240 MB to 6.9 MB
In Morse code E, the most common letter, is one dot. Common things get short names. That is the third trick of Deep Compression (Han et al., ICLR 2016), which stacks pruning, quantization and Huffman coding.
How many bits are enough? Slide 37 plots AlexNet accuracy against bits per weight. Accuracy holds, then collapses below 4 bits for convolution layers and 2 bits for fully-connected layers.
After quantization each weight is an index, and some indices are far more common than others (slide 38 plots 32 of them). Huffman coding gives frequent symbols short codes and rare ones long codes. To build it, join the two rarest symbols into one node with their summed frequency, and repeat until one node is left. A symbol's code length is its depth in that tree.
Four symbols with frequencies 0.50, 0.25, 0.15 and 0.10 get 1, 2, 3 and 3 bits. The average is 0.50 + 0.50 + 0.45 + 0.30 = 1.75 bits, against 2 for a fixed code. No code starts another, so the stream needs no separators. You decode to plain indices before running the layer.
Each bar is how often one of 16 indices is used. The number above it is its Huffman code length. Drag the skew from even use to a few common indices.
Illustrative: 16 indices whose frequencies fall off geometrically as the skew rises. The real histogram is slide 38's. The device builds the tree live.
At skew 0 every index costs 4 bits. Raise the skew and the average falls well below 4.
Slide 39 gives the order, with the same accuracy after each stage:
Pruning goes first so quantization has fewer weights to handle. Huffman goes last because it is lossless and works on whatever symbols remain.
| Network | Original size | Compressed | Ratio | Accuracy before | Accuracy after |
|---|---|---|---|---|---|
| LeNet-300 | 1070 KB | 27 KB | 40x | 98.36% | 98.42% |
| LeNet-5 | 1720 KB | 44 KB | 39x | 99.20% | 99.26% |
| AlexNet | 240 MB | 6.9 MB | 35x | 80.27% | 80.30% |
| VGGNet | 550 MB | 11.3 MB | 49x | 88.68% | 89.09% |
| GoogleNet | 28 MB | 2.8 MB | 10x | 88.90% | 88.92% |
| ResNet-18 | 44.6 MB | 4.0 MB | 11x | 89.24% | 89.28% |
No network loses accuracy (slide 40). The slide then asks: can we make compact models to begin with? SqueezeNet (Iandola et al., 2016) is one answer. Its Fire module squeezes 64 channels to 16 with a 1 by 1 convolution (slide 41). Parallel 1 by 1 and 3 by 3 convolutions then expand to 64 + 64 = 128 channels.
| Network | Approach | Size | Ratio | Top-1 | Top-5 |
|---|---|---|---|---|---|
| AlexNet | none | 240 MB | 1x | 57.2% | 80.3% |
| AlexNet | SVD | 48 MB | 5x | 56.0% | 79.4% |
| AlexNet | Deep Compression | 6.9 MB | 35x | 57.2% | 80.3% |
| SqueezeNet | none | 4.8 MB | 50x | 57.5% | 80.3% |
| SqueezeNet | Deep Compression | 0.47 MB | 510x | 57.5% | 80.3% |
Design small, then compress: SqueezeNet with Deep Compression is 510 times smaller than AlexNet at the same accuracy (slide 42).
The failure: Huffman gains little on a layer. Measure: if the layer uses the 16 indices about equally, the average code stays near 4 bits. Fix: prune first, so zeros dominate the histogram.
pythonimport heapq def huffman_lengths(freq): # freq: {symbol: probability} h = [(p, i, [s]) for i, (s, p) in enumerate(freq.items())] heapq.heapify(h); depth = {s: 0 for s in freq}; n = len(h) while len(h) > 1: p1, _, a = heapq.heappop(h); p2, _, b = heapq.heappop(h) # the two rarest for s in a + b: depth[s] += 1 # one level deeper heapq.heappush(h, (p1 + p2, n, a + b)); n += 1 return depth # code length per symbol
Chapter 7
See why a codebook leaves the math in floats, then meet the affine map that lets integers do the work
Slide 43 follows a K-means layer at run time. A lookup table turns each 2-bit index back into a 32-bit float, and the inputs, convolution, bias, output and ReLU are all floats. In the slide's words, K-means-based weight quantization only saves storage cost; all the computation and memory access are still floating-point. The 3.7 pJ multiply stays.
Linear quantization stores integer weights and computes with integer arithmetic (slide 44), the pair the energy table rewards.
Read a ruler as tick number times spacing. If real zero sits at some other tick, subtract that tick first. That multiply and shift is an affine mapping. Call the real weight r, the stored integer q, the spacing the scale S, and the tick for real zero the zero point Z.
r equals S times, q minus Z.
Take the stored integer q. Subtract the zero point Z. Multiply by the scale S to get the real weight r.
Slide 47 uses S = 1.07 and Z = −1. The weight 2.09 is stored as q = 1: r = 1.07 × (1 + 1) = 2.14, an error of −0.05. And q = −1 gives 1.07 × 0 = 0 exactly.
The slide notes that Z lets real 0 be exactly representable. That matters: zero padding and ReLU outputs must stay exactly zero, or every padded border pixel carries an error.
Each square shows the decoded weight and its error. Yellow shading marks a bigger error. A red outline means the weight lies outside the range the grid can reach.
Weights and the slide's choice (S = 1.07, Z = −1, largest error 0.46) are the lecture's. Each weight is quantized as q = round(r / S + Z), clamped to −2 to 1. Clipped means beyond the grid by more than 0.02.
At the slide's values the largest error is 0.46, for the weight 1.53. Lower S to 0.90: the largest error falls to 0.32, but the grid reaches only −0.90 to 1.80, so seven weights clip. A smaller scale buys finer steps and cuts off the ends.
At 2 bits K-means erred by at most 0.14, linear by 0.46. K-means puts its values where the weights cluster; linear spaces them evenly. Linear buys a plain integer grid, so the multiplies can stay integer.
Chapter 8
Pin the two ends of the real range to the two ends of the integer range and solve for S and Z
Slides 49 to 53 derive S and Z by gluing two number lines together at both ends. The real line runs from the smallest weight rmin to the largest rmax. The integer line runs from qmin to qmax, the two's complement range of N bits.
| Bit width | qmin | qmax |
|---|---|---|
| 2 | −2 | 1 |
| 3 | −4 | 3 |
| 4 | −8 | 7 |
| N | −2N−1 | 2N−1 − 1 |
Write r = S(q − Z) at both ends (slide 50):
Subtract the second line from the first, and the S × Z terms cancel.
S equals, r max minus r min, over, q max minus q min.
Divide the real width, r max minus r min, by the number of tick gaps, q max minus q min.
Slide 51: r runs from −1.08 to 2.12, and 2 bits give q from −2 to 1. S = 3.20 / 3 = 1.07.
Now solve the rmin line for Z, and round, because Z must name a tick.
Z equals round of, q min minus r min over S.
Count the smallest weight r min in ticks. Subtract that count from q min. Round to a whole tick.
Slide 53: Z = round(−2 + 1.08 / 1.07) = round(−0.99) = −1.
Check: real 0 maps to q = −1 and decodes to exactly 0. The ends decode to −1.07 and 2.14, not −1.08 and 2.12, because rounding Z shifted the grid a little. That buys an exact zero.
At 8 bits the same range gives S = 3.20 / 255 = 0.01255 and Z = round(−41.9) = −42. The grid is 85 times finer, so the worst rounding error, half of S, drops to about 0.006.
The thin lines are the ticks of the integer grid. The purple tick is the zero point. The yellow band is the real range your weights use. Drag the ends and the bits.
Defaults are the slide's block (−1.08 to 2.12, 2 bits). The worst rounding error inside the range is half of S.
Drag the smallest weight above 0. That is the failure. Symptom: the read-out says Z does not fit. Measure: weights from 1 to 3 at 8 bits give S = 2 / 255 = 0.00784 and Z = round(−255.5), about −256, far outside −128 to 127. Fix: widen the range to include 0; then Z = −128. You waste some grid and keep an exact zero.
pythondef linear_params(r_min, r_max, bits): q_min, q_max = -2**(bits - 1), 2**(bits - 1) - 1 S = (r_max - r_min) / (q_max - q_min) # real width per tick Z = round(q_min - r_min / S) # the tick that means real zero return S, Z S, Z = linear_params(-1.08, 2.12, 2) # (1.0667, -1)
Chapter 9
Multiply two integer matrices, then rescale with a bit shift, and see why symmetric weights save work
A layer computes Y = WX. The weights, the input and the output each get a scale and a zero point: SW and ZW, SX and ZX, SY and ZY. Slide 54 puts r = S(q − Z) in for all three:
Solve for the output integer qY and multiply out the brackets.
q Y equals S W S X over S Y, times a bracket, plus Z Y. The bracket is q W q X, minus Z W q X, minus Z X q W, plus Z W Z X.
Multiply the integer weights q W by the integer inputs q X and sum. Subtract the zero-point terms. Rescale, then add Z Y.
In the toy row below, the integer sum −5,280 becomes q Y = −71, which decodes to −0.055 against the float −0.06.
A float rescale would undo the gain. Slide 56 writes the factor as 2−n M0, with M0 in [0.5, 1). Multiply by M0 as a fixed-point integer, then bit-shift right by n places. The chip needs no floating-point unit.
If ZW = 0 (slides 57 and 60), the live-input term and the constant vanish. Symmetric linear quantization gets Z = 0 from a range of −|r|max to |r|max. In full range mode (slide 59), S = |r|max / 2N−1, so the largest weight clamps one tick short.
Toy numbers: weight row (0.5, −0.3), input (0.6, 1.2), float answer −0.06. Everything is 8-bit:
| Tensor | Real range | Scale S | Zero point Z |
|---|---|---|---|
| Weights (symmetric) | −0.8 to 0.8 | 0.8 / 128 = 0.00625 | 0 |
| Input | 0 to 2 | 2 / 255 = 0.00784 | −128 |
| Output | −0.5 to 1.5 | 2 / 255 = 0.00784 | −64 |
Each box is one step for output row 0. Purple boxes come from the weights alone; a yellow box needs the live input. Switch the weight mode.
Toy numbers from the table above. Method from slides 54 to 60.
The data runs from your chosen smallest value up to 2. The top row is the asymmetric grid, the bottom row the symmetric grid. Faded ticks fall outside the data.
Illustrative range from the slider up to 2.0. Symmetric: S = |r|max / 2N−1 (slide 59). Asymmetric: S = (r max − r min) / (2N − 1).
For data from 0 to 2 at 4 bits, the asymmetric grid uses all 16 levels with a step of 0.13. The symmetric grid steps 0.25 and puts only 8 levels in the data.
The failure is a skipped rescale. Symptom: every output saturates. Measure: row 1's corrected 32-bit sum is 21,895, and an 8-bit output holds at most 127. Fix: rescale before adding ZY: 21,895 × 0.00625 = 136.8, rounded to 137, minus 64 gives 73.
Chapter 10
Fold the bias and the zero point into one precomputed integer, and size the accumulator so it never overflows
A real layer adds a bias b, with its own scale Sb and zero point Zb. Slide 62 sets Zb = 0 and Sb = SWSX. Now the bias counts in the same unit as the integer sum. With ZW = 0:
Slide 63 folds the input-free terms into one integer:
q bias equals q b minus Z X q W. Then q Y equals S W S X over S Y, times q W q X plus q bias, plus Z Y.
Before inference, fold Z X times the weight sum into q b. At run time, add q bias to the integer sum, rescale, and add Z Y.
Chapter 9's row plus a made-up bias of 0.1: q b = 0.1 / 0.0000490 = 2,040, so q bias = 2,040 + 4,096 = 6,136. The sum −5,280 + 6,136 = 856 rescales to 5. Then 5 − 64 = −59 decodes to 0.039, against the float 0.04.
A convolution slides a kernel of weights over an image and takes a matrix-row sum at each spot. So slide 65 swaps qWqX for Conv(qW, qX), and qbias becomes qb − Conv(qW, ZX).
Warm boxes are small integers. Yellow boxes are 32-bit integers. Drag the step to move through the layer from input to output.
The stages follow slides 65 and 66: N-bit inputs and weights, a 32-bit sum and bias, an N-bit output. Here N is 8 or 4.
Pad the border with ZX, not 0, so padded pixels decode to true zero (our reasoning, not the slides').
A product of two N-bit signed integers reaches at most 22N−2. An output sums K products, where the fan-in K is kernel width × height × input channels. The worst case needs 2N − 1 + ceil(log2 K) bits.
The bar shows the bits the worst-case sum needs. The marks are 16 and 32 bits. Pick a layer, or set the bits and the fan-in K yourself.
Our own worst-case bound, every product at its largest. The layer sizes are common shapes, not slide figures.
At 8 bits and K = 4,608 (3×3 kernel, 512 channels) the worst case needs 15 + 13 = 28 bits. That is the failure. Symptom: wide layers give garbage with flipped signs. Measure: one product reaches 16,129, so three pass the 16-bit limit of 32,767. Fix: accumulate in 32 bits.
pythondef int_linear(qx, qW, qb, Zx, Zy, M): # qx (K,) int8, qW (O,K) int8, qb (O,) int32 q_bias = qb - Zx * qW.sum(1, dtype=np.int32) # precompute once per layer acc = qW.astype(np.int32) @ qx.astype(np.int32) + q_bias # int32 accumulate return np.clip(np.round(M * acc) + Zy, -128, 127).astype(np.int8) # rescale, shift, clamp
| Network (slide 67) | Floating point | 8-bit integer |
|---|---|---|
| ResNet-50 | 76.4% | 74.9% |
| Inception-V3 | 78.4% | 75.4% |
On Snapdragon 835 big cores, integer-only MobileNets beat float ones on accuracy at the same latency (Jacob et al., CVPR 2018).
Chapter 11
Keep the numbers, the terms, the checklist and the core code in one place
Slide 68 shows the agenda grid once more, with a question mark for binary and ternary quantization: that is Lecture 6. Slide 69 sums up three things: numeric data types, the idea of quantization, and two methods, K-means-based and linear. Quantization converts weights and activations into a limited discrete set of numbers.
| What | Value | Where |
|---|---|---|
| Add, 8-bit integer against 32-bit float | 0.03 pJ against 0.9 pJ, 30 times | Chapter 0, slide 3 |
| Multiply, 8-bit integer against 32-bit float | 0.2 pJ against 3.7 pJ, about 18 times (slide marks 16 times) | Chapter 0, slide 3 |
| FP32 layout | 1 sign, 8 exponent, 23 fraction, bias 127 | Chapter 2, slide 8 |
| FP32 smallest subnormal, largest normal | 2−149, about 3.4 × 1038 | Chapter 2, slides 12 and 16 |
| FP16, BF16 | 1/5/10 (max 65,504), 1/8/7 (same range as FP32) | Chapter 3, slide 17 |
| FP8 E4M3, E5M2 largest values | 448, 57,344 | Chapter 3, slide 20 |
| INT8, INT4 ranges | −128 to 127, −8 to 7 | Chapters 1 and 8, slides 6 and 49 |
| K-means storage, 4 by 4 block at 2 bits | 64 B to 20 B, 3.2 times; large layers about 32 / N | Chapter 4, slide 28 |
| Deep Compression | AlexNet 240 MB to 6.9 MB (35 times), VGGNet 49 times, SqueezeNet 510 times | Chapter 6, slides 40 and 42 |
| Linear scale and zero point | S = (rmax − rmin) / (qmax − qmin), Z = round(qmin − rmin / S) | Chapter 8, slides 50 and 52 |
| Slide block at 2 bits | S = 1.07, Z = −1, largest error 0.46 | Chapter 7, slide 47 |
| Quantized layer | qY = (SW SX / SY)(qW qX + qbias) + ZY | Chapter 10, slide 64 |
| Accumulator width, worst case | 2N − 1 + ceil(log2 K) bits (our bound) | Chapter 10 |
| Term | Meaning |
|---|---|
| Quantization | Constrain values from a large set to a short list. |
| Quantization error | The gap between a value and the one it snapped to. |
| Codebook, centroid | The short list of stored values, and each entry in it. |
| Scale S | The real distance between two neighbouring integers. |
| Zero point Z | The integer that decodes to real 0. |
| Symmetric quantization | Z = 0, with the real range centered on zero. |
| Subnormal | A float with exponent field 0 and no hidden 1. |
| Huffman coding | Short codes for common symbols, lossless. |
pythonimport numpy as np def linear_params(r_min, r_max, bits): q_min, q_max = -2**(bits - 1), 2**(bits - 1) - 1 S = (r_max - r_min) / (q_max - q_min) # real width per tick Z = int(round(q_min - r_min / S)) # the tick that means real 0 return S, Z, q_min, q_max def quantize(r, S, Z, q_min, q_max): return np.clip(np.round(r / S + Z), q_min, q_max).astype(np.int32) def dequantize(q, S, Z): return S * (q.astype(np.float32) - Z) # r = S (q - Z) def int_linear(qx, qW, qb, Zx, Zy, M): # M = S_W S_X / S_Y q_bias = qb - Zx * qW.sum(1, dtype=np.int32) # once, ahead of time acc = qW.astype(np.int32) @ qx.astype(np.int32) + q_bias # int32 accumulate return np.clip(np.round(M * acc) + Zy, -128, 127).astype(np.int8) w = np.array([2.09, -0.98, 1.48, 0.09, 0.05, -0.14, -1.08, 2.12, -0.91, 1.92, 0, -1.03, 1.87, 0, 1.53, 1.49]) S, Z, lo, hi = linear_params(w.min(), w.max(), 2) q = quantize(w, S, Z, lo, hi) # S = 1.0667, Z = -1 err = np.abs(w - dequantize(q, S, Z)).max() # 0.46, the slide's largest error
This lecture gives the vocabulary. Later work picks which values to keep, handles weight and activation outliers, and trains with quantization in the loop. Lecture 6 continues with the activation zero point we skipped, then binary and ternary weights. The pruning half of Deep Compression is in Pruning I and Pruning II.
This lesson follows Lecture 5 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course site, which links the slides. The papers the lecture cites include Horowitz's "Computing's Energy Problem" (ISSCC 2014), Deep Compression (Han et al., ICLR 2016), SqueezeNet (Iandola et al., 2016), and "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference" (Jacob et al., CVPR 2018). All explanations, devices and worked examples here are our own, except where we say a number is the slide's.
Now press Teach and explain, from memory, how a range of real weights becomes a scale and a zero point, and why a layer can then run on integers. Then go back to the weights at the top and compare the two methods once more.