Quantizers#

A quantizer rounds every element of a tensor to a format. It is the simplest thing MPTorch does and the building block of everything else. A layer applies quantizers to its weights and activations, a straight-through estimator wraps one, and a quantization-aware-training observer sits in front of one. An elementwise quantizer rounds each element independently:

\[\tilde{x}_i = Q_{F,\circ}(x_i) \qquad \text{for every element } i,\]

A block quantizer first chooses each block’s scale from the block’s values and then rounds each of its elements (Block quantization and packed storage). Elementwise quantizers have three spellings, described below from the most explicit to the most convenient.

The functions#

binaryK_quantize() and superfp_quantize() take a tensor and the format’s parameters spelled out, and return a new tensor of the same shape and dtype.

docs/snippets/quantizers_functions.py#
"""The two elementwise quantization functions."""

import warnings

import torch

from mptorch import RoundMode
from mptorch.quant import binaryK_quantize, superfp_quantize

torch.manual_seed(0)
torch.set_printoptions(precision=5)

x = torch.randn(6)
print("x              ", x)
print("Binary8p4, RNE ", binaryK_quantize(x, K=8, P=4))
print("Binary8p4, RZ  ", binaryK_quantize(x, K=8, P=4, rounding_mode=RoundMode.RZ))
print("Binary8p3, RNE ", binaryK_quantize(x, K=8, P=3))
print("superfp        ", superfp_quantize(x, man_bits=3, exp_bits=4, normal_binades=2, bias=7))

# Every floating-point dtype torch trains in is accepted. A float64 tensor is
# rounded in binary64, the others in binary32, and the result comes back in the
# input's dtype.
for dtype in (torch.float64, torch.float16, torch.bfloat16):
    y = binaryK_quantize(x.to(dtype), K=8, P=4)
    print(f"{str(dtype):<14}", y.dtype, y.tolist())

# Storing the result in float16 or bfloat16 rounds it once more, so the format
# has to fit that dtype too. The inputs are already float16 values, so only an
# edge of the format's range can miss: E5M2's layout (bias 15) reaches 98304, and
# an input near float16's top rounds up to 65536 -- which float16 stores as
# infinity, whatever the format's saturation mode says.
x16 = torch.tensor([60000.0], dtype=torch.float16)
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    y16 = binaryK_quantize(x16, K=8, P=3, bias=15, rounding_mode=RoundMode.RU)
y32 = binaryK_quantize(x16.float(), K=8, P=3, bias=15, rounding_mode=RoundMode.RU)
print(f"\nE5M2's layout, RU, of 60000: {y32.item()} in float32, {y16.item()} in float16")
print(f"{caught[0].category.__name__}: {caught[0].message}")

# Stochastic rounding takes its random bits from below the target mantissa, in
# the carrier the rounding happens in, so the format's mantissa and its random
# bits share the carrier's: binary64's 52 bits for float64, binary32's 23 for
# the rest.
y = binaryK_quantize(x.double(), K=8, P=4, prng_bits=21, rounding_mode=RoundMode.SR)
print("\nfloat64, 3 + 21 bits:", y.tolist())
try:
    binaryK_quantize(x.to(torch.bfloat16), K=8, P=4, prng_bits=21, rounding_mode=RoundMode.SR)
except ValueError as e:
    print("bfloat16: ValueError:", e)

# CPU and CUDA give the same result under every deterministic rounding mode.
if torch.cuda.is_available():
    big = torch.randn(1_000_000)
    for mode in (RoundMode.RNE, RoundMode.RZ, RoundMode.RO):
        same = torch.equal(
            binaryK_quantize(big, K=8, P=4, rounding_mode=mode),
            binaryK_quantize(big.cuda(), K=8, P=4, rounding_mode=mode).cpu(),
        )
        print(f"CPU == CUDA under {mode.name}: {same}")
output#
x               tensor([ 1.54100, -0.29343, -2.17879,  0.56843, -1.08452, -1.39860])
Binary8p4, RNE  tensor([ 1.50000, -0.28125, -2.25000,  0.56250, -1.12500, -1.37500])
Binary8p4, RZ   tensor([ 1.50000, -0.28125, -2.00000,  0.56250, -1.00000, -1.37500])
Binary8p3, RNE  tensor([ 1.50000, -0.31250, -2.00000,  0.62500, -1.00000, -1.50000])
superfp         tensor([ 2.00000, -0.25000, -2.00000,  0.50000, -1.00000, -1.00000])
torch.float64  torch.float64 [1.5, -0.28125, -2.25, 0.5625, -1.125, -1.375]
torch.float16  torch.float16 [1.5, -0.28125, -2.25, 0.5625, -1.125, -1.375]
torch.bfloat16 torch.bfloat16 [1.5, -0.28125, -2.25, 0.5625, -1.125, -1.375]

E5M2's layout, RU, of 60000: 65536.0 in float32, inf in float16
FormatRangeWarning: BinaryK(K=8, P=3, bias=15) reaches past float16's largest finite value, which is not on the format's grid: a float16 input near it rounds up out of float16's range and is stored as infinity, whatever the saturation mode

