AI Logic

Model Compression

BinaryConnect

Updated:

How BinaryConnect works. The left side shows one training step: the stored real-valued weights w are binarized, forward and backward propagation are computed with the binary weights w_b, and the resulting gradient updates the real-valued w, which is clipped to [−1, 1]. The right side shows two ways to map weights to ±1: deterministic binarization that takes the sign of a real-valued weight matrix, and a graph of stochastic binarization where the probability of +1 is given by a hard sigmoid

Background and Overview

BinaryConnect is a method that trains a network while binarizing weights to +1 or −1 only during forward and backward propagation. It was proposed by Courbariaux, Bengio, and David in 2015 and presented at NIPS 2015.

Most of the computation in a neural network consists of multiply-accumulate operations that sum products of weights and inputs. If weights can only be +1 or −1, each multiplication becomes either "add as is" or "add with the sign flipped." Multiplier circuits are large in area and power, so this yields big savings on dedicated hardware.

However, holding weights only as binary values from the start does not train well. SGD moves weights by accumulating many small updates, so when each update is much smaller than the binary step size, the update is lost to rounding. BinaryConnect solves this by keeping a separate set of real-valued weights and accumulating updates there.

As an everyday analogy, the real-valued weights in BinaryConnect are like "savings," and the binary weights are like "whether the bill available today is a 1,000-yen note or nothing." Daily small change (small updates) accumulates in the savings, and only when the savings cross a certain amount does the usable bill switch.

On MNIST (in a setting without convolutions), CIFAR-10, and SVHN, the paper reported error rates with binary weights that were nearly the same as or better than those with real-valued weights. It was the starting point for research on binary weights, and later methods such as XNOR-Net and BitNet for large language models inherit this framework of "update with real-valued weights, compute with binary weights."

Theory (Propagate with Binary Weights, Update Real-Valued Weights)

BinaryConnect consists of two parts: a way to binarize weights and a training procedure.

Two ways to map weights to ±1

The simplest is deterministic binarization, which uses the sign (Eq. (1) in the paper).

wb={+1w≥0−1otherwisew_b = \begin{cases} +1 & w \ge 0 \\ -1 & \text{otherwise} \end{cases}

Here, ww is the real-valued weight and wbw_b is the binarized weight. The other is stochastic binarization, which chooses +1 with a probability that depends on the value of the real-valued weight (Eqs. (2) and (3)).

wb={+1with probability p=σ(w)−1with probability 1−p,σ(x)=clip ⁣(x+12, 0, 1)w_b = \begin{cases} +1 & \text{with probability } p = \sigma(w) \\ -1 & \text{with probability } 1 - p \end{cases}, \qquad \sigma(x) = \mathrm{clip}\!\left(\frac{x + 1}{2},\ 0,\ 1\right)

σ\sigma is a piecewise-linear function called the hard sigmoid, chosen because it is cheaper to compute than the ordinary sigmoid. When ww lies in [−1,1][-1, 1], the expected value of wbw_b is 1⋅σ(w)+(−1)(1−σ(w))=w1 \cdot \sigma(w) + (-1)(1 - \sigma(w)) = w. In other words, stochastic binarization rounds in a way that matches the original real-valued weight on average (right side of the figure at the top).

Training procedure

For each mini-batch, training proceeds as follows (Algorithm 1 in the paper).

  1. Binarize the stored real-valued weights ww to obtain wbw_b.
  2. Run forward propagation from input to output using wbw_b.
  3. Run backpropagation from output to input using wbw_b to obtain the gradients with respect to each layer's activations.
  4. Compute the gradient with respect to the binary weights, ∂C/∂wb\partial C / \partial w_b, and use it to update the real-valued weights ww.
  5. Clip the updated ww to the range [−1,1][-1, 1]. For the next mini-batch, this ww is binarized again.

Steps 4 and 5 combine into the following equation (η\eta is the learning rate).

wt=clip ⁣(wt−1−η ∂C∂wb, −1, 1)w_t = \mathrm{clip}\!\left(w_{t-1} - \eta\, \frac{\partial C}{\partial w_b},\ -1,\ 1\right)

The binarization function has zero slope almost everywhere, so gradients would not flow through it as is. BinaryConnect ignores the binarization and uses the gradient with respect to the binary weights directly as the gradient of the real-valued weights. This is the same idea as the straight-through estimator (STE) described in the quantization article.

Step 5 clips to [−1,1][-1, 1] because binarization looks only at the sign of ww. Without a bounded range, the real-valued weights could grow arbitrarily large without any effect on the binary weights. Keeping them within the range lets the sign flip quickly when the gradient direction changes.

Weights at inference

The paper lists three ways to use the trained network (Section 2.6).

UsageWeights used at inferenceBenefit at inference
Use binary weightsDeterministically binarized wbw_bNo multiplications; weight memory drops greatly
Use real-valued weightsReal-valued wwInference is not faster (only training is accelerated)
Binarize stochastically many times and averageMany stochastically sampled wbw_bEnsemble effect (heavy, since it computes many times)

In the paper's experiments, deterministic binarization is evaluated with the first approach and stochastic binarization with the second. Using real-valued weights at inference in the stochastic case follows the same idea as Dropout removing its noise at inference.

Why Training with Binary Weights Works

The paper gives two reasons why BinaryConnect can learn.

  • Small updates accumulate in the real-valued weights. A single SGD update is very small, so holding only binary weights would lose updates to rounding. Accumulating gradients in real-valued weights averages the gradients over many mini-batches and cancels out noise. The paper explains that what matters at the end of training is the sign of the weights, and that the continuous quantity ww is moved little by little to determine that sign (Eq. (4)).
  • Binarization acts as noise and serves as regularization. Rounding weights to ±1 can be viewed as adding noise to the weights. Stochastic binarization in particular perturbs weights while preserving their expected value, giving a regularization effect similar to DropConnect, which randomly sets some weights to 0. Indeed, in the paper's learning curves, BinaryConnect had higher training loss and trained more slowly, yet achieved lower validation error.

BinaryConnect binarizes only the weights. Activations (layer outputs) remain real-valued, so the computation becomes "add or subtract the real-valued activation depending on the sign of the weight." Binarizing activations as well lets the multiplications themselves be replaced by bit operations, but accuracy tends to drop (see XNOR-Net).

To stabilize training, the paper uses batch normalization in all experiments. With weights at ±1, the scale of layer outputs changes easily, and batch normalization reduces that effect. In the convolutional network experiments, the paper also uses Adam and scales each layer's weight learning rate by the coefficient from Xavier initialization. On a small CNN for CIFAR-10, this scaling reduced the error rate from 12.81% (plain Adam) to 10.47% (Table 1 in the paper).

Experimental Results

The paper compares test error rates on permutation-invariant MNIST (a 3-layer MLP with 1024 units per layer) and on CIFAR-10 and SVHN (6 convolutional layers similar to VGG plus 2 fully connected layers; SVHN uses half the units) (Table 2; lower is better). The output layer is an L2-SVM (minimizing the squared hinge loss).

MethodMNISTCIFAR-10SVHN
No regularizer (real-valued weights)1.30 ± 0.04%10.64%2.44%
BinaryConnect (deterministic)1.29 ± 0.08%9.90%2.30%
BinaryConnect (stochastic)1.18 ± 0.04%8.27%2.15%
50% Dropout1.01 ± 0.04%−−

The results show the following.

  • Propagating with 1-bit weights was no worse than real-valued weights. On all three datasets, both deterministic and stochastic versions achieved error rates equal to or lower than "no regularizer."
  • Stochastic binarization had a stronger regularization effect. On CIFAR-10, the error dropped from 10.64% to 8.27%. Note, however, that the stochastic method in the table uses real-valued weights at inference.
  • On MNIST, Dropout was the stronger regularizer. The paper also states that stochastic BinaryConnect is a somewhat weaker regularizer than Dropout.

On larger datasets, by contrast, the accuracy gap becomes noticeable. The XNOR-Net paper (Rastegari et al., 2016) trained AlexNet on ImageNet with deterministic BinaryConnect and reported a top-1 accuracy of 35.4% (56.6% with real-valued weights). The same paper's method that multiplies weights by a per-filter scale (Binary-Weight-Network) reached 56.8%.

Practical Considerations

  • Real-valued weights are also needed during training. Real-valued weights are stored in addition to binary weights and the updates are applied to them, so memory during training does not decrease. Memory shrinks only after training, when only the binary weights are kept.
  • For lightweight inference, use deterministic binarization. In the paper's experiments, stochastic binarization achieves better accuracy when real-valued weights are used at inference. If binary weights are to be used at inference as well, use weights trained with deterministic binarization.
  • Whether it gets faster depends on hardware and implementation. Replacing multiplications with additions pays off only with dedicated hardware or computational building blocks (kernels) written for binary weights. Computing it as a real-valued matrix multiplication on an ordinary GPU is not faster.
  • Batch normalization and learning-rate scaling are required. The paper uses batch normalization in all experiments and scales per-layer learning rates by the initialization coefficients. Without them, the same accuracy is not guaranteed.

BinaryConnect's accuracy was verified on small image datasets such as MNIST, CIFAR-10, and SVHN. On a large dataset such as ImageNet, a reproduction in the XNOR-Net paper gave an accuracy more than 20 points below real-valued weights. When binarizing weights in large models, consider approaches such as XNOR-Net, which applies a scale.

Comparison with Other Methods

The table compares methods that make weights binary or ternary with ordinary low-bit quantization along the same dimensions.

MethodWeight valuesWeight scaleActivationsMain target
BinaryConnect+1, −1NoneReal-valuedSmall image recognition (MLP, CNN)
XNOR-Net (binary weights only)+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 scales)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 / per group16-bitPretrained large language models

All methods from BinaryConnect up to (but not including) GPTQ keep real-valued weights while training with binary or ternary weights in the computation (quantization-aware training). Only GPTQ quantizes a trained model without retraining it.

  • To understand how weight binarization works or to experiment with small models, BinaryConnect, the simplest of these, is the starting point.
  • To cut weight memory to nearly 1/32 in large image recognition models, XNOR-Net's binary-weights-only method with scaling is a good fit.
  • To train a large language model in low bit width from the start, BitNet and BitNet b1.58 are candidates; to slim down an existing model, post-training quantization such as GPTQ is a candidate.

PyTorch example

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


class Binarize(torch.autograd.Function):
    """Map weights to ±1. In backprop, ignore binarization and pass the gradient straight to the real-valued weights"""

    @staticmethod
    def forward(ctx, w, stochastic):
        if stochastic:
            p = torch.clamp((w + 1) / 2, 0, 1)                   # hard sigmoid (Eq. (3))
            plus = torch.rand_like(w) < p                        # +1 with probability p (Eq. (2))
        else:
            plus = w >= 0                                        # decided by sign (Eq. (1))
        return torch.where(plus, torch.ones_like(w), -torch.ones_like(w))

    @staticmethod
    def backward(ctx, grad_out):
        return grad_out, None                                    # use ∂C/∂w_b as the gradient of w


class BinaryLinear(nn.Linear):
    """Linear layer that propagates with binary weights w_b and updates real-valued weights w"""

    def __init__(self, in_features, out_features, stochastic=False):
        super().__init__(in_features, out_features)
        self.stochastic = stochastic

    def forward(self, x):
        if self.training:
            w = Binarize.apply(self.weight, self.stochastic)    # re-binarize for every mini-batch
        elif not self.stochastic:
            w = Binarize.apply(self.weight, False)              # inference: deterministic binary weights
        else:
            w = self.weight                                      # inference: real-valued weights if stochastic (as in the paper's experiments)
        return F.linear(x, w, self.bias)


def clip_weights(model):
    """After the update, clip the real-valued weights to [-1, 1] (Section 2.4)"""
    with torch.no_grad():
        for m in model.modules():
            if isinstance(m, BinaryLinear):
                m.weight.clamp_(-1, 1)


# Similar to the paper's MNIST experiment: 3 hidden layers + batch normalization
model = nn.Sequential(
    BinaryLinear(784, 1024), nn.BatchNorm1d(1024), nn.ReLU(),
    BinaryLinear(1024, 1024), nn.BatchNorm1d(1024), nn.ReLU(),
    BinaryLinear(1024, 1024), nn.BatchNorm1d(1024), nn.ReLU(),
    BinaryLinear(1024, 10),
)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

x = torch.randn(200, 784)
y = torch.randint(0, 10, (200,))

model.train()                                    # training: propagate with binary weights
loss = F.cross_entropy(model(x), y)              # the paper uses an L2-SVM (squared hinge loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()                                 # update the real-valued weights
clip_weights(model)                              # clip to [-1, 1]

model.eval()                                     # inference: if deterministic, only ±1 weights are needed
with torch.no_grad():
    pred = model(x).argmax(dim=1)
print(pred[:10])

FAQ

Q. Why does BinaryConnect keep real-valued weights during training?
A.

Because a single SGD update is very small, and holding weights only as ±1 would lose the updates to rounding. Accumulating gradients in real-valued weights lets updates from many mini-batches add up, and the sign flips once enough has accumulated. The real-valued weights are used only during training; with deterministic binarization, only the ±1 weights wbw_b need to be kept for inference.

Q. Should I use deterministic or stochastic binarization?
A.

In the paper's experiments, stochastic binarization gave lower error rates (8.27% on CIFAR-10 versus 9.90% for deterministic). However, the stochastic figures were obtained using real-valued weights at inference. If inference should also use only ±1 weights, that is, if memory and multiplications are to be reduced, use deterministic binarization.

Q. How much lighter does computation become with BinaryConnect?
A.

Since weights are ±1, multiplications by weights become additions and subtractions. The paper estimates that training no longer needs the multiplications in forward and backward propagation (about 2/3 of the total), that inference with deterministic binarization needs no multiplications, and that weight memory shrinks to at most 1/16 of 16-bit storage. This benefit appears only with hardware or implementations that support binary computation; computing it as a real-valued matrix multiplication on an ordinary GPU is not faster.

References

  1. 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.
  2. 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.
  3. MatthieuCourbariaux, "BinaryConnect" (GitHub).