AI Logic

Model Compression

Deep Compression

Updated:

How Deep Compression works. The left side shows the three stages "① pruning → ② quantization → ③ Huffman coding," with the size after each stage reduced to 1/9–1/13, 1/27–1/31, and 1/35–1/49 of the original. The right side shows an example in which 4 × 4 weights are grouped into four shared values, each weight is represented by a 2-bit index, and the shared values are retrained with gradients

Background and Overview

Deep Compression, proposed by Han, Mao, and Dally (2016), is a method that reduces the storage size of a trained network by tens of times while preserving accuracy. It applies the following three stages in order.

  1. Pruning: Remove connections with small values to reduce the number of weights.
  2. Quantization (weight sharing): Group the remaining weights into a few shared values and represent each weight only by the index of its shared value. This reduces the number of bits needed per weight.
  3. Huffman coding: Assign shorter codes to more frequent indices to pack the data further.

The goal is to make models easier to deploy on devices such as smartphones. The paper gives two reasons. One is distribution size: a feature that adds 100MB to an app is treated more cautiously than one that adds 10MB. The other is power consumption: on a 45nm process, a 32-bit floating-point addition costs 0.9pJ, while reading 32 bits from off-chip DRAM costs 640pJ. If a model becomes small enough to fit in on-chip SRAM, memory reads, which account for most of the power, can be reduced.

As an everyday analogy, Deep Compression is like packing for a move. First, throw away what is not needed (pruning); then put similar items together in one box and write only the box number (quantization); finally, give short labels to the boxes used most often (Huffman coding). The three techniques do not interfere with each other, so their effects multiply almost directly.

Theory (The Three-Stage Procedure)

① Pruning

This stage uses the method of Han et al. (2015) as is. After normal training learns which connections are important, weights below a threshold are removed and the remaining weights are retrained. For AlexNet and VGG-16, this reduces the number of weights by 9× and 13×.

The resulting sparse matrix is stored in a format that records the nonzero values and their positions (CSR or CSC). With aa nonzero elements and nn rows (or columns), this format requires 2a+n+12a + n + 1 numbers. Positions are recorded not as absolute addresses but as differences from the previous element, using 8 bits for convolutional layers and 5 bits for fully connected layers. When a difference exceeds that range, a zero-valued filler element is inserted.

② Quantization (weight sharing)

The nn weights of a layer, W={w1,…,wn}W = \{w_1, \dots, w_n\}, are partitioned into kk clusters C={c1,…,ck}C = \{c_1, \dots, c_k\}. The partition is found with one-dimensional k-means, minimizing the within-cluster sum of squares (Eq. (2) in the paper).

arg⁡min⁡C∑i=1k∑w∈ci∣w−ci∣2\arg\min_{C} \sum_{i=1}^{k} \sum_{w \in c_i} |w - c_i|^2

Weights in the same cluster share the same value (the centroid). Only the table of shared values (the codebook) and an index per weight indicating which shared value it uses are stored. With kk shared values, each index needs only log⁡2k\log_2 k bits. Weights are not shared across layers.

After quantization, the shared values are fine-tuned by retraining. The gradient of the loss LL with respect to a shared value CkC_k is the sum of the gradients of the weights that use it (Eq. (3)). IijI_{ij} is the index of weight WijW_{ij}, and 1(⋅)\mathbb{1}(\cdot) is a function that is 1 when the condition holds and 0 otherwise.

∂L∂Ck=∑i,j∂L∂Wij∂Wij∂Ck=∑i,j∂L∂Wij 1(Iij=k)\frac{\partial L}{\partial C_k} = \sum_{i,j} \frac{\partial L}{\partial W_{ij}} \frac{\partial W_{ij}}{\partial C_k} = \sum_{i,j} \frac{\partial L}{\partial W_{ij}}\, \mathbb{1}(I_{ij} = k)

The right side of the figure at the top is the example from Figure 3 of the paper. 4 × 4 = 16 weights are grouped into four shared values (2.00, 1.50, 0.00, −1.00), and each weight is represented by a 2-bit index. After retraining, the shared values move to 1.96, 1.48, −0.04, and −0.97.

When nn connections, each represented with bb bits, share kk values, the compression rate is as follows (Eq. (1)).

r=nbnlog⁡2k+kbr = \frac{n b}{n \log_2 k + k b}

In the figure's example, r=16⋅32/(16⋅2+4⋅32)=3.2r = 16 \cdot 32 / (16 \cdot 2 + 4 \cdot 32) = 3.2.

③ Huffman coding

Huffman coding is a lossless compression method that assigns shorter codes to more frequent symbols. Both the quantized weight indices and the position differences in the sparse matrix have skewed value distributions (weights cluster around two peaks, and most position differences are below 20). As a result, Huffman coding shrinks the model by a further 20–30%. It requires no training and is applied after all retraining is finished.

