Skip to content

4406: 1.58-bit Quantization

⏱ 3 min read·📅 Last updated: 2026-10-17

Difficulty: ⭐⭐⭐ Advanced

Estimated Time: 3 hours

Table of Contents


Learning Objectives

After completing this lesson, you will be able to:

  • Derive the 1.58-bit number from the entropy of a {-1, 0, +1} distribution and explain why real storage is 2 bits per weight
  • Explain the core BitNet insight: ternary weights with 8-bit activations turn matrix multiplication into additions and subtractions
  • Implement a BitLinear layer — absmean weight ternarization, per-tensor INT8 activations, straight-through estimator
  • Distinguish training-from-scratch ternarization (BitNet) from post-training ternarization, and predict the quality outcome of each
  • State the 2026 deployment reality: which models exist (BitNet b1.58 2B4T, Falcon-E), which kernels run them, and when ternary beats 4401: GPTQ-style INT4 — and when it does not

Abstract

1.58-bit quantization represents each weight with three states, {-1, 0, +1}. The name is the information-theoretic floor — the entropy of a balanced ternary distribution — not a storage format; real checkpoints pack 2 bits per weight. What makes ternary interesting is not just size: with weights in {-1, 0, +1}, a matrix multiply needs no multipliers at all — only additions and subtractions — which is an energy and silicon argument, not merely a memory one. This lesson builds the real mechanism (BitNet's BitLinear: absmean-scaled ternary weights, 8-bit activations, straight-through-estimator training), then draws the line that most tutorials blur: ternary quantization is a training-time commitment, unlike GPTQ-style post-training quantization — and it ends with the honest 2026 deployment picture.

What "1.58-bit" Means

The information-theoretic number

balanced ternary distribution:
  P(-1) = 0.25    P(0) = 0.5    P(+1) = 0.25

H = -(0.25*log2(0.25) + 0.5*log2(0.5) + 0.25*log2(0.25))
  = -(-0.5 - 0.5 - 0.5)
  = 1.58 bits per weight

NOT literally 1.58 bits - fractional bits are not addressable.
What actually gets stored

real checkpoints pack 2 bits per weight (4 values per byte,
one 2-bit code per state: 00=-1  01=0  10=+1  11=unused)

size for an 8B-parameter model:
  FP32   32 GB        INT8    8 GB
  FP16   16 GB        INT4    4 GB
  2-bit ternary  ~2 GB  (plus fp16 embeddings/norms on top)

embeddings, layernorms, and output heads typically STAY at
higher precision - "2GB total" claims refer to the ternary
matmul weights only

Why Ternary Is Interesting: Additions, Not Multiplications

Memory compression alone does not motivate ternary — INT4 (4401) already compresses harder in practice. The real payoff is the arithmetic:

Dense matmul (FP16/INT8):
    y = SUM w_i * x_i        every term is a MULTIPLY-ACCUMULATE

Ternary matmul (w in {-1, 0, +1}):
    y = SUM_{w=+1} x_i  -  SUM_{w=-1} x_i

    the "+1 weights" select activations to ADD,
    the "-1 weights" select activations to SUBTRACT,
    zero weights select nothing.

    -> NO MULTIPLIER HARDWARE required. Only adders.
Why this matters beyond the math
- an FP16/FP32 multiplier consumes orders of magnitude more
  energy and silicon area than an integer adder - on ternary-
  native hardware (or packed CPU kernels) the energy-per-token
  story, not the GB story, is the headline
- the catch: this arithmetic benefit is only realized by
  kernels WRITTEN for ternary inputs. On a stock GPU stack,
  a 2-bit ternary model runs through generic int kernels and
  gets none of it (see Storage and Kernels)

Frequent misconception
ternary WEIGHTS do not make activations ternary. BitNet b1.58
keeps ACTIVATIONS at 8 bits - a ternary-activation model is a
different, much harder design point (binary networks).

BitLinear: The Actual Mechanism

BitNet b1.58 (Ma et al., 2024) replaces every nn.Linear with a BitLinear — layernorm, ternary weights via absmean scaling, 8-bit activations, all trained from scratch with a straight-through estimator:

import torch
import torch.nn as nn

class BitLinear(nn.Module):
    """BitNet b1.58 BitLinear (teaching simplification):
    ternary weights + 8-bit activations, STE-trained."""

    def __init__(self, in_features, out_features, bits_act=8):
        super().__init__()
        self.weight = nn.Parameter(
            torch.randn(out_features, in_features) * 0.02)
        self.norm = nn.LayerNorm(in_features)
        self.bits_act = bits_act

    @staticmethod
    def ternarize(w, eps=1e-5):
        """absmean rule: W_t = RoundClip(W / mean(|W|), -1, 1).
        mean(|W|) - not max - makes the scale robust to the few
        large weights LLMs always have."""
        gamma = w.abs().mean()
        return torch.clamp(torch.round(w / (gamma + eps)), -1, 1)

    def quantize_act(self, x, eps=1e-5):
        """Per-tensor INT8: scale by max, round, clamp, rescale
        so the GEMM still runs in a bf16/int8-friendly range."""
        q_max = 2 ** (self.bits_act - 1) - 1
        scale = x.abs().max() + eps
        return (x / scale * q_max).round().clamp(0, q_max) / q_max

    def forward(self, x):
        x = self.norm(x)                       # LN BEFORE quantizing

        # straight-through estimator: forward sees quantized
        # values, backward gradient flows to latent fp weights
        w_q = self.weight + (self.ternarize(self.weight)
                             - self.weight).detach()
        x_q = x + (self.quantize_act(x) - x).detach()

        return nn.functional.linear(x_q, w_q)
Reading the design decisions
1. layernorm FIRST: activations must be roughly zero-mean and
   bounded before per-tensor INT8 rounding - unnormalized
   transformer activations have outliers that eat the 8-bit grid
2. absmean, not absmax: dividing by max(|W|) collapses most
   weights to 0 when one outlier weight dominates; the mean is
   the scale that keeps the {-1, 0, +1} usage balanced
3. latent FP weights: the nn.Parameter STAYS full precision
   during training; only the forward view is ternary. Rounding
   weights in place would destroy the model (4405, Bug 1)
4. per-tensor activation scale is the simplification - the
   paper uses a learned scale; either way it is per-TENSOR,
   not per-channel, to keep the adder-only kernel story intact

Training from Scratch vs Post-Training

This is the boundary the 1.58-bit world actually lives on, and it is the opposite of the INT4 world:

GPTQ/AWQ (4401/4402)     POST-TRAINING: take a pretrained
                         checkpoint, calibrate, ship. Hours.
Ternary (BitNet)         TRAINING-TIME: the model must learn
                         WITH ternary weights from early in
                         pretraining. Weeks of compute.
Why post-training ternarization of a pretrained LLaMA fails
- a checkpoint's weights were never asked to be compressible
  to 3 states; quantizing them in place destroys the layer
  function, and there is no cheap recovery (a ternary model
  has ~1.58 bits of freedom per weight - recovery would mean
  re-learning what was destroyed)
- every credible ternary LLM result (BitNet line, TWN lineage,
  Falcon-E) trains with quantization in the loop from the
  start; PTQ ternarization results that look good are either
  heavily distilled/retrained or benchmarks run wrong
- so "convert my model to 1.58-bit" is not a thing you can do
  to a downloaded checkpoint the way "GPTQ my model" is

The classic non-BitNet recipe, Ternary Weight Networks (Li & Liu, 2016), already contained the key ideas — fixed threshold on mean magnitude, per-layer scale, STE:

TWN rule (predecessor of BitLinear's ternarize)
threshold  delta = 0.75 * mean(|W|)
scale      alpha = mean(|w_i| for |w_i| > delta)   per-layer
ternary    w_i' = alpha * sign-ish(w_i; delta)
Same STE training story: full-precision latent weights,
ternary forward view.

Ternarization Criteria

For analysis and ablations it helps to see the criteria side by side; all of them feed the same STE pattern above:

import torch

@torch.no_grad()
def threshold_for_density(w_abs: torch.Tensor, keep_fraction: float):
    """Threshold keeping exactly keep_fraction of the LARGEST
    weights. kthvalue, not torch.quantile - quantile() raises
    above ~16.7M elements (4405)."""
    n = w_abs.numel()
    keep = max(1, int(n * keep_fraction))
    return w_abs.flatten().kthvalue(n - keep + 1).values

@torch.no_grad()
def ternarize_absmean(w: torch.Tensor, ratio=0.75):
    """TWN/BitNet-style: keep weights above ratio * mean(|w|)."""
    delta = ratio * w.abs().mean()
    t = torch.zeros_like(w)
    t[w > delta] = 1
    t[w < -delta] = -1
    return t
Reading the criteria
- absmean + fixed ratio (0.75): simple, robust, what TWN and
  BitLinear use - the zero fraction emerges from the weight
  distribution, it is not a dial you set
- density-targeted (threshold_for_density): use when you need
  a guaranteed zero fraction (e.g. packing or kernel alignment);
  it is a diagnostic/ablation tool, not the training rule
- max-based thresholds (k * max(|w|)): avoid - one outlier
  weight drives the threshold and collapses most of the layer
  to zero (this is the bug in many tutorial implementations)

Accuracy Recovery

For the (rare) case of pushing an existing ternary-trained model further, or recovering after a mid-training ternarization switch, two tools carry the load:

Knowledge Distillation from the Full-Precision Teacher

import torch
import torch.nn as nn

def distill_step(teacher, student, batch, temperature=3.0, alpha=0.5):
    """Soft-target distillation: the ternary student matches the
    teacher's distribution, with the task loss to stay grounded."""
    with torch.no_grad():
        t_probs = torch.softmax(teacher(batch) / temperature, dim=-1)

    s_logits = student(batch)
    s_log_probs = torch.log_softmax(s_logits / temperature, dim=-1)

    kl = nn.KLDivLoss(reduction="batchmean")(
        s_log_probs, t_probs) * temperature ** 2
    task = nn.functional.cross_entropy(s_logits, batch["labels"])

    return alpha * kl + (1 - alpha) * task

The Training-Schedule Lever

The BitNet recipes schedule ternarization, not thresholds
1. start pretraining in full/bf16 precision (the latent
   weights and the optimizer need stable statistics early)
2. switch to BitLinear (or raise the quantization schedule)
   once the LR has decayed and the model is past the unstable
   warmup phase (5502) - typically after a fraction of total
   tokens, then train to the end in ternary
3. distill from the fp latent view during the switch window to
   flatten the loss spike

What NOT to do: flip every layer to ternary at step 0 with a
high LR - the STE gradient is a coarse approximation and
early training needs it least exactly when it is least
trustworthy.

Storage and Kernels

2-bit Packing (vectorized)

import torch

def pack_ternary(t: torch.Tensor) -> torch.Tensor:
    """Pack {-1, 0, +1} -> 2 bits per weight (4 per byte).
    Vectorized: a per-element Python loop takes hours on a 7B
    tensor; this is one reduction."""
    t = t.flatten()
    t = t[: (t.numel() // 4) * 4]           # demo: trim the tail
    codes = (t + 1).long().view(-1, 4)      # {-1,0,1} -> {0,1,2}
    weights = torch.tensor([1, 4, 16, 64],
                           device=t.device, dtype=torch.long)
    return (codes * weights).sum(dim=1).to(torch.uint8)

def unpack_ternary(packed: torch.Tensor, shape) -> torch.Tensor:
    vals = [((packed.long() >> s) & 0b11) - 1 for s in (0, 2, 4, 6)]
    return torch.stack(vals, dim=1).flatten().reshape(shape)

Kernel Reality, 2026

Where ternary actually RUNS fast
- bitnet.cpp (Microsoft, 2024): the reference ternary kernel
  stack - packed CPU (and some NPU) paths built around the
  adder-only arithmetic; this is where the energy claims live
- ternary-native edge models (BitNet 2B4T, Falcon-E) ship
  with/know of these kernels

Where it does NOT
- mainstream GPU serving stacks (vLLM, TensorRT-LLM, exllama)
  have no native ternary GEMM path - a 2-bit ternary model
  served there falls back to generic int kernels and LOSES to
  an INT4 GPTQ model (4401) in both speed and quality
- llama.cpp's 2-3-bit quants (IQ2/IQ3) are GRID quantization,
  not ternary networks - do not confuse them; they quantize
  pretrained weights (the PTQ world) rather than train ternary

State of the Art, 2026

Verified milestones (paper-reported, workload-dependent)

BitNet b1.58 (2024)
  - trains 3B-scale LLMs from scratch in ternary-weights/
    int8-acts; reports matching full-precision baselines of
    the same size/data at that scale - the foundational claim
    of the line
BitNet b1.58 2B4T (Microsoft, 2025)
  - 2B params, 4T training tokens, OPEN WEIGHTS (MIT) - the
    first widely available native-ternary model; ~0.4 GB
    weight footprint; positioned for CPU/edge inference
Falcon-E (TII, 2025)
  - 1.3B-7.5B 1.58-bit series trained natively; same
    from-scratch recipe, edge/serving-oriented

The honest deployment framing
- datacenter serving: INT4 GPTQ/AWQ (4401/4402) is the
  production answer; ternary has no kernel + no ecosystem win
- edge/CPU, energy-first: ternary-native models + bitnet.cpp
  are genuinely differentiated - this is where 1.58-bit earns
  its existence
- do not post-train your way to ternary; if you want a
  ternary model, deploy one that was TRAINED ternary

Best Practices

1. Say "2-bit packed" when talking storage, "1.58-bit" only
   when talking entropy - mixing them signals tutorial copy
2. absmean scaling + layernorm-before-quant + STE on latent
   fp weights: the three load-bearing parts of BitLinear;
   hand-rolled absmax variants collapse layers to zero
3. Never round weights in place - latent full-precision
   parameters, quantized forward view, always (4405)
4. Ternary is a training decision, not a conversion: budget
   pretraining-scale compute or use released ternary models
5. Benchmark against INT4 GPTQ at the same size before
   choosing ternary for GPU serving - the INT4 stack usually
   wins today
6. For edge/energy workloads, evaluate with bitnet.cpp-class
   kernels on TARGET hardware; energy claims do not transfer
   from paper benchmarks
7. kthvalue/topk for thresholds; torch.quantile breaks past
   ~16.7M elements

Summary

1.58-bit quantization gives each weight three states, {-1, 0, +1}: the name is the entropy of a balanced ternary distribution, while real checkpoints pack two bits. The payoff is architectural - ternary matmuls need no multipliers, only additions - and that is where the energy and silicon win lives. This lesson built BitLinear as the concrete mechanism, contrasted training from scratch with post-training recovery, gave the ternarization criteria and the accuracy-recovery tricks, and closed with storage, kernels, and the 2026 state of the art.

References


Next Steps