AI Logic

Model Compression

XNOR-Net

Updated:

How XNOR-Net works. Left: a comparison of the block order in a standard CNN (convolution, batch normalization, activation function, pooling) and in XNOR-Net (batch normalization, binarization, binary convolution, pooling). Right: the convolution approximation, in which the weight filter is split into its sign sign(W) and a scale α equal to the mean |W|, the input into its sign sign(I) and a per-position scale K, giving I ∗ W ≈ (sign(I) ⊛ sign(W)) ⊙ Kα

Background and Overview

XNOR-Net is a method that binarizes both the weights and the inputs of a convolutional neural network to +1 or −1 and approximates convolutions with bitwise operations. It was proposed by Rastegari, Ordonez, Redmon, and Farhadi in 2016 and presented at ECCV 2016.

The paper proposes two variants.

  • Binary-Weight-Network (BWN): Only the weights are binarized. Weight memory shrinks to about 1/32 of single precision, and convolutions can be computed with additions and subtractions alone.
  • XNOR-Network (XNOR-Net): In addition to the weights, the inputs to convolutions are also binarized. Dot products between ±1 values can be computed with a bitwise XNOR and a bitcount that counts the 1s, so the paper's CPU implementation speeds up convolutions by about 58x.

Earlier binarization methods such as BinaryConnect had only been validated on small datasets such as MNIST and CIFAR-10. The XNOR-Net paper was the first to evaluate binary networks on ImageNet, showing that an AlexNet turned into a BWN matches the accuracy of real-valued weights.

The key to preserving accuracy is multiplying the values rounded to ±1 by a scale that represents the magnitude of the original values. It is like attaching "how much" to an arrow that only says "up or down." The magnitude information lost by keeping only the sign is compensated with a single number.

Theory (Approximation by Sign and Scale)

Binarizing the Weights (Binary-Weight-Network)

Treat the weights of one filter as a vector WW of nn values, and approximate it as W≈αBW \approx \alpha B with a binary vector B∈{+1,−1}nB \in \{+1, -1\}^n and a positive scale α\alpha. These are chosen to minimize the approximation error (Eq. (2) in the paper).

α∗,B∗=argmin⁡α,B∥W−αB∥2\alpha^*, B^* = \operatorname*{argmin}_{\alpha, B} \left\| W - \alpha B \right\|^2

Expanding this expression, and noting that B⊤B=nB^\top B = n is a constant, the optimal BB and α\alpha are obtained as follows (Eqs. (4)–(6)).

B∗=sign(W),α∗=W⊤sign(W)n=1n∑i∣Wi∣B^* = \mathrm{sign}(W), \qquad \alpha^* = \frac{W^\top \mathrm{sign}(W)}{n} = \frac{1}{n} \sum_i \lvert W_i \rvert

In other words, the binary values are the signs of the weights, and the scale is the mean absolute value of the weights. A convolution then becomes a multiplication-free convolution (⊕\oplus) of the input II with the binary filter, followed by a single multiplication by α\alpha (Eq. (1)).

I∗W≈(I⊕B) αI * W \approx (I \oplus B)\, \alpha

Binarizing the Inputs Too (XNOR-Net)

To binarize the inputs as well, the dot product between a patch of the input XX and the weights WW is approximated as X⊤W≈βH⊤αBX^\top W \approx \beta H^\top \alpha B (H,B∈{+1,−1}nH, B \in \{+1, -1\}^n, β,α>0\beta, \alpha > 0). Solving in the same way as for the weights gives H∗=sign(X)H^* = \mathrm{sign}(X), B∗=sign(W)B^* = \mathrm{sign}(W), and β∗≈1n∥X∥ℓ1\beta^* \approx \frac{1}{n} \lVert X \rVert_{\ell 1} (Eqs. (7)–(10)).

In a convolution, the input patch changes with each position the filter is applied to, so β\beta is needed for each position. To avoid recomputing overlapping regions, the scales are computed all at once as follows (Section 3.2).

  1. Average the absolute value of the input II along the channel dimension to form the matrix A=∑i∣I:,:,i∣/cA = \sum_i \lvert I_{:,:,i} \rvert / c.
  2. Convolve AA with a filter kk whose elements are all 1/(w×h)1/(w \times h) to obtain the per-position scale K=A∗kK = A * k (w×hw \times h is the filter size).
  3. Convolve the input sign sign(I)\mathrm{sign}(I) with the weight sign sign(W)\mathrm{sign}(W) using XNOR and bitcount.
  4. Multiply the result by the per-position KK and the per-filter α\alpha.