float64, 3 + 21 bits: [1.5, -0.28125, -2.0, 0.5625, -1.125, -1.375]
bfloat16: ValueError: BinaryK(K=8, P=4, bias=8) asks for 21 stochastic-rounding bits below a 3-bit mantissa; they are drawn from the binary32 significand the rounding happens in, which has 23 bits to share. binary64 holds all of it: a float64 tensor's carrier, which carrier=torch.float64 gives a narrower tensor too.
CPU == CUDA under RNE: True
CPU == CUDA under RZ: True
CPU == CUDA under RO: True

Some things to know about them:

  • bias is optional for binaryK_quantize, because P3109 defines a default: \(2^{K-P-1}\), or \(2^{K-P}\) unsigned. It is required for superfp_quantize, because a superfp’s bias is part of the format’s design and no rule derives it (Formats and rounding, “SuperFP: precision at the top, range below”).

  • Any floating dtype PyTorch trains in is accepted: float32, float64, float16 and bfloat16. A float64 input is rounded directly in binary64. The others are rounded on their float32 value, in binary32 unless the call names binary64. float64 and the carrier below shows what that changes.

  • The result is stored back in the input’s dtype, whichever carrier rounded it, so a float16 or bfloat16 result is rounded once more. The input is already a value of that dtype, so only an edge of the format’s range can miss the dtype’s grid, and the call warns when one can. The run shows the top of E5M2’s layout meeting float16’s. Formats and rounding gives the rule, and the stricter one that a GEMM’s result is held to.

  • The result is a new tensor, and the input is never modified. The in-place twins, binaryK_quantize_ and superfp_quantize_, are the exception and have a section of their own.

  • NaN passes through with its payload. An infinity passes through too, except under SatFinite in either domain (SaturationMode.SAT_FINITE and SAT_FINITE_EXTENDED), which clamps it to the largest finite value like any other overflow.

  • prng_bits only matters under RoundMode.SR. The random bits are drawn in the carrier, below the format’s mantissa, so the format’s mantissa and the random bits share the carrier’s mantissa bits: 23 in binary32 and 52 in binary64, as the run shows.

  • Every function here also takes carrier, described below.

  • CPU and CUDA produce bit-identical results under every deterministic mode. Under SR, CUDA draws from its own default generator, so torch.manual_seed reproduces a CUDA run on CUDA. An Apple GPU ("mps") draws from the CPU’s generator and matches the CPU bit for bit in every mode, SR included (On an Apple GPU gives the exceptions).

fixedpoint_quantize() is the function for a FixedPoint format (FixedPoint: one step across the range). It takes wl, fl, is_signed and symmetric in place of a float’s fields, and no saturation_mode, because a fixed-point result always saturates. The points above apply to it too: the dtypes, the carrier, the storage check, prng_bits (which shares the carrier’s precision, 24 bits or 53, with the format’s magnitude bits) and the backends. Under SR it is exact, the random bits added on the input’s word directly below the step (FixedPoint: one step across the range).

docs/snippets/quantizers_fixedpoint.py#
"""The fixed-point quantizer: the function, its in-place twin, and Quant."""

import warnings

import torch

from mptorch import FixedPoint, RoundMode
from mptorch.quant import Quant, fixedpoint_quantize, fixedpoint_quantize_

torch.manual_seed(0)
torch.set_printoptions(precision=5)

x = torch.randn(6)
print("x                ", x)
print("wl=8, fl=4       ", fixedpoint_quantize(x, wl=8, fl=4))
# Two more fractional bits: a finer step, and a range of [-2, 2) instead of [-8, 8).
print("wl=8, fl=6       ", fixedpoint_quantize(x, wl=8, fl=6))
print(
    "SR, 8 random bits", fixedpoint_quantize(x, wl=8, fl=4, prng_bits=8, rounding_mode=RoundMode.SR)
)

# Quant calls the function, with the arguments taken from the format.
q = Quant(FixedPoint(8, 4))
print("\nQuant == function:", torch.equal(q(x), fixedpoint_quantize(x, wl=8, fl=4)))

# The in-place twin writes over its argument and returns it.
y = x.clone()
out = fixedpoint_quantize_(y, wl=8, fl=4)
print("in place:         ", out is y, torch.equal(y, fixedpoint_quantize(x, wl=8, fl=4)))

# The magnitude bits must fit the carrier's precision: 24 bits in binary32, 53 in
# binary64. A float64 tensor is rounded in binary64, which holds the wider format.
try:
    fixedpoint_quantize(x, wl=26, fl=20)
except ValueError as e:
    print("\nfloat32: ValueError:", e)
wide = fixedpoint_quantize(x.double(), wl=26, fl=20)
print("float64:", wide[:2].tolist())

# A float16 or bfloat16 result is rounded once more when it is stored. Only an
# end of the range can miss the dtype's grid, and the call warns when one can:
# FixedPoint(16, 14)'s largest value, 2 - 2**-14, needs 15 bits and float16 has
# 11, so 3.0, which saturates to it, is stored as 2.0.
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    h = fixedpoint_quantize(torch.tensor([1.0, 3.0], dtype=torch.float16), wl=16, fl=14)
print("\nfloat16 result: ", h.tolist())
for w in caught:
    print("  warning:", str(w.message).split(". ")[0])
