Quantization I

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.

Squeeze sixteen weights

2

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

Fewer Bits Cost Less Energy

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.

OperationEnergy (pJ)
8-bit integer add0.03
32-bit integer add0.1
16-bit float add0.4
32-bit float add0.9
8-bit integer multiply0.2
32-bit integer multiply3.1
16-bit float multiply1.1
32-bit float multiply3.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.

Price an inference

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.

Price the arithmetic

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.

1,000 million

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.

  1. Integers and fixed point: eight bits, read three ways.
  2. Floating point from the inside: sign, exponent, fraction, subnormals.
  3. FP16, BF16, FP8 and 4 bits: range against precision.
  4. The K-means codebook: snap, store, count the bytes.
  5. Fine-tuning the codebook: shared nudges and spiky histograms.
  6. Deep Compression: prune, quantize, Huffman code.
  7. Linear quantization: the affine map r = S(q − Z).
  8. Scale and zero point: derive them from the range.
  9. Integer matrix multiplication: rescale with a shift.
  10. Layers: bias, convolution and the accumulator.
  11. The field guide: numbers, code and where to go next.
Using the lecture's table, which change saves the most energy per operation?

Chapter 1

Integers and Fixed Point

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.

Say it aloud

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.

value
value the whole number the row stands for.
bn−1
b n-minus-one the leftmost bit. When it is 1, the number is negative.
2n−1
two to the n minus one the leftmost place value: 128 for 8 bits, counted as −128.
∑i=0n−2
the sum over i from zero to n minus two one term for each of the other bits.
bi · 2i
b-i times two to the i the bit in place i times its place value 1, 2, 4 and so on.
In plain words

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.

With numbers

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.

Read eight switches

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.

Fixed point: slide in a decimal point

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.

In 8-bit two's complement, what is 10000001?

Chapter 2

A Floating-Point Number from the Inside

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.

Say it aloud

Value equals minus one to the sign, times one plus fraction, times two to the exponent minus one hundred twenty-seven.

value
value the real number a normal FP32 pattern stands for.
(−1)sign
minus one to the sign +1 when the sign bit is 0, −1 when it is 1.
1 + fraction
one plus fraction the digits. The 1 is the hidden bit: a normal binary number always starts with 1, so the chip does not store it.
exponent
exponent the 8-bit field, 1 to 254 for normal numbers.
127
one hundred twenty-seven the bias, 28−1 − 1. Subtracting it lets the unsigned field reach scales from 2−126 to 2127.
In plain words

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.

With numbers

Slide 8's 0 01111101 00010000000000000000000: sign 0, exponent 125, fraction 2−4 = 0.0625. Value = 1.0625 × 2125−127 = 0.265625.

Zero, tiny numbers and infinity

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.

Say it aloud

Value equals minus one to the sign, times fraction, times two to the one minus one hundred twenty-seven.

value
value a subnormal: its exponent field is 0.
fraction
fraction the 23 bits, 0 to just under 1, with no 1 in front.
21−127
two to the one minus one hundred twenty-seven a fixed scale, 2−126, the scale of the smallest normal number.
In plain words

Multiply the bare fraction by 2 to the minus 126. An all-zero fraction now gives 0, with a +0 and a −0.

With numbers

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 fieldFraction is 0Fraction is not 0
0±0subnormal
1 to 254normal number
255±∞not-a-number

Open a float yourself

Build an FP32 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.

125
4/64

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.

Why does FP32 have subnormal numbers, where the exponent field is 0 and the hidden 1 is dropped?

Chapter 3

FP16, BF16, FP8 and the 4-Bit Zoo

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.

FormatExponent bitsFraction bitsTotal bits
IEEE FP3282332
IEEE FP1651016
Google Brain Float, BF168716

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.

Decode one, encode one

Slide 18 decodes the FP16 pattern 1100011100000000:

  1. Sign: the first bit is 1, so the number is negative.
  2. Exponent: 10001 is 17. Subtract the bias: 17 − 15 = 2.
  3. Fraction: 1100000000 is 0.5 + 0.25 = 0.75.
  4. Value: −(1 + 0.75) × 22 = −7.0.

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.