Put together, this gives the following expression (Eq. (11); ⊛\circledast is convolution via XNOR and bitcount, and ⊙\odot is the element-wise product).

I∗W≈(sign(I)⊛sign(W))⊙KαI * W \approx \left(\mathrm{sign}(I) \circledast \mathrm{sign}(W)\right) \odot K \alpha

The product of two ±1 values becomes an XNOR because, if +1 is encoded as bit 1 and −1 as bit 0, the product is +1 (XNOR gives 1) when the two match and −1 (XNOR gives 0) when they differ. The sum of nn products is 2p−n2p - n, where pp is the number of 1s in the XNOR result. A CPU can process 64 bits in a single instruction, so 64 products are computed at once.

Training

As in BinaryConnect, training keeps real-valued weights and uses binary values only for propagation (Algorithm 1 in the paper).

  1. For each filter in each layer, compute α=1n∥W∥ℓ1\alpha = \frac{1}{n}\lVert W \rVert_{\ell 1} and B=sign(W)B = \mathrm{sign}(W), and form W~=αB\tilde{W} = \alpha B.
  2. Run the forward pass using BB and α\alpha (convolution via Eq. (1) or Eq. (11)).
  3. Run backpropagation using W~\tilde{W} to obtain the gradients.
  4. Update the real-valued weights WW with those gradients using SGD, Adam, or a similar optimizer.

For the gradient of the sign function, an approximation (the straight-through estimator) passes a gradient of 1 only where ∣r∣≤1\lvert r \rvert \le 1 and 0 elsewhere. After training, the real-valued weights can be discarded, keeping only the binary weights and scales.

Why Accuracy Is Preserved

XNOR-Net improved accuracy substantially over earlier binarization methods for two main reasons.

  • Scales compensate for magnitude information. With signs alone, a weight with absolute value 0.01 and one with 1.0 both become ±1. Multiplying back by the per-filter α\alpha and the per-position KK brings the magnitude of the layer output closer to that of the original convolution. In the paper's ablation, making α\alpha a learned parameter instead of computing it with Eq. (6) dropped the top-1 accuracy of AlexNet BWN from 56.8% to 46.2% (Table 3a).
  • The block order is rearranged to suit binarization. A standard CNN uses the order "convolution → batch normalization → activation → pooling." XNOR-Net uses "batch normalization → binarization → binary convolution → pooling" (left side of the top figure). Normalizing to zero mean before binarization reduces the error from taking the sign around 0. Also, applying max pooling to ±1 inputs makes most values +1 and loses information, so pooling is moved after the convolution. This reordering raised XNOR-Net's top-1 from 30.3% to 44.2% (Table 3b).

Of the two scales, the weight scale α\alpha does most of the work. According to the paper, removing the input scale β\beta (KK) lowered AlexNet's top-1 by less than 1 point.

For speed, the paper estimates the speedup of a single convolution by counting high-precision operations (Section 4.1). With cc channels and NW=w×hN_W = w \times h filter elements, and assuming 64 binary operations per instruction, the speedup is:

S=64 cNWcNW+64S = \frac{64\, c N_W}{c N_W + 64}

For c=256c = 256 and NW=3×3N_W = 3 \times 3, which covers many ResNet layers, the theoretical speedup is 62.27x, and the paper's CPU implementation achieved about 58x. On the other hand, the first layer with 3 channels and the last layer with 1×11 \times 1 filters gain little speed, so the paper does not binarize these two layers.

Experimental Results

The paper compares top-1 and top-5 accuracy for image classification on ImageNet (ILSVRC2012) (Tables 1 and 2; higher is better). BC denotes BinaryConnect (deterministic binarization), and BNN denotes BinaryNet, which binarizes both weights and activations.

ModelMethodWeightsInputstop-1top-5
AlexNetReal-valued (with batch normalization)RealReal56.680.2
AlexNetBinaryConnect±1Real35.461.0
AlexNetBWN±1 with scaleReal56.879.4
AlexNetBinaryNet±1±127.950.42
AlexNetXNOR-Net±1 with scale±1 with scale44.269.2
ResNet-18Real-valuedRealReal69.389.2
ResNet-18BWN±1 with scaleReal60.883.0
ResNet-18XNOR-Net±1 with scale±1 with scale51.273.2