# FixedPoint(8, 6)'s largest value, 1.984375, needs 7 bits: bfloat16 holds it.
b = fixedpoint_quantize(torch.tensor([1.0, 3.0], dtype=torch.bfloat16), wl=8, fl=6)
print("bfloat16 result:", b.tolist(), "(no warning)")

# CPU and CUDA return the same words in every deterministic mode.
if torch.cuda.is_available():
    x = torch.randn(1 << 16) * 4
    modes = [m for m in RoundMode if not m.is_stochastic]
    same = all(
        torch.equal(
            fixedpoint_quantize(x, wl=8, fl=4, rounding_mode=m),
            fixedpoint_quantize(x.cuda(), wl=8, fl=4, rounding_mode=m).cpu(),
        )
        for m in modes
    )
    print(f"\nCPU == CUDA on {x.numel()} values in {len(modes)} modes:", same)
output#
x                 tensor([ 1.54100, -0.29343, -2.17879,  0.56843, -1.08452, -1.39860])
wl=8, fl=4        tensor([ 1.56250, -0.31250, -2.18750,  0.56250, -1.06250, -1.37500])
wl=8, fl=6        tensor([ 1.54688, -0.29688, -2.00000,  0.56250, -1.07812, -1.40625])
SR, 8 random bits tensor([ 1.50000, -0.31250, -2.18750,  0.56250, -1.12500, -1.37500])

Quant == function: True
in place:          True True

float32: ValueError: FixedPoint(wl=26, fl=20) asks for 25 bits of precision, its magnitude bits, and it is rounded in binary32, which has 24. binary64 holds all of it: a float64 tensor's carrier, which carrier=torch.float64 gives a narrower tensor too.
float64: [1.5409965515136719, -0.2934284210205078]

float16 result:  [1.0, 2.0]
  warning: FixedPoint(wl=16, fl=14)'s largest value is not a float16 value; saturated results are rounded again
bfloat16 result: [1.0, 1.984375] (no warning)

CPU == CUDA on 65536 values in 6 modes: True

The end of the run shows the storage check on a narrower result and the two backends side by side:

  • A float16 or bfloat16 result is held to the elementwise storage rule, as a float format’s is: only an end of the range can miss the dtype’s grid. FixedPoint(16, 14)’s largest value needs 15 bits, so a float16 result warns, and an input that saturates to it is stored as 2.0. FixedPoint(8, 6)’s largest value fits bfloat16’s 8 bits, so that call is silent. FixedPoint: one step across the range gives the rule.

  • CPU and CUDA return the same words in every deterministic mode. This run was recorded on a machine with an NVIDIA GPU; without one, the snippet skips that line.

float64 and the carrier#

A quantizer rounds in its carrier (Formats and rounding): by default binary64 for a float64 tensor and binary32 for the other three dtypes. For a float64 tensor, binary64 has three consequences. carrier=torch.float64 gives the other dtypes those of the three that their values can use.

  • Wider formats. The format is held to binary64’s bounds, so up to 53 bits of precision and ten exponent bits are simulated exactly. The same call on a float32 tensor raises, because binary32 has only 24 bits to round in.

  • Rounded once. A value that float32 cannot hold is rounded on its own bits. 1.0625 + 2**-30 is above the tie between 1.0 and 1.125 on Binary8p4’s grid, and rounds up. Narrowed to float32 it is the tie, and round-to-nearest-even takes it down.

  • Wider random draws. Stochastic rounding takes its random bits below the format’s mantissa in the carrier. P - 1 + prng_bits may therefore reach 52 instead of 23, and each element draws two words of its random stream.

carrier=torch.float64 rounds a float32, float16 or bfloat16 tensor in binary64. The tensor is widened, rounded under binary64’s bounds, and the result is narrowed back to the tensor’s dtype. This is bit for bit the float64 call on the widened tensor, stored with one rounding.

For an elementwise quantizer this gives the wider formats and the wider random draws, but not the single rounding. The tensor’s values are already values of its dtype, and a format that binary32 carries rounds them to the same answer in either carrier, as the run checks. The result is held to what its dtype can store (Formats and rounding). For float32 that is 24 bits of precision and binary32’s range at the edges.

carrier=torch.float32 names binary32. A float64 tensor refuses it, because the carrier is never narrower than the tensor. Quant takes the same keyword.

docs/snippets/quantizers_float64.py#
"""An elementwise quantizer's carrier: binary64 for float64, and for any tensor naming it."""

import math

import torch

from mptorch import BinaryK, RoundMode
from mptorch.quant import Quant, binaryK_quantize

F32, F64 = torch.float32, torch.float64
torch.manual_seed(0)

# A float64 tensor is rounded in binary64, so a format float32 cannot carry is
# reachable: 30 bits of precision, each value rounded to the nearest multiple
# of its binade's step, 2**(e - 29).
x = torch.tensor([math.pi, -math.e, 1 / 3, 1e-9], dtype=F64)
q = binaryK_quantize(x, K=40, P=30)
for v, r in zip(x.tolist(), q.tolist(), strict=True):
    step = 2.0 ** (math.floor(math.log2(abs(v))) - 29)
    exact = r == round(v / step) * step
    print(f"{v!r:>21} -> {r!r:<21} the nearest multiple of 2^{round(math.log2(step))}: {exact}")