FP8: two ways to cut a byte

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.

Slide the format along the trade

Range against precision

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.

1,000

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.

INT4 and the 4-bit floats

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.

FormatPositive valuesSpacing
INT40 to 7 (and −1 to −8)steps of 1
FP4 E1M20, 0.5, 1, 1.5, 2, 2.5, 3, 3.5even
FP4 E2M10, 0.5, 1, 1.5, 2, 3, 4, 6fine near 0, wide at the top
FP4 E3M00, 0.25, 0.5, 1, 2, 4, 8, 16each value doubles

Which numbers fit in 4 bits

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.

A gradient value of 100,000 appears. Which format holds it without overflow?

Chapter 4

What Quantization Is, and the K-Means Codebook

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.

Turn a wave into steps

The blue curve is the smooth signal. The warm steps are what you keep. The yellow bars are the error. Drag the bits.

2

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.

Stored versus computed

Slides 23 and 24 sort the methods by what they keep and what they compute:

MethodStored weightsArithmetic
Original32-bit floatsfloating-point
K-means-basedinteger indices plus a floating-point codebookfloating-point
Linearintegersinteger
Binary and ternary1 or 2 bitsnext lecture

K-means: choose the pots from the weights

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).

Counting bytes

Call the weight count M and the index width N bits.

Say it aloud

Ratio equals thirty-two M, over N M plus thirty-two times two to the N, which is about thirty-two over N.

ratio
ratio how many times smaller the layer gets.
32 M
thirty-two M the original size in bits: M weights at 32 bits.
N M
N M the indices: M of them, N bits each.
32 · 2N
thirty-two times two to the N the codebook: 2N centroids at 32 bits.
32 / N
about thirty-two over N the limit when M is much larger than 2N, so the codebook drops out.
In plain words

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.

With numbers

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.

Count the bytes

Blue is the original, warm the indices, purple the codebook. Set the weight count and the index bits.

16
2

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
A layer has 1,000,000 weights. You store 4-bit K-means indices and a 16-entry float codebook. About how many times smaller is the layer?

Chapter 5

Fine-Tuning a Codebook

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.

Say it aloud

c-k becomes c-k minus eta times the sum, over every i whose index is k, of d L by d w-i.

ck
c-k centroid number k, one codebook entry.
←
becomes replace the old value with the new one.
η
eta the learning rate.
∑i : k(i) = k
the sum over i such that k of i is k one term for each weight whose index points at centroid k.
∂L / ∂wi
d L by d w-i the gradient of the loss L for weight i.
In plain words

Group the gradients by index. Add each group. Multiply the sum by eta and subtract it from that group's centroid c-k.

With numbers

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.

Nudge the codebook

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.

1.0

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.

Watch hills turn into spikes

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.

3

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
Three weights share centroid 1.50 and have gradients 0.10, −0.04 and 0.02. With a learning rate of 1, what is the new centroid?

Chapter 6

Deep Compression: Prune, Quantize, Huffman

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.

Huffman coding

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.

Build a Huffman code

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.

6

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.

The pipeline and the results

Slide 39 gives the order, with the same accuracy after each stage:

  1. Prune: train, remove connections, retrain. 9 to 13 times smaller.
  2. Quantize: cluster, build the codebook, retrain it as in Chapter 5. 27 to 31 times.
  3. Huffman-encode the weights and the indices. 35 to 49 times.

Pruning goes first so quantization has fewer weights to handle. Huffman goes last because it is lossless and works on whatever symbols remain.

NetworkOriginal sizeCompressedRatioAccuracy beforeAccuracy after
LeNet-3001070 KB27 KB40x98.36%98.42%
LeNet-51720 KB44 KB39x99.20%99.26%
AlexNet240 MB6.9 MB35x80.27%80.30%
VGGNet550 MB11.3 MB49x88.68%89.09%
GoogleNet28 MB2.8 MB10x88.90%88.92%
ResNet-1844.6 MB4.0 MB11x89.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.

NetworkApproachSizeRatioTop-1Top-5
AlexNetnone240 MB1x57.2%80.3%
AlexNetSVD48 MB5x56.0%79.4%
AlexNetDeep Compression6.9 MB35x57.2%80.3%
SqueezeNetnone4.8 MB50x57.5%80.3%
SqueezeNetDeep Compression0.47 MB510x57.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
Why does Deep Compression run Huffman coding last?

Chapter 7

Storage Is Not Enough: Linear Quantization

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.

A ruler with an offset

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.

Say it aloud

r equals S times, q minus Z.

r
r the real weight, a 32-bit float after decoding.
S
S the scale, a 32-bit float: real distance per tick.
q
q the stored integer. At 2 bits, 01 = 1, 00 = 0, 11 = −1, 10 = −2.
Z
Z the zero point, an integer of the same width: the tick for real 0.
In plain words

Take the stored integer q. Subtract the zero point Z. Multiply by the scale S to get the real weight r.

With numbers

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.

Find a scale and a zero point

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.

1.07
−1

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.

With S = 1.07 and Z = −1, what real number does the stored integer q = −1 decode to, and why does that matter?

Chapter 8

Deriving the Scale and the Zero Point

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 widthqminqmax
2−21
3−43
4−87
N−2N−12N−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.

Say it aloud

S equals, r max minus r min, over, q max minus q min.

S
S the scale: real distance per tick.
rmax − rmin
r max minus r min the width of the real range the weights use.
qmax − qmin
q max minus q min the gaps between ticks, 2N − 1.
In plain words

Divide the real width, r max minus r min, by the number of tick gaps, q max minus q min.

With numbers

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.

Say it aloud

Z equals round of, q min minus r min over S.

Z
Z the zero point: the tick that decodes to real 0.
round
round of the nearest whole number.
qmin
q min the lowest integer, −2 at 2 bits.
rmin / S
r min over S the smallest weight, counted in ticks from real 0.
In plain words

Count the smallest weight r min in ticks. Subtract that count from q min. Round to a whole tick.

With numbers

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.

Move the two ends yourself

Glue the ruler to the range

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.

−1.08
2.12
2

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)
A weight range is −1 to 3 and you quantize to 4-bit signed integers, q from −8 to 7. What is the scale S?

Chapter 9

Quantized Matrix Multiplication

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.

Say it aloud

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.

qY
q Y the integer stored for the output.
SW SX / SY
S W S X over S Y one real number that rescales the integer sum into output units. Slide 56: always between 0 and 1.
qW qX
q W q X N-bit integer multiplies, summed in 32-bit integers.
ZW qX
Z W q X the weight zero point times the input sum. It depends on the live input, so it runs every time.
ZX qW
Z X q W the input zero point times the weight sum. Weights only, so precompute it.
ZW ZX
Z W Z X a constant. Precompute it.
ZY
Z Y the output zero point, one N-bit integer add.
In plain words

Multiply the integer weights q W by the integer inputs q X and sum. Subtract the zero-point terms. Rescale, then add Z Y.

With numbers

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.

Symmetric weights drop a term

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.

One output, every step

Toy numbers: weight row (0.5, −0.3), input (0.6, 1.2), float answer −0.06. Everything is 8-bit:

TensorReal rangeScale SZero point Z
Weights (symmetric)−0.8 to 0.80.8 / 128 = 0.006250
Input0 to 22 / 255 = 0.00784−128
Output−0.5 to 1.52 / 255 = 0.00784−64
  1. Quantize: qW = (80, −48), qX = (−51, 25).
  2. Integer sum: 80 × (−51) + (−48) × 25 = −5,280.
  3. Precomputed term: ZX Σ qW = −128 × 32 = −4,096. Subtract it: −1,184.
  4. Rescale by 0.00625 = 2−7 × 0.8: −7.4, rounded to −7.
  5. Add ZY: −7 − 64 = −71 = qY.
  6. Decode: 0.00784 × (−71 + 64) = −0.055.

Run the integer pipeline

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.

Count the wasted levels

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.

0.00
4

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.

Why does setting ZW = 0 make the integer matrix multiplication cheaper?

Chapter 10

Fully-Connected and Convolution Layers

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:

Say it aloud

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.

qbias
q bias the folded bias: one 32-bit integer per output, computed before inference.
qb
q b the bias as a 32-bit integer on scale S W S X (slide 64).
ZX qW
Z X q W the input zero point times the sum of that output's integer weights. Slide 63 leaves how to find Z X to the next lecture.
SW SX / SY
S W S X over S Y the rescale: a fixed-point multiply and a shift.
qW qX
q W q X the integer multiply-and-sum, in 32 bits.
ZY
Z Y the output zero point.
In plain words

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.

With numbers

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.

Convolution is the same pipeline

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).

Follow the integers through a layer

Warm boxes are small integers. Yellow boxes are 32-bit integers. Drag the step to move through the layer from input to output.

1

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').

Why 32 bits for the sum?

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.

Size the accumulator

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.

8
4,096

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

Does it pay off on a phone?

Network (slide 67)Floating point8-bit integer
ResNet-5076.4%74.9%
Inception-V378.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).

Why are the bias scale and zero point set to Sb = SW SX and Zb = 0?

Chapter 11

The Field Guide

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.

Numbers to keep

WhatValueWhere
Add, 8-bit integer against 32-bit float0.03 pJ against 0.9 pJ, 30 timesChapter 0, slide 3
Multiply, 8-bit integer against 32-bit float0.2 pJ against 3.7 pJ, about 18 times (slide marks 16 times)Chapter 0, slide 3
FP32 layout1 sign, 8 exponent, 23 fraction, bias 127Chapter 2, slide 8
FP32 smallest subnormal, largest normal2−149, about 3.4 × 1038Chapter 2, slides 12 and 16
FP16, BF161/5/10 (max 65,504), 1/8/7 (same range as FP32)Chapter 3, slide 17
FP8 E4M3, E5M2 largest values448, 57,344Chapter 3, slide 20
INT8, INT4 ranges−128 to 127, −8 to 7Chapters 1 and 8, slides 6 and 49
K-means storage, 4 by 4 block at 2 bits64 B to 20 B, 3.2 times; large layers about 32 / NChapter 4, slide 28
Deep CompressionAlexNet 240 MB to 6.9 MB (35 times), VGGNet 49 times, SqueezeNet 510 timesChapter 6, slides 40 and 42
Linear scale and zero pointS = (rmax − rmin) / (qmax − qmin), Z = round(qmin − rmin / S)Chapter 8, slides 50 and 52
Slide block at 2 bitsS = 1.07, Z = −1, largest error 0.46Chapter 7, slide 47
Quantized layerqY = (SW SX / SY)(qW qX + qbias) + ZYChapter 10, slide 64
Accumulator width, worst case2N − 1 + ceil(log2 K) bits (our bound)Chapter 10

Terms in one line each

TermMeaning
QuantizationConstrain values from a large set to a short list.
Quantization errorThe gap between a value and the one it snapped to.
Codebook, centroidThe short list of stored values, and each entry in it.
Scale SThe real distance between two neighbouring integers.
Zero point ZThe integer that decodes to real 0.
Symmetric quantizationZ = 0, with the real range centered on zero.
SubnormalA float with exponent field 0 and no hidden 1.
Huffman codingShort codes for common symbols, lossless.

A checklist for quantizing a layer

The core as code

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

Where it sits in the field

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.

Keep going

The takeaway. Fewer bits cost less energy. A codebook saves storage and leaves the math in floats. A linear grid defined by a scale and a zero point saves both, because its multiplies stay in small integers and one precomputed 32-bit bias.

Credit

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.

Which statement about the three methods in the lecture's agenda grid is correct?

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.

MIT 6.5940 Lecture 5: Quantization I
The course site · Lecture 5 slides · Back to Lecture 4 · On to Lecture 6 · Back to Gleams