The results show the following.

  • For AlexNet, BWN matches the accuracy of real-valued weights. It is more than 21 points higher in top-1 than BinaryConnect, which also binarizes only the weights.
  • Binarizing the inputs as well lowers accuracy. XNOR-Net on AlexNet is 12.4 points lower in top-1 than the real-valued model, but more than 16 points higher than BinaryNet.
  • The gap widens for deeper models. On ResNet-18, top-1 drops by 8.5 points even with BWN and by 18.1 points with XNOR-Net relative to the real-valued model.

On CIFAR-10, using the same network architecture as BinaryConnect, the error rate is 9.88% for BWN and 10.17% for XNOR-Net. In addition, when the gradients with respect to the inputs are also binarized in backpropagation (using the maximum absolute value as the scale), the top-1 drop for XNOR-Net is only 1.4 points.

For memory, the paper compares binary weights with double-precision weights, showing reductions from 475MB to 7.4MB for AlexNet, from 1GB to 16MB for VGG-19, and from 100MB to 1.5MB for ResNet-18 (Figure 4a).

Practical Considerations

  • Do not binarize the first and last layers. The paper keeps the first layer, which has few channels, and the 1×11 \times 1 last layer at high precision because binarizing them yields no speedup.
  • Change the block order. Simply replacing the convolutions of an existing network with binary convolutions is not enough; the blocks must be reordered as "batch normalization → binarization → binary convolution → pooling." The paper notes that for large networks such as AlexNet and VGG, inserting a non-binary activation such as ReLU after the binary convolution improves accuracy.
  • Speedup depends on the compute kernels. Speedups appear only with dedicated implementations that use XNOR and bitcount. Also, according to the paper, on CPUs that can perform a multiply and an add in a single cycle, the weight-only BWN does not get faster (although memory is still reduced).
  • Real-valued weights are needed during training. The binary weights and scales are rebuilt from the real-valued weights for each mini-batch. Training memory is not reduced; the savings apply at inference time.

XNOR-Net, which also binarizes the inputs, loses 12.4 points of top-1 on AlexNet and 18.1 points on ResNet-18. For applications that cannot afford an accuracy drop, choose BWN, which binarizes only the weights, or quantization with more bits.

Comparison with Other Methods

The table below compares methods that binarize or ternarize weights with standard low-bit quantization along the same dimensions.

MethodWeight valuesWeight scaleActivationsMain target
BinaryConnect+1, −1NoneReal-valuedSmall-scale image recognition (MLPs, CNNs)
XNOR-Net (weights only: BWN)+1, −1Mean ∣W∣\lvert W \rvert per filterReal-valuedImageNet CNNs
XNOR-Net+1, −1Mean ∣W∣\lvert W \rvert per filter+1, −1 (with per-position scale)ImageNet CNNs
BitNet+1, −1 (sign after subtracting the mean)Mean ∣W∣\lvert W \rvert per matrix8-bitLarge language models
BitNet b1.58−1, 0, +1Mean ∣W∣\lvert W \rvert per matrix8-bitLarge language models
GPTQ3–4-bit integersPer row or per group16-bitPre-trained large language models

XNOR-Net's idea of "multiplying the sign by the mean ∣W∣\lvert W \rvert" was carried over into the later BitNet and BitNet b1.58. The difference is that XNOR-Net keeps a scale per filter and binarizes the inputs to ±1, whereas the BitNet family uses a single scale for the whole matrix and keeps activations at 8 bits.

  • To greatly reduce the weight memory of an image recognition model while preserving as much accuracy as possible, BWN is a good fit.
  • To run inference on CPUs or small devices with almost no multiplications, choose XNOR-Net and accept the accuracy drop.
  • If 4 or 8 bits are sufficient, standard quantization preserves accuracy more easily and is supported by more libraries.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


class SignSTE(torch.autograd.Function):
    """Pass the gradient of sign as 1 only where |x| <= 1 (used to binarize inputs)"""

    @staticmethod
    def forward(ctx, x):
        ctx.save_for_backward(x)
        return torch.where(x >= 0, torch.ones_like(x), -torch.ones_like(x))

    @staticmethod
    def backward(ctx, g):
        (x,) = ctx.saved_tensors
        return g * (x.abs() <= 1).to(g.dtype)


class BinarizeWeight(torch.autograd.Function):
    """W~ = alpha * sign(W), where alpha is the per-filter mean |W| (Eq. (6)).
    The backward pass follows the paper's dC/dW = dC/dW~ * (1/n + alpha * 1_{|W|<=1})"""

    @staticmethod
    def forward(ctx, w):
        n = w[0].numel()
        alpha = w.abs().mean(dim=(1, 2, 3), keepdim=True)
        ctx.save_for_backward(w, alpha)
        ctx.n = n
        return alpha * torch.where(w >= 0, torch.ones_like(w), -torch.ones_like(w))

    @staticmethod
    def backward(ctx, g):
        w, alpha = ctx.saved_tensors
        return g * (1.0 / ctx.n + alpha * (w.abs() <= 1).to(g.dtype))