try:
    binaryK_quantize(x.float(), K=40, P=30)
except ValueError as e:
    print("float32:", str(e).split(": ")[0])

# The float64 input is rounded once, directly. Its float32 neighbour has lost
# the 2**-30 and sits on the tie itself, whichever carrier rounds it:
# carrier=torch.float64 widens the float32 tensor, rounds it in binary64 and
# stores the result back as float32.
t = torch.tensor([1.0625 + 2**-30, 1.1875 - 2**-30], dtype=F64)
print("\nfloat64                        ", binaryK_quantize(t, K=8, P=4).tolist())
print("float32                        ", binaryK_quantize(t.float(), K=8, P=4).tolist())
t64 = binaryK_quantize(t.float(), K=8, P=4, carrier=F64)
print("float32, carrier=torch.float64 ", t64.tolist(), t64.dtype)

# That is the rule for a tensor's own values: a format binary32 carries rounds
# them to the same answer in either carrier. So for float32, float16 or
# bfloat16 values, carrier=torch.float64 changes what the format may be, and
# the random draws of stochastic rounding, not a deterministic answer.
y = torch.randn(10_000)
for dtype in (F32, torch.float16, torch.bfloat16):
    yd = y.to(dtype)
    wide = binaryK_quantize(yd, K=8, P=4, carrier=F64)
    same = torch.equal(wide, binaryK_quantize(yd, K=8, P=4))
    print(f"{str(dtype):<14} carrier=torch.float64 -> {wide.dtype}, same as binary32's: {same}")

# Quant takes the same keyword, for a layer's quantizer slots.
q64 = Quant(BinaryK(8, 4), carrier=F64)
print(
    "Quant(..., carrier=torch.float64) agrees:",
    torch.equal(q64(y), binaryK_quantize(y, 8, 4, carrier=F64)),
)

# Stochastic rounding draws its random bits in the carrier, below the format's
# mantissa: 52 bits to share in binary64, 23 in binary32. The input sits
# 0.3 + 2**-37 of the way from 1.0 to 1.125, which 40 bits resolve. A float32
# tensor is refused 40 bits in its own carrier, and given them by naming binary64.
v = torch.full((1_000_000,), 1 + 0.3 * 0.125 + 2**-40, dtype=F64)
sr = binaryK_quantize(v, K=8, P=4, prng_bits=40, rounding_mode=RoundMode.SR)
values, up = sorted(sr.unique().tolist()), (sr > 1).double().mean().item()
print(f"\nSR with 40 random bits: values {values}, P(up) = {up:.4f}")
v32 = torch.full((1_000_000,), 1 + 0.3 * 0.125)
try:
    binaryK_quantize(v32, K=8, P=4, prng_bits=40, rounding_mode=RoundMode.SR)
except ValueError as e:
    print("float32:", str(e).split(";")[0])
sr32 = binaryK_quantize(v32, K=8, P=4, prng_bits=40, rounding_mode=RoundMode.SR, carrier=F64)
print(
    f"float32, carrier=torch.float64: P(up) = {(sr32 > 1).double().mean().item():.4f}, {sr32.dtype}"
)

# The carrier is never narrower than the tensor.
try:
    binaryK_quantize(x, K=8, P=4, carrier=F32)
except ValueError as e:
    print("\ncarrier=torch.float32 on float64:", str(e).split(";")[0])
output#
    3.141592653589793 -> 3.1415926553308964    the nearest multiple of 2^-28: True
   -2.718281828459045 -> -2.718281827867031    the nearest multiple of 2^-28: True
   0.3333333333333333 -> 0.33333333348855376   the nearest multiple of 2^-31: True
                1e-09 -> 9.999999994736442e-10 the nearest multiple of 2^-59: True
float32: BinaryK(K=40, P=30, bias=512) asks for 30 bits of precision, and it is rounded in binary32, which has 24

float64                         [1.125, 1.125]
float32                         [1.0, 1.25]
float32, carrier=torch.float64  [1.0, 1.25] torch.float32
torch.float32  carrier=torch.float64 -> torch.float32, same as binary32's: True
torch.float16  carrier=torch.float64 -> torch.float16, same as binary32's: True
torch.bfloat16 carrier=torch.float64 -> torch.bfloat16, same as binary32's: True
Quant(..., carrier=torch.float64) agrees: True

SR with 40 random bits: values [1.0, 1.125], P(up) = 0.2996
float32: BinaryK(K=8, P=4, bias=8) asks for 40 stochastic-rounding bits below a 3-bit mantissa
float32, carrier=torch.float64: P(up) = 0.2995, torch.float32

carrier=torch.float32 on float64: carrier=torch.float32 is narrower than float64 operands, whose inputs it would round once before the format does

Quant: a format and a rounding mode, as a function#