Mechanism and Why It Works

  • Pruning and quantization do not interfere with each other. In Figure 6 of the paper, pruning alone or quantization alone started to lose accuracy sharply when the model was shrunk below 8% of its original size. Combining the two allowed shrinking to 3% of the original without loss of accuracy. Pruning reduces the number of weights to quantize from 60 million to 6.7 million, so the same number of shared values yields smaller error (AlexNet).
  • Retraining the shared values recovers accuracy even with coarse quantization. The shared values chosen by k-means are based only on how close the weights are. Retraining moves the shared values in the direction that reduces the loss.
  • Initializing the shared values at equal intervals worked best. The paper compared random selection (Forgy), selection along the cumulative distribution, and placing values at equal intervals from the minimum to the maximum; equal intervals gave the best results except in the 3-bit case (Figure 8). After pruning, weights cluster in two peaks, and only a few weights have large values. The other two methods rarely place shared values near the large values, so the important large weights are poorly represented.
  • Different layers need different numbers of bits. Convolutional layers lost much accuracy below 4 bits, while fully connected layers held up down to 2 bits (Figure 7). The experiments therefore use 8 bits (256 shared values) for convolutional layers and 5 bits (32 shared values) for fully connected layers.

The quantization here differs from the uniform quantization that rounds to an evenly spaced grid described in the quantization article; it is a non-uniform quantization that clusters weights and shares centroid values. Because the shared values are placed according to the weight distribution, error stays low even with few bits, but there is an extra step of looking up shared values from indices before computation.

Experimental Results

Table 1 of the paper compresses four networks by 35–49× while preserving accuracy (lower error is better; sizes include the sparse-matrix positions and the codebook).

Model (data)Original errorCompressed errorOriginal sizeCompressed sizeCompression rate
LeNet-300-100 (MNIST)1.64%1.58%1070KB27KB40×
LeNet-5 (MNIST)0.80%0.74%1720KB44KB39×
AlexNet (ImageNet, top-1)42.78%42.78%240MB6.9MB35×
VGG-16 (ImageNet, top-1)31.50%31.17%552MB11.3MB49×

The stage-by-stage breakdown for AlexNet (Table 4) is as follows.

StageFraction of weights remainingBits per weightSize relative to original
After pruning11% (1/9)32—
+ Quantization11%5.4 on average3.7% (1/27)
+ Huffman coding11%4 on average2.88% (1/35)

The paper also examines how far the bit width can be reduced (Table 6, AlexNet). With 8 bits for convolutional layers and 5 bits for fully connected layers, the error rate did not change, and with 8 and 4 bits the top-1 error increased by only 0.01%. Going down to 4 and 2 bits increased the error by 1.99% (top-1) and 2.60% (top-5).

Speed and power were also measured, but only for the pruned fully connected layers, processing one image at a time (batch size 1). Compared with the original dense layers, they ran 3× faster on CPU, 3.5× on GPU, and 4.2× on mobile GPU, and energy consumption dropped to 1/7 on CPU, 1/3.3 on GPU, and 1/4.2 on mobile GPU (Figures 9 and 10).

Practical Considerations

  • What mainly shrinks is storage size. Looking up weights from codebook indices and sparse matrices encoded with position differences cannot be handled by ordinary matrix computation libraries. The paper itself does not measure the speed of the quantized model; speed was measured only for the pruned fully connected layers. Dedicated hardware that computes directly on the compressed model (EIE) was proposed later.
  • The benefit is largest for models with large fully connected layers. In AlexNet and VGG-16, more than 90% of the parameters are in fully connected layers, and 96% of the weights in VGG-16's fully connected layers could be removed. In models with small fully connected layers, the fraction that pruning can remove is smaller.
  • Retraining is needed twice. Retraining happens both after pruning and after quantization, which requires training time and data.
  • There are per-layer hyperparameters. The pruning threshold and the number of shared values are set per layer. Convolutional layers are sensitive to low bit widths, so they are assigned more bits than fully connected layers.

Running a model compressed with Deep Compression as is in ordinary PyTorch or similar frameworks means converting indices back to shared values and expanding sparse matrices into dense ones before computation. In that case, file and download sizes shrink, but inference speed and runtime memory barely change.

Comparison with Other Methods

The table compares Deep Compression with methods close to each of its stages and with other compression approaches.

MethodWhat it reducesWhen it gets fasterRetraining required
Deep CompressionNumber of weights, bits per weight, code lengthDedicated hardware or sparse computation kernelsYes (twice)
Pruning onlyNumber of weightsSupport for sparse computationYes
Uniform quantization (INT8, etc.)Bits per valueDirectly, if integer arithmetic units are availableNot for post-training quantization
Filter pruning, Network SlimmingNumber of filters and channelsStill ordinary dense computationYes
Low-rank factorizationMatrix sizeStill ordinary dense computationUsually
Knowledge distillationOverall model sizeDirectly, with a small studentYes

Figure 6 of the paper also compares low-rank approximation by singular value decomposition (SVD), reporting that it is cheap to compute but achieves a low compression rate.

  • To reduce app distribution size or on-device storage, the Deep Compression approach is effective. It can also be applied on top of architectures that are small to begin with, such as SqueezeNet.
  • To speed up inference on ordinary GPUs or CPUs, structured pruning that removes channels or uniform quantization that uses integer arithmetic units is a better fit.

PyTorch example

Show code
python
import heapq
from collections import Counter

import torch
import torch.nn as nn
import torch.nn.utils.prune as prune

# ① Pruning: remove weights with small absolute values (built into PyTorch). Retrain afterward
layer = nn.Linear(256, 128)
prune.l1_unstructured(layer, name="weight", amount=0.9)
prune.remove(layer, "weight")              # make the mask permanent, leaving a weight that contains zeros
mask = layer.weight.detach() != 0           # remaining connections


# ② Quantization: group the remaining weights into k shared values with 1-D k-means (Eq. (2))
def kmeans_1d(w, k, iters=30):
    # initialize the shared values at equal intervals from min to max (the best method in the paper)
    c = torch.linspace(w.min().item(), w.max().item(), k)
    for _ in range(iters):
        idx = (w[:, None] - c[None, :]).abs().argmin(dim=1)  # index of the nearest shared value
        for j in range(k):
            if (idx == j).any():
                c[j] = w[idx == j].mean()
    return c, idx


class SharedWeightLinear(nn.Module):
    """Linear layer that stores weights as "codebook (shared values) + indices". Only the shared values are trained"""
    def __init__(self, weight, bias, mask, bits=5):
        super().__init__()
        k = 2 ** bits
        w = weight[mask]
        centroids, idx = kmeans_1d(w, k)
        self.codebook = nn.Parameter(centroids)          # k shared values (32-bit)
        full_idx = torch.zeros(weight.shape, dtype=torch.long)
        full_idx[mask] = idx
        self.register_buffer("index", full_idx)          # index of each weight (bits bits)
        self.register_buffer("mask", mask)
        self.bias = nn.Parameter(bias.clone())

    def forward(self, x):
        # build the weights by looking up shared values from indices. With autograd, the gradient of
        # shared value C_k is the sum of the gradients of the weights with index k (Eq. (3))
        w = self.codebook[self.index] * self.mask
        return nn.functional.linear(x, w, self.bias)


q = SharedWeightLinear(layer.weight.detach(), layer.bias.detach(), mask, bits=5)
q.train()
out = q(torch.randn(4, 256))
out.sum().backward()
print(q.codebook.grad.shape)  # torch.Size([32]): gradient per shared value


# Compression rate (Eq. (1)): represent n b-bit weights with k shared values and log2(k)-bit indices
def compression_rate(n, b, k):
    return n * b / (n * torch.log2(torch.tensor(float(k))).item() + k * b)

print(compression_rate(16, 32, 4))  # 3.2 (the example in Figure 3 of the paper)


# ③ Huffman coding: compute the average code length (bits) from index frequencies
def huffman_avg_bits(symbols):
    freq = Counter(symbols)
    if len(freq) == 1:
        return 1.0
    heap = [(f, i, {s: 0}) for i, (s, f) in enumerate(freq.items())]
    heapq.heapify(heap)
    uid = len(heap)
    while len(heap) > 1:
        f1, _, a = heapq.heappop(heap)
        f2, _, b = heapq.heappop(heap)
        merged = {s: d + 1 for s, d in {**a, **b}.items()}  # merging two nodes lengthens their codes by 1 bit
        heapq.heappush(heap, (f1 + f2, uid, merged))
        uid += 1
    lengths = heap[0][2]
    total = sum(freq.values())
    return sum(freq[s] * lengths[s] for s in freq) / total

print(huffman_avg_bits(q.index[q.mask].tolist()))  # often shorter than 5 bits

FAQ

Q. Does a model compressed with Deep Compression also run faster at inference?
A.

In ordinary environments, it barely gets faster. What mainly shrinks is the storage and download size, because looking up shared values from indices and sparse matrices encoded with position differences cannot be handled by ordinary matrix computation libraries. The paper measured speed only for the pruned fully connected layers, which ran 3–4× faster when processing one image at a time. Computing directly on the compressed form requires dedicated hardware such as EIE.

Q. How does the quantization here differ from INT8 quantization?
A.

Uniform quantization such as INT8 rounds values to an evenly spaced grid so that computation can be done in integers. Deep Compression's quantization is non-uniform: it groups weights into kk shared values with k-means and represents each weight with a log⁡2k\log_2 k-bit index. Because the positions of the shared values are retrained to fit the weight distribution, accuracy is easier to preserve with few bits, but the values must be converted back to shared values before computation. See the quantization article for details.

Q. Which of the three stages contributes the most?
A.

Pruning and quantization account for most of it. For AlexNet, pruning gave 9×, adding quantization 27×, and adding Huffman coding 35×. For LeNet-300-100 as well, pruning and quantization gave 32× and adding Huffman coding 40×, so the extra gain from Huffman coding was relatively small.

References

  1. S. Han, H. Mao, and W. J. Dally, "Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman Coding," ICLR, 2016. arXiv:1510.00149.
  2. S. Han, J. Pool, J. Tran, and W. J. Dally, "Learning both Weights and Connections for Efficient Neural Networks," arXiv:1506.02626, 2015.
  3. PyTorch Documentation, "torch.nn.utils.prune.l1_unstructured."