class XNORConv2d(nn.Conv2d):
    """A layer combining BinActiv and BinConv: (sign(I) ⊛ sign(W)) ⊙ K α (Eq. (11)).
    Here the ±1 convolution is simulated with an ordinary floating-point convolution (no speedup)"""

    def forward(self, x):
        kh, kw = self.kernel_size
        # K: average |I| over channels (A), then convolve with a filter whose elements are all 1/(w*h)
        A = x.abs().mean(dim=1, keepdim=True)
        k = torch.full((1, 1, kh, kw), 1.0 / (kh * kw), device=x.device, dtype=x.dtype)
        K = F.conv2d(A, k, stride=self.stride, padding=self.padding)
        xb = SignSTE.apply(x)                                   # sign(I)
        w_tilde = BinarizeWeight.apply(self.weight)             # alpha * sign(W)
        out = F.conv2d(xb, w_tilde, None, self.stride, self.padding)
        return out * K                                          # multiply by the per-position beta


class XNORBlock(nn.Module):
    """XNOR-Net block: batch normalization -> binarization -> binary convolution -> pooling (Fig. 3, right)"""

    def __init__(self, c_in, c_out, pool=True):
        super().__init__()
        self.bn = nn.BatchNorm2d(c_in)
        self.conv = XNORConv2d(c_in, c_out, kernel_size=3, padding=1, bias=False)
        self.pool = nn.MaxPool2d(2) if pool else nn.Identity()

    def forward(self, x):
        return self.pool(self.conv(self.bn(x)))


# The first and last layers are not binarized (Section 4.1 of the paper)
model = nn.Sequential(
    nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),   # real-valued first layer
    XNORBlock(64, 128), XNORBlock(128, 256),
    nn.BatchNorm2d(256), nn.AdaptiveAvgPool2d(1), nn.Flatten(),
    nn.Linear(256, 10),                                              # real-valued last layer
)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)            # the paper uses Adam for XNOR-Net

x = torch.randn(8, 3, 32, 32)
y = torch.randint(0, 10, (8,))
model.train()
loss = F.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()                         # update the real-valued weights (binary weights are rebuilt every step)

model.eval()                             # inference: batch normalization switches to the statistics from training
with torch.no_grad():
    print(model(x).argmax(dim=1))

FAQ

Q. What is the difference between Binary-Weight-Network and XNOR-Net?
A.

Binary-Weight-Network (BWN) binarizes only the weights to ±1 and keeps the inputs real-valued. Convolutions become additions and subtractions, and on AlexNet it matches the accuracy of real-valued weights (top-1 56.8%). XNOR-Net also binarizes the inputs to ±1, so convolutions can be computed with the bitwise operations XNOR and bitcount, making them about 58x faster on a CPU, but AlexNet's top-1 drops to 44.2%.

Q. Why is the scale α set to the mean |W|?
A.

Minimizing the approximation error ∥W−αB∥2\lVert W - \alpha B \rVert^2 of W≈αBW \approx \alpha B with B=sign(W)B = \mathrm{sign}(W) gives the optimal α\alpha as 1n∑i∣Wi∣\frac{1}{n}\sum_i \lvert W_i \rvert, that is, the mean absolute value. In the paper's experiments, computing α\alpha with this formula gave more than 10 points higher top-1 on AlexNet than making it a learned parameter.

Q. Does XNOR-Net also run faster on GPUs?
A.

The speedups reported in the paper are estimates and measurements for a CPU implementation that uses XNOR and bitcount. Standard GPU matrix-multiplication kernels assume floating-point or integer multiply-accumulate operations, so computing ±1 values in floating point brings no speedup. A dedicated implementation that performs convolutions with bitwise operations is required for speed. The roughly 1/32 memory reduction, however, is obtained regardless of the implementation.

References

  1. M. Rastegari, V. Ordonez, J. Redmon, and A. Farhadi, "XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks," ECCV 2016, Lecture Notes in Computer Science, pp. 525–542. arXiv:1603.05279.
  2. M. Courbariaux, Y. Bengio, and J.-P. David, "BinaryConnect: Training Deep Neural Networks with binary weights during propagations," Advances in Neural Information Processing Systems 28 (NIPS 2015). arXiv:1511.00363.