Quant binds a format object and a rounding mode into a callable. The *_quant slots of a layer’s formats are meant to hold one. It is the function call above with the arguments filled in from the format, and the run checks that the two are equal to the bit.

docs/snippets/quantizers_quant.py#
"""Quant: a format plus a rounding mode, as a callable."""

import torch

from mptorch import BinaryK, RoundMode, SuperFP
from mptorch.quant import Quant, binaryK_quantize

torch.manual_seed(0)
x = torch.randn(4, 4)

q = Quant(BinaryK(8, 4))  # rounding defaults to RoundMode.RNE
print(q)
print(q(x))

# A Quant is exactly the flat function call, spelled once.
same = torch.equal(q(x), binaryK_quantize(x, K=8, P=4, bias=8))
print("Quant(BinaryK(8, 4))(x) == binaryK_quantize(x, K=8, P=4):", same)

# Any format the kernels implement works, with any rounding mode.
q_sr = Quant(SuperFP(3, 4, 2, 7, prng_bits=8), RoundMode.SR)
print(q_sr(x))

# Formats and Quants are frozen values: equal by value, and usable as keys.
assert BinaryK(8, 4) == BinaryK(8, 4, bias=8)
cache = {BinaryK(8, 4): "Binary8p4", BinaryK(8, 3): "Binary8p3"}
print(cache[BinaryK(8, 4)], cache[BinaryK(8, 3)])
output#
Quant(fmt=BinaryK(K=8, P=4, bias=8, is_signed=True, prng_bits=0, saturation=<SaturationMode.SAT_NONE: 2>, domain=<Domain.EXTENDED: 0>, subnormals=<SubnormalsMode.SUBNORMALS: 0>), rounding=<RoundMode.RNE: 0>, carrier=None, inplace=False)
tensor([[-1.1250, -1.1250, -0.2500, -0.4375],
        [ 0.8750,  0.6875, -0.3125, -2.0000],
        [ 0.3125, -1.2500,  0.3438,  0.3125],
        [ 0.1172,  1.2500,  1.1250, -0.2500]])
Quant(BinaryK(8, 4))(x) == binaryK_quantize(x, K=8, P=4): True
tensor([[-1.0000, -1.0000, -0.2500, -0.5000],
        [ 1.0000,  0.5000, -0.2500, -2.0000],
        [ 0.2500, -1.0000,  0.5000,  0.2500],
        [ 0.1250,  2.0000,  1.0000, -0.2500]])
Binary8p4 Binary8p3

Formats and Quants are frozen dataclasses, so they compare and hash by value. This lets a layer resolve its format once and lets the library memoize on it. Build them once and keep them, instead of constructing one per call.

In place#

binaryK_quantize_(), superfp_quantize_() and fixedpoint_quantize_() take the arguments of the functions above, write the result over the tensor, and return it. They run the same kernels with the output pointer set to the input’s. The result is therefore the out-of-place one bit for bit, including under RoundMode.SR with the same seed; the only difference is that no result is allocated. They are meant for a tensor the caller owns, such as a weight rounded once when a model is loaded, or an activation that nothing else will read. Quant(fmt, rounding, inplace=True) is the same thing as a value.

The out-of-place functions handle some inputs by making a copy. The in-place ones refuse those inputs, because the kernel would round the copy and leave the caller’s tensor unchanged:

  • a tensor that is not contiguous;

  • on CUDA, a contiguous view that does not start on a 16-byte boundary (x[1:]), because the kernel moves 16 bytes at a time and cannot address such a view;

  • carrier=torch.float64 on a float32, float16 or bfloat16 tensor, which rounds a float64 copy and narrows the result. A float64 tensor does round in place in binary64, since that is its own carrier.

Each error names the out-of-place function, which accepts all three.

The in-place ops are not differentiable, like their twins, and raise the same way on a tensor that requires grad. On a tensor that does not, the write bumps the tensor’s version counter, like any in-place op of PyTorch’s own, so autograd notices if a tensor it had saved is rounded. A layer’s *_quant slots should never hold an in-place Quant, because a layer’s input belongs to the graph of whatever produced it, and autograd may have saved it. On an "mps" tensor the in-place ops run the out-of-place kernel with the tensor as both its input and its output.

docs/snippets/quantizers_inplace.py#
"""The in-place quantizers: the same rounding, written over a tensor the caller owns."""

import torch

from mptorch import BinaryK, RoundMode
from mptorch.quant import (
    Quant,
    binaryK_quantize,
    binaryK_quantize_,
    superfp_quantize,
    superfp_quantize_,
)

# A weight quantized once at load: nothing else reads the unrounded values, so
# the result can take their place. The tensor handed in is the tensor returned.
w = torch.randn(256, 256)
expected = binaryK_quantize(w, K=8, P=4)
out = binaryK_quantize_(w, K=8, P=4)
print(
    "returns its argument:", out is w, "| equals the out-of-place result:", torch.equal(w, expected)
)

