AI Logic

Model Compression

BitNet

Updated:

How BitNet works. The left side shows the whole of BitNet: the embedding and output layers stay at high precision, and the linear layers of the attention and feed-forward blocks repeated L times are replaced by BitLinear. The center shows the BitLinear computation: apply LayerNorm to input x, quantize to 8 bits with absmax, compute the matrix product with 1-bit weights, and dequantize with β and γ. The right side shows subtracting the mean α from the weight matrix and taking the sign, and dividing activations by their maximum γ to obtain 8-bit integers

Background and Overview

BitNet is a Transformer trained from scratch with the weights of the linear layers of a large language model set to 1 bit, either +1 or āˆ’1. It was proposed in 2023 by Wang, Ma, Dong, and colleagues at Microsoft Research and elsewhere (published on arXiv).

The main burdens of running a large language model are reading huge weights from memory and the vast number of multiplications in matrix products. Most earlier approaches were post-training methods that quantize a trained model afterward with tools such as GPTQ or SmoothQuant. They are convenient, but accuracy drops sharply as the bit width decreases, and at 1–2 bits the model breaks down.

BitNet takes the quantization-aware training (QAT) route: it simply replaces the linear layers of a Transformer (PyTorch's nn.Linear) with a layer called BitLinear and trains a model with 1-bit weights from scratch. In BitLinear, weights are ±1 and activations are 8 bits (W1A8).

The paper's three main results are as follows.

  • At 6.7B parameters, 1-bit BitNet achieves accuracy comparable to a 16-bit model post-training quantized to 8 bits, and clearly outperforms post-training quantization at 4 bits or fewer.
  • Scaling from 125M to 30B, the loss follows a power law just like the 16-bit Transformer, and the gap between the two narrows as models get larger.
  • The arithmetic energy of matrix multiplication is estimated to be far smaller than that of a 16-bit Transformer.

Note that BitNet b1.58, released by the same group in 2024, is a method from a separate paper that makes weights ternary (āˆ’1, 0, +1). This article covers the original BitNet with ±1 weights.

Theory (How BitLinear Computes)

BitNet has the same structure as an ordinary Transformer, stacking blocks of self-attention and feed-forward networks (left of the figure at the top). The only difference is that the matrix products inside the blocks are computed with BitLinear. Components such as the input and output embeddings remain at high precision (the reasons are given later).

BitLinear computes a linear layer in the following steps (Section 2.1 of the paper; center of the figure at the top).

  1. Apply LayerNorm to the input xx.
  2. Quantize the normalized input to bb bits (8 bits in the paper) with absmax quantization.
  3. Make the weights WW 1-bit.
  4. Compute the matrix product of the 1-bit weights and the quantized input.
  5. Multiply the output by the weight and input scales to restore the original magnitude (dequantization).

Making weights 1-bit

From the weight matrix W∈RnƗmW \in \mathbb{R}^{n \times m}, first subtract the overall mean α\alpha to center it at 0, then take the sign (Eqs. (1)–(3)).

W~=Sign(Wāˆ’Ī±),α=1nmāˆ‘ijWij\widetilde{W} = \mathrm{Sign}(W - \alpha), \qquad \alpha = \frac{1}{nm} \sum_{ij} W_{ij}

Here, Sign\mathrm{Sign} returns +1 for positive values and āˆ’1 for values at or below 0. Subtracting the mean makes full use of the two available values. As a scale that reduces the difference between the real-valued and 1-bit weights, the mean absolute value β=1nm∄W∄1\beta = \frac{1}{nm}\lVert W \rVert_1 is used (Eq. (12)).

Making activations 8-bit

The input is divided by its maximum absolute value γ\gamma and scaled into the range [āˆ’Qb,Qb][-Q_b, Q_b] (Qb=2bāˆ’1Q_b = 2^{b-1}) (Eqs. (4) and (5)).

x~=Quant(x)=Clip ⁣(xƗQbγ,Ā āˆ’Qb+ϵ,Ā Qbāˆ’Ļµ),γ=∄xāˆ„āˆž\tilde{x} = \mathrm{Quant}(x) = \mathrm{Clip}\!\left(x \times \frac{Q_b}{\gamma},\ -Q_b + \epsilon,\ Q_b - \epsilon\right), \qquad \gamma = \lVert x \rVert_\infty

ϵ\epsilon is a small number that prevents overflow at the edges of the range. Only for activations before nonlinear functions such as ReLU, the minimum η\eta is subtracted first and the values are scaled into [0,Qb][0, Q_b], making all values non-negative (Eq. (6)). The range is determined over the whole tensor during training and per token during inference.

The combined formula

Putting it all together, BitLinear is the following equation (Eq. (11)).

y=W~ Quant(LN(x))×βγQby = \widetilde{W}\, \mathrm{Quant}(\mathrm{LN}(x)) \times \frac{\beta \gamma}{Q_b}

Since W~\widetilde{W} is ±1, the matrix product becomes additions and subtractions of the quantized activations. The only remaining multiplications are the final ones by the scales β\beta and γ/Qb\gamma / Q_b.

LayerNorm is placed before quantization to preserve the variance of the output. Assuming the weights and inputs are independent, the output variance is roughly E[x~2]\mathrm{E}[\tilde{x}^2] (Eqs. (8)–(10)). Normalizing the input with LayerNorm keeps this value around 1, matching the scale of a real-valued model with ordinary initialization. Inside a Transformer, this has the same implementation as the SubLN structure.

Training and Why It Is Stable

BitNet training uses three techniques (Section 2.2 of the paper).

  • Straight-through estimator (STE): Sign\mathrm{Sign} and Clip\mathrm{Clip} have zero derivative almost everywhere. In backpropagation, these functions are bypassed and the gradient flows through unchanged.
  • Keep high-precision weights: Gradients and optimizer states (such as the moving averages in Adam) are kept at high precision. High-precision weights (latent weights) are retained to accumulate updates, and they are binarized to 1 bit on every forward pass. The latent weights are not used at inference. This is the same idea as BinaryConnect.
  • Use a large learning rate: Moving a latent weight slightly does not change the 1-bit weight unless its sign flips. Convergence is therefore slow, especially early in training. After trying several approaches, the paper concluded that increasing the learning rate is the simplest and best option.

In the paper's stability experiment (Figure 5), with the same large learning rate, the 16-bit Transformer diverged early in training while BitNet converged. Moreover, BitNet's perplexity improved as the learning rate increased.

What is made 1-bit and what is kept

BitNet makes only the weights of linear layers with parameters 1-bit. Everything else is kept at high precision (8 bits in the experiments). The paper gives three reasons.

Kept componentReason
Residual connections, LayerNormNegligible relative to the total computation of a large language model
The computation inside attention that produces outputs from Q, K, and VAs models grow, its cost is much smaller than that of the parameterized projections
Input and output embeddingsSelecting the next token requires high-precision probabilities

Techniques for model parallelism

Large models split a single matrix across multiple GPUs for computation (tensor parallelism). However, α\alpha, β\beta, γ\gamma, Ī·\eta, and the mean and variance of LayerNorm are computed over the whole matrix, which increases communication between GPUs. The paper therefore divides weights and activations into GG groups along the partition dimension and computes the scales and normalization statistics per group (Eqs. (13)–(15); the normalization follows the idea of Group Normalization). This enables model parallelism without additional communication.

Experimental Results

The paper trains BitNet from 125M to 30B on English text (Pile, Common Crawl, RealNews, CC-Stories) and compares it with 16-bit Transformers under the same settings.

Comparison with post-training quantization

The table compares models at 6.7B parameters against 16-bit Transformers with post-training quantization (Table 3). It shows perplexity (PPL; lower is better) and zero-shot accuracy on four tasks (higher is better: Winograd, Winogrande, HellaSwag, StoryCloze).

Weight bitsMethodPost-training quantizationPPLWinogradWinograndeHellaSwagStoryClozeAvg.
16Transformerāˆ’15.1966.754.342.967.457.8
8Absmaxāœ“21.4360.452.038.362.753.4
8SmoothQuantāœ“15.6765.353.140.967.656.7
4GPTQāœ“16.0557.251.239.963.452.9
2QuIPāœ“70.4356.151.230.358.449.0
1SmoothQuantāœ“3.3e2150.549.524.653.144.4
1BitNetāˆ’17.0766.351.438.966.955.9

The results show the following.

  • 1-bit BitNet was about as accurate as 8-bit post-training quantization. Its average accuracy of 55.9 was close to 8-bit SmoothQuant (56.7) and higher than 4-bit GPTQ (52.9).
  • Post-training quantization collapses at 2 bits or fewer. SmoothQuant at 1 bit had an extremely large perplexity, and its accuracy was about the same as random guessing.
  • A gap to the 16-bit model remains. Perplexity was 17.07 versus 15.19, and average accuracy 55.9 versus 57.8.

Trends across model sizes

When the relationship between model size NN and loss LL is expressed as the power law L(N)=aNb+cL(N) = aN^b + c, BitNet follows a shape similar to the 16-bit Transformer (Figure 3). A fit from 125M–6.7B predicts the 13B and 30B losses well, and the gap to the 16-bit model narrows as models get larger. The paper also presents an "inference-optimal scaling law" that plots loss against inference energy, stating that BitNet achieves lower loss for the same energy.

Energy estimates

The paper estimates the arithmetic energy of matrix multiplication from a table of per-operation energy costs (Table 1; input length 512). For a 6.7B model on a 7nm process, multiplication cost 1.14J for the 16-bit Transformer versus 0.02J for BitNet, and addition cost 0.54J versus 0.04J. In BitNet's matrix products, the weights are 1-bit, so multiplications are needed only for the final scaling and the rest are additions.

Effect of each technique

In the ablation (Table 4), changing activation quantization from absmax to a learned scale (Elastic) or replacing SubLN with Pre-LN worsened perplexity from 20.34 to 22–24. The paper states that absmax makes training more stable and allows a larger learning rate.

Practical Considerations

  • It must be trained from scratch. BitNet is a quantization-aware training method, not a way to convert a trained model to 1 bit after the fact. Training requires as much data and compute as an ordinary Transformer.
  • Memory during training does not decrease. Gradients, optimizer states, and latent weights are kept at high precision, so memory shrinks only at inference.
  • The energy figures are estimates. The values in Table 1 are computed from a table of per-operation energy costs, not measured on real machines. Without computational kernels or dedicated hardware that handle 1-bit weights efficiently, the speed and energy advantages do not materialize.
  • The learning rate setting differs from usual. BitNet converged better with large learning rates that would make 16-bit models diverge. Reusing the settings of a 16-bit model as is may slow convergence.

At 6.7B, BitNet had a perplexity 1.9 higher than the 16-bit Transformer, and its average zero-shot accuracy was 1.9 points lower. Note that it is "comparable to 8-bit post-training quantization," not "the same as a 16-bit model." The successor, BitNet b1.58, narrowed the gap to 16 bits by making weights ternary.

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

BitNet can be seen as bringing XNOR-Net's approximation of "sign multiplied by the mean absolute value" to the linear layers of large language models. However, it keeps activations at 8 bits rather than ±1, and places LayerNorm (SubLN) before quantization to stabilize training.

  • When a large language model can be trained from scratch and inference memory and energy should be cut substantially, the BitNet family is a candidate. To keep the gap to 16-bit models as small as possible, BitNet b1.58 is the better fit.
  • To slim down an existing trained model, use post-training quantization such as GPTQ or AWQ, which requires no retraining.

PyTorch example

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


class BitLinear(nn.Linear):
    """BitNet's BitLinear (Eq. (11)): y = W~ Ā· Quant(LN(x)) Ā· beta Ā· gamma / Q_b
    Weights are ±1, activations are b bits. Backprop passes gradients via the straight-through estimator (STE)"""

    def __init__(self, in_features, out_features, bits=8, eps=1e-5):
        super().__init__(in_features, out_features, bias=False)
        self.ln = nn.LayerNorm(in_features, elementwise_affine=False)   # normalization corresponding to SubLN
        self.Qb = 2 ** (bits - 1)
        self.eps = eps

    def quant_weight(self):
        w = self.weight                                   # high-precision latent weights
        alpha = w.mean()                                  # Eq. (3): mean
        beta = w.abs().mean()                             # Eq. (12): mean absolute value
        w_c = w - alpha
        w_bin = torch.where(w_c > 0, torch.ones_like(w), -torch.ones_like(w))   # Eqs. (1)(2)
        w_bin = w_c + (w_bin - w_c).detach()              # STE: ±1 in forward, identity in backward
        return w_bin, beta

    def quant_act(self, x):
        # gamma = max|x| over the whole tensor in training, per token in inference (Section 2.1)
        if self.training:
            gamma = x.abs().max()
        else:
            gamma = x.abs().amax(dim=-1, keepdim=True)
        gamma = gamma.clamp(min=self.eps)
        x_s = torch.clamp(x * self.Qb / gamma, -self.Qb + self.eps, self.Qb - self.eps)   # Eq. (4)
        x_q = x_s + (torch.round(x_s) - x_s).detach()    # round to 8-bit values (STE)
        return x_q, gamma

    def forward(self, x):
        x_q, gamma = self.quant_act(self.ln(x))
        w_bin, beta = self.quant_weight()
        return F.linear(x_q, w_bin) * beta * gamma / self.Qb    # dequantize


# Example: replace the nn.Linear layers of a Transformer feed-forward block with BitLinear (Eq. (6), mapping activations before the nonlinearity to [0, Q_b], is omitted)
class BitFFN(nn.Module):
    def __init__(self, d_model=512, d_ff=2048):
        super().__init__()
        self.up = BitLinear(d_model, d_ff)
        self.down = BitLinear(d_ff, d_model)

    def forward(self, x):
        return self.down(F.gelu(self.up(x)))


ffn = BitFFN()
# The paper uses large learning rates (e.g., 4.8e-4 for 6.7B, 2.4e-3 for 125M). Adam betas are (0.9, 0.98)
optimizer = torch.optim.AdamW(ffn.parameters(), lr=2.4e-3, betas=(0.9, 0.98), weight_decay=0.01)

x = torch.randn(4, 16, 512)          # (batch, tokens, dim)
ffn.train()
loss = ffn(x).pow(2).mean()
optimizer.zero_grad()
loss.backward()                      # gradients flow to the latent weights via STE
optimizer.step()

ffn.eval()                           # inference: activation scales are computed per token
with torch.no_grad():
    print(ffn(x).shape)

FAQ

Q. What is the difference between BitNet and BitNet b1.58?
A.

They are methods from separate papers. BitNet (Wang et al., 2023) binarizes weights to +1 and āˆ’1 by subtracting the mean and taking the sign. BitNet b1.58 (Ma et al., 2024) adds 0 to make weights ternary (āˆ’1, 0, +1) by dividing by the mean absolute value and rounding. b1.58 reports perplexity comparable to 16-bit LLaMA-style models at sizes of 3B and above.

Q. Can a trained model be turned into BitNet?
A.

BitNet in the paper is a method that trains with 1-bit weights from scratch (quantization-aware training). Applying 1-bit quantization afterward to a trained 16-bit model makes perplexity extremely bad, as shown in Table 3 of the paper. Obtaining BitNet's accuracy requires retraining a model built with BitLinear.

Q. Are BitNet's weights really just 1 bit?
A.

The linear layer weights are ±1, but each matrix has one high-precision scale, the mean absolute value β\beta. In addition, components such as the input and output embeddings and LayerNorm stay at high precision, and activations are 8 bits. During training, high-precision weights are also kept to accumulate updates.

References

  1. H. Wang, S. Ma, L. Dong, S. Huang, H. Wang, L. Ma, F. Yang, R. Wang, Y. Wu, and F. Wei, "BitNet: Scaling 1-bit Transformers for Large Language Models," arXiv:2310.11453, 2023.
  2. S. Ma, H. Wang, L. Ma, L. Wang, W. Wang, S. Huang, L. Dong, R. Wang, J. Xue, and F. Wei, "The Era of 1-bit LLMs: All Large Language Models are in 1.58 Bits," arXiv:2402.17764, 2024.
  3. 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.