# Stochastic rounding too: an element's random word is keyed on its index, so
# under one seed the two spellings draw the same words.
x = torch.randn(10_000)
m3e4 = dict(man_bits=3, exp_bits=4, normal_binades=8, bias=7, prng_bits=8)
torch.manual_seed(0)
expected = superfp_quantize(x, **m3e4, rounding_mode=RoundMode.SR)
torch.manual_seed(0)
superfp_quantize_(x, **m3e4, rounding_mode=RoundMode.SR)
print("superfp, SR, same seed:", torch.equal(x, expected))

# A float64 tensor rounds in binary64 in place, like any dtype in its own
# carrier: 1.0625 + 2**-30 is above Binary8p4's tie and goes up, where its float32
# neighbour is the tie itself.
d = torch.tensor([1.0625 + 2**-30], dtype=torch.float64)
print("float64:", binaryK_quantize_(d.clone(), K=8, P=4).tolist(), end="  ")
print("float32:", binaryK_quantize_(d.float(), K=8, P=4).tolist())

# What the out-of-place functions handle by copying, these refuse: the kernel
# would round the copy and leave the caller's tensor as it was.
m = torch.randn(4, 4)
try:
    binaryK_quantize_(m.t(), K=8, P=4)
except RuntimeError as e:
    print("\na transposed view:", str(e).split(":")[0])
try:
    binaryK_quantize_(m.half(), K=8, P=4, carrier=torch.float64)
except ValueError as e:
    print("a wider carrier:", str(e).split(":")[0])
if torch.cuda.is_available():
    g = torch.randn(64, device="cuda")
    try:
        binaryK_quantize_(g[1:], K=8, P=4)
    except RuntimeError as e:
        print("a CUDA view off a 16-byte boundary:", str(e).split(";")[0].split(", so ")[1])
    binaryK_quantize_(g[16:], K=8, P=4)  # 64 bytes in: on the boundary
    print("g[16:] is rounded, g[:16] is not:", g[:16].mul(16).frac().ne(0).any().item())

# The write is one autograd knows about. a * s saves s for a's gradient, and
# rounding s before backward() is caught rather than differentiated against.
a = torch.randn(8, requires_grad=True)
s = torch.randn(8)
loss = (a * s).sum()
binaryK_quantize_(s, K=8, P=4)
try:
    loss.backward()
except RuntimeError as e:
    print("\nbackward after the write:", str(e).split(":")[0])

# Quant takes it as a keyword, and it is part of the value.
q = Quant(BinaryK(8, 4), inplace=True)
y = torch.randn(1000)
expected = Quant(BinaryK(8, 4))(y)
print("\nQuant(..., inplace=True):", q(y) is y, torch.equal(y, expected), q == Quant(BinaryK(8, 4)))

# What it saves is the result's allocation, not time: the kernel reads and
# writes the same bytes either way.
if torch.cuda.is_available():
    big = torch.randn(1 << 24, device="cuda")

    def peak(fn):
        torch.cuda.synchronize()
        torch.cuda.reset_peak_memory_stats()
        start = torch.cuda.memory_allocated()
        r = fn()
        torch.cuda.synchronize()
        del r
        return (torch.cuda.max_memory_allocated() - start) / 2**20

    out_of_place = peak(lambda: binaryK_quantize(big, 8, 4))
    in_place = peak(lambda: binaryK_quantize_(big, 8, 4))
    print(
        f"\npeak above a 64 MiB float32 input: {out_of_place:.0f} MiB, in place {in_place:.0f} MiB"
    )
output#
returns its argument: True | equals the out-of-place result: True
superfp, SR, same seed: True
float64: [1.125]  float32: [1.0]

a transposed view: binaryK_quant_ writes its argument in place and needs a contiguous tensor, got strides [1, 4] for sizes [4, 4]
a wider carrier: binaryK_quantize_ cannot round a torch.float16 tensor in carrier=torch.float64 in place
a CUDA view off a 16-byte boundary: the tensor must start on a 16-byte boundary
g[16:] is rounded, g[:16] is not: True

backward after the write: one of the variables needed for gradient computation has been modified by an inplace operation

Quant(..., inplace=True): True True False

peak above a 64 MiB float32 input: 64 MiB, in place 0 MiB

The saving is in memory, not time, because the kernel reads and writes the same bytes either way. On CUDA the two take the same time at every size measured. On the CPU they also do, as long as the allocator recycles the result’s block. A result large enough to be mapped fresh from the system on every call pays for its pages on first touch, which can cost more than the rounding (dev/benchmarks/timing/cpu_quantize_elementwise.py compares the two).

Block quantization and packed storage#

A block format (Block formats) is quantized one block at a time. The block’s scale is chosen from the block’s values by the format’s scale_rounding rule. Each element is then divided by the scale and rounded to the element format in the call’s rounding mode.

block_quantize() returns the decoded values in the input’s dtype, like an elementwise quantizer. Its axis argument names the packed axis. For a format with a per-tensor scale (NVFP4), tensor_scale gives a static scale in place of the default, which is the tensor’s largest magnitude over the largest value the format can decode.

block_pack() rounds a tensor along one axis and returns a BlockPacked. It holds data, the element codes, and scales, the scale codes, both uint8. Each row of data is the tensor with its packed axis moved last, stored as a little-endian bit stream per block: the \(w\)-bit code of element \(i\) occupies bits \([i\,w, (i+1)\,w)\). Two 4-bit codes therefore share a byte, the first in the low nibble (the order of torch.float4_e2m1fn_x2 and CUTLASS), and four 6-bit codes fill three bytes.

block_unpack() decodes a packed tensor. block_quantize() is the two fused: it returns the decoded values with no packed intermediate, and is the fake quantizer that a layer’s *_quant slot takes. BlockQuant is its value spelling. Quant with a block format is another, along the last axis.

docs/snippets/block_formats.py#
"""Block formats: packing a tensor, what the bytes hold, and reading it back."""

import torch

from mptorch import MXFP4_E2M1, MXFP8_E4M3, NVFP4
from mptorch.quant import block_pack, block_quantize, block_unpack

torch.manual_seed(0)
x = torch.randn(4, 64)

# The OCP MX presets and NVFP4: bytes per element, codes and scales included
for name, fmt in (("MXFP8_E4M3", MXFP8_E4M3), ("MXFP4_E2M1", MXFP4_E2M1), ("NVFP4", NVFP4)):
    p = block_pack(x, fmt)
    err = (p.unpack() - x).abs().max().item()
    print(
        f"{name:11s} data {tuple(p.data.shape)} scales {tuple(p.scales.shape)}"
        f"  {p.nbytes / x.numel():.3f} B/elem  max error {err:.4f}"
    )

# One MXFP4 block of 32: the scale is 2^(floor(log2(amax)) - emax), here
# amax = 6 and E2M1's emax = 2, so 2^0 (E8M0 code 127); the elements round
# to E2M1's grid {0, 0.5, 1, 1.5, 2, 3, 4, 6}, two codes to a byte, low
# nibble first.
v = torch.tensor([[0.3, -1.0, 2.5, 6.0] * 8])
p = block_pack(v, MXFP4_E2M1)
print("\nscale code", p.scales.item(), " first bytes", [hex(b) for b in p.data[0, :2].tolist()])
print("decoded    ", block_unpack(p)[0, :4].tolist())

# block_quantize is pack + unpack fused, with no packed intermediate
print(
    "fused equal:",
    torch.equal(block_quantize(x, MXFP8_E4M3), block_unpack(block_pack(x, MXFP8_E4M3))),
)
output#
MXFP8_E4M3  data (4, 64) scales (4, 2)  1.031 B/elem  max error 0.2007
MXFP4_E2M1  data (4, 32) scales (4, 2)  0.531 B/elem  max error 0.4507
NVFP4       data (4, 32) scales (4, 4)  0.562 B/elem  max error 0.3108

scale code 127  first bytes ['0xa1', '0x74']
decoded     [0.5, -1.0, 2.0, 6.0]
fused equal: True

A strided input is packed through its strides, so packing a weight along its first axis copies nothing. Under RoundMode.SR an element’s random bits are keyed on its index in the packed orientation. block_quantize and block_pack therefore draw the same bits from the same generator state, whatever the thread count.

The block kernels round in the carrier: binary64 for a float64 tensor, or for a narrower one with carrier=torch.float64 (it is widened, and a decoded result narrowed back once), binary32 otherwise. A BlockPacked remembers the carrier it was packed in, and block_unpack() decodes in that carrier or a wider one. A format only binary64 holds, such as one whose elements have nine exponent bits, is refused in binary32 with an error that says so. A result narrower than its carrier is held to what its dtype can store (Formats and rounding, “What a narrower tensor can store”). block_quantize_ writes over its input, under the rules of In place. Block matrix products covers multiplying packed block-format tensors.

docs/snippets/block_float64.py#
"""Block formats in binary64: float64 tensors, the widening carrier, and formats
only binary64 holds."""

import warnings

import torch

from mptorch import E8M0, NVFP4, BinaryK, BlockFormat, FormatRangeWarning
from mptorch.quant import block_matmul, block_pack, block_quantize

torch.manual_seed(0)
x = torch.randn(4, 64, dtype=torch.float64)

# A float64 tensor packs and decodes in binary64, and remembers it.
p = block_pack(x, NVFP4)
print("packed in", p.carrier, "-> unpacks to", p.unpack().dtype)
print("its tensor scale is a float64 quotient:", p.tensor_scale)

# carrier=torch.float64 on a float32 tensor is the float64 call on the widened
# tensor, narrowed back once. (NVFP4's decoded values are binary64 products a
# float32 result rounds a second time, which a FormatRangeWarning says.)
warnings.simplefilter("ignore", FormatRangeWarning)
x32 = x.float()
same = torch.equal(
    block_quantize(x32, NVFP4, carrier=torch.float64),
    block_quantize(x32.double(), NVFP4).float(),
)
print("float32, carrier=torch.float64 == the float64 call, narrowed:", same)

# An element with nine exponent bits (2^-255 .. 2^256) is a format of float64
# tensors: binary32 refuses it, and says which carrier holds it.
e9m2 = BlockFormat(BinaryK(12, 3), E8M0, 32)
try:
    block_quantize(x32, e9m2)
except ValueError as e:
    print("binary32 refuses it:", str(e).split("; ")[-1])
tiny = x * 2.0**-200
q = block_quantize(tiny, e9m2)
print("binary64: relative error", (torch.linalg.norm(q - tiny) / torch.linalg.norm(tiny)).item())

# The block GEMM of two binary64 packings is a binary64 product.
w = torch.randn(64, 8, dtype=torch.float64)
y = block_matmul(block_pack(x, NVFP4), block_pack(w, NVFP4, 0), acc=BinaryK(32, 27))
print("block_matmul:", y.dtype, tuple(y.shape))
output#
packed in torch.float64 -> unpacks to torch.float64
its tensor scale is a float64 quotient: 0.0011701251016083085
float32, carrier=torch.float64 == the float64 call, narrowed: True
binary32 refuses it: binary64 holds it: pack a float64 tensor, or pass carrier=torch.float64
binary64: relative error 0.05399427464908147
block_matmul: torch.float64 (4, 8)

Quantizer: a straight-through estimator#

Rounding is a step function. Its derivative is zero almost everywhere and undefined at the steps, so autograd cannot derive a gradient “through” a quantizer. That gradient is a modelling choice, and the standard choice is the straight-through estimator (STE): in the backward pass, pretend that the quantizer was the identity. Quantizer implements it, with one refinement: the gradient that passes through can itself be rounded, to a format of its own:

\[\text{forward:}\quad y = Q_{F_{\text{fwd}}}(x), \qquad \text{backward:}\quad \frac{\partial L}{\partial x} := Q_{F_{\text{bwd}}}\Big(\frac{\partial L}{\partial y}\Big).\]

Either format may be None (that direction is left alone), a format object (wrapped in a Quant with round-to-nearest), or any callable Tensor -> Tensor of your own. The two directions are separate on purpose: a quantization-aware forward pass usually wants a narrow format, and the gradient a wider one.

docs/snippets/quantizers_quantizer.py#
"""Quantizer: a straight-through estimator with its own backward format."""

import torch

from mptorch import BinaryK
from mptorch.quant import Quantizer, binaryK_quantize

torch.manual_seed(0)
torch.set_printoptions(precision=5)

x = torch.randn(5, requires_grad=True)
g = torch.randn(5) * 0.01  # an incoming gradient, small enough to show Binary8p3's grid

# Forward in Binary8p4, backward in Binary8p3.
act = Quantizer(BinaryK(8, 4), BinaryK(8, 3))
y = act(x)
y.backward(g)
print("x                  ", x.detach())
print("act(x)             ", y.detach())
print("grad_output        ", g)
print("x.grad (Binary8p3) ", x.grad)

# Backward left as None: the gradient passes through untouched.
x.grad = None
Quantizer(BinaryK(8, 4))(x).backward(g)
print("x.grad (pass)      ", x.grad, "\n  identical to grad_output:", torch.equal(x.grad, g))

# The raw quantize function is not differentiable, and says so rather than
# returning a tensor whose gradient would silently vanish.
try:
    binaryK_quantize(x, K=8, P=4)
except RuntimeError as e:
    print("\nRuntimeError:", str(e).split(" Detach")[0])

# ... unless no gradient is being tracked, which is how a layer's autograd
# Function calls it.
with torch.no_grad():
    print("\nunder no_grad:", binaryK_quantize(x, K=8, P=4))
output#
x                   tensor([ 1.54100, -0.29343, -2.17879,  0.56843, -1.08452])
act(x)              tensor([ 1.50000, -0.28125, -2.25000,  0.56250, -1.12500])
grad_output         tensor([-0.01399,  0.00403,  0.00838, -0.00719, -0.00403])
x.grad (Binary8p3)  tensor([-0.01367,  0.00391,  0.00781, -0.00684, -0.00391])
x.grad (pass)       tensor([-0.01399,  0.00403,  0.00838, -0.00719, -0.00403]) 
  identical to grad_output: True

RuntimeError: mptorch::binaryK_quant is not differentiable: rounding to a coarse format has a zero derivative almost everywhere, so a gradient through it is a modelling choice. Use mptorch.quant.Quantizer, which applies one format in the forward pass and one of your choosing in the backward.

under no_grad: tensor([ 1.50000, -0.28125, -2.25000,  0.56250, -1.12500])

A Quantizer is an nn.Module, so it can sit anywhere in a model: between two layers, or in a *_quant slot of a layer’s formats. It is registered with its parent, so any state it carries travels with the model’s state_dict.

The rule for gradients#

The run above also shows what the raw functions do with a tensor that requires a gradient: they raise. None of MPTorch’s operators is differentiable in autograd’s sense. A quantizer has a zero derivative, and a GEMM that simulates its own arithmetic has no derivative the framework could infer. Returning a tensor anyway would silently drop its gradient: .grad would be None after .backward(), and the model would not train. So each raw operator raises and names the entry point that does carry a gradient: Quantizer for the quantizers, and qmatmul / QMatmul for the matrix products.

The check is gradient mode and requires_grad, so the layers are unaffected. A torch.autograd.Function’s forward runs with gradient mode off, so QLinear and the other layers can call the raw operators on tensors that require grad. Under torch.no_grad(), or on a detached tensor, the raw functions simply run.