Layers#
The layers combine the two kinds of rounding: a quantizer for each signal,
and an arithmetic for each matrix product. Each layer is a thin subclass of
its torch.nn counterpart, and its forward delegates to a custom
torch.autograd.Function. A model built from them trains with the
ordinary optimizer, scheduler and loss.
What a quantized layer computes#
Take a linear layer, \(y = xW^{\top} + b\). With \(G = \partial L / \partial y\) arriving from above, the three gradients are
A QLinear computes the same four quantities, with a
quantizer in front of each signal and a separate arithmetic for each
product:
Here \([\cdot]_{\text{fwd}}\), \([\cdot]_{\text{igrad}}\) and \([\cdot]_{\text{wgrad}}\) are the three matrix products, each in the arithmetic of its hook. Two points are worth noting:
The backward pass reuses the quantized weight and input from the forward pass. The layer saves \(Q_{\text{w}}(W)\) and \(Q_{\text{in}}(x)\), not \(W\) and \(x\).
The incoming gradient is quantized separately for the two paths it feeds, because the input gradient and the weight gradient often need different formats.
QAffineFormats#
QAffineFormats is the configuration object that a
layer takes. It has nine optional slots, and each defaults to “plain
PyTorch”.
slot |
role |
|---|---|
|
\(Q_{\text{in}}\), applied to the layer’s input |
|
\(Q_{\text{w}}\), applied to the weight |
|
\(Q_{\text{b}}\), applied to the bias |
|
\(Q_{\text{igrad}}\), applied to \(G\) on the input-gradient path |
|
\(Q_{\text{wgrad}}\), applied to \(G\) on the weight-gradient path |
|
\(Q_{\text{bgrad}}\), applied to \(G\) on the bias-gradient path |
|
the forward product; default |
|
the input-gradient product; default a |
|
the weight-gradient product; default a |
A quantizer slot takes any callable Tensor -> Tensor: a
Quant, a Quantizer, or a
function of your own (a scaled quantizer, an observer). QAffineFormats
is itself an nn.Module, so a quantizer that is a module is registered in
the model’s state_dict. Two more fields, recompute_input and
recompute_weight, choose what the layer keeps for its backward pass
(below, “What a layer keeps for backward”).
The run below builds a layer with a quantizer on every signal: Binary8p4 in the forward direction and Binary8p3 on the gradients. It then recomputes the four equations by hand on the same tensors. The results agree to the bit.
"""QLinear with operand quantizers: what each slot of QAffineFormats does."""
import torch
import torch.nn.functional as F
from torch import nn
from mptorch import BinaryK
from mptorch.quant import QAffineFormats, QLinear, Quant
torch.manual_seed(0)
q8p4, q8p3 = Quant(BinaryK(8, 4)), Quant(BinaryK(8, 3))
# Forward signals in Binary8p4, backward signals in Binary8p3; the matmuls themselves
# stay float32 (no *_math hook set).
formats = QAffineFormats(
weight_quant=q8p4,
input_quant=q8p4,
bias_quant=q8p4,
igrad_quant=q8p3,
wgrad_quant=q8p3,
bgrad_quant=q8p3,
)
layer = QLinear(16, 8, formats=formats)
x = torch.randn(4, 16, requires_grad=True)
out = layer(x)
g = torch.randn_like(out)
out.backward(g)
# The same thing written out from the equations, on the same tensors.
with torch.no_grad():
qx, qw, qb = q8p4(x), q8p4(layer.weight), q8p4(layer.bias)
y = F.linear(qx, qw, qb) # y = Q(x) Q(W)^T + Q(b)
grad_x = q8p3(g) @ qw # dL/dx = Q(dL/dy) Q(W)
grad_w = q8p3(g).T @ qx # dL/dW = Q(dL/dy)^T Q(x)
grad_b = q8p3(g).sum(0) # dL/db = sum over the batch of Q(dL/dy)
print("forward ", torch.equal(out, y))
print("input grad ", torch.equal(x.grad, grad_x))
print("weight grad ", torch.equal(layer.weight.grad, grad_w))
print("bias grad ", torch.equal(layer.bias.grad, grad_b))
# A QAffineFormats() with nothing set is a plain nn.Linear.
plain = QLinear(16, 8)
ref = nn.Linear(16, 8)
ref.load_state_dict(plain.state_dict())
print("\nno formats == nn.Linear:", torch.equal(plain(x), ref(x)))
forward True
input grad True
weight grad True
bias grad True
no formats == nn.Linear: True
Custom arithmetic in the matrix products#
With the *_math hooks unset, the three products are PyTorch’s own, in the
layer’s dtype, however narrowly the operands were rounded. To simulate the
arithmetic inside the products, a factory fills the three hooks with
products of the core routine (Quantized numerical kernels):
binaryK_gemm_formats(): aSplitMacin BinaryK formats. It takesmul_*andacc_*arguments, andaccumulate_quant=Falsefor an unrounded sum.binaryK_gemm_formats_fma(): aFusedMacin a BinaryK format. It takesfma_*arguments.superfp_gemm_formats()andsuperfp_gemm_formats_fma(): the same for SuperFP.binaryK_superfp_gemm_formats()andsuperfp_binaryK_gemm_formats(): aSplitMacwhose products are of one family and whose sums are of the other.
Each returns a QAffineFormats with only the math hooks set. Operand
quantizers are assigned afterwards, so the two choices stay independent. The
hooks follow the layer’s call contract:
fwd_math(q_input, q_weight, q_bias),
bwd_igrad_math(q_grad, q_weight) and bwd_wgrad_math(q_grad, q_input).
They handle the transposes, and they fold any leading batch dimensions of
the input into one GEMM. The format is resolved once, when the factory runs,
not on every forward pass. Each factory also takes carrier (float64
models and the carrier).
"""QLinear whose matmuls themselves run in custom arithmetic."""
import torch
from mptorch import BinaryK, RoundMode
from mptorch.quant import (
QLinear,
Quant,
binaryK_gemm_formats,
binaryK_gemm_formats_fma,
binaryK_matmul,
superfp_gemm_formats,
superfp_gemm_formats_fma,
)
torch.manual_seed(0)
# The factory sets the three math hooks -- forward, input-gradient and
# weight-gradient GEMMs -- to a binaryK core: Binary8p4 products, float32 sums.
formats = binaryK_gemm_formats(mul_K=8, mul_P=4, accumulate_quant=False)
print(
"hooks set:",
[h for h in ("fwd_math", "bwd_igrad_math", "bwd_wgrad_math") if getattr(formats, h)],
)
print("quantizers set:", [q for q in ("weight_quant", "input_quant") if getattr(formats, q)])
# Operand quantization is layered on separately -- the two are composable.
formats.input_quant = Quant(BinaryK(8, 4))
formats.weight_quant = Quant(BinaryK(8, 4))
layer = QLinear(256, 64, formats=formats)
x = torch.randn(32, 256, requires_grad=True)
out = layer(x)
out.sum().backward()
# The forward is exactly the raw op on the quantized operands ...
with torch.no_grad():
qx, qw = Quant(BinaryK(8, 4))(x), Quant(BinaryK(8, 4))(layer.weight)
ref = (
binaryK_matmul(qx, qw, trans_b=True, mul_K=8, mul_P=4, accumulate_quant=False) + layer.bias
)
print("\nforward == binaryK_matmul(Q(x), Q(W)^T) + b:", torch.equal(out, ref))
# ... and the gradient GEMMs run in the same arithmetic.
with torch.no_grad():
g = torch.ones_like(out)
ref_gx = binaryK_matmul(g, qw, mul_K=8, mul_P=4, accumulate_quant=False)
print("input grad == binaryK_matmul(dL/dy, Q(W)):", torch.equal(x.grad, ref_gx))
# Leading batch dims are folded into M for the GEMM and restored afterwards.
out3 = layer(torch.randn(2, 5, 256))
print("\n[2, 5, 256] ->", tuple(out3.shape))
# The four factories: split / fused, binaryK / superfp.
factories = {
"binaryK_gemm_formats_fma": binaryK_gemm_formats_fma(
fma_K=8, fma_P=4, rounding_mode=RoundMode.SR, fma_prng_bits=8
),
"superfp_gemm_formats": superfp_gemm_formats(
mul_man_bits=3, mul_exp_bits=4, mul_normal_binades=2, mul_bias=7
),
"superfp_gemm_formats_fma": superfp_gemm_formats_fma(
fma_man_bits=3, fma_exp_bits=4, fma_normal_binades=2, fma_bias=7
),
}
for name, f in factories.items():
other = QLinear(256, 64, formats=f)
other.load_state_dict(layer.state_dict()) # same weights, different arithmetic
out = other(x)
print(
f"{name:<26} -> {tuple(out.shape)}, cos to float32 layer: "
f"{torch.nn.functional.cosine_similarity(out.flatten(), layer(x).flatten(), dim=0):.4f}"
)
hooks set: ['fwd_math', 'bwd_igrad_math', 'bwd_wgrad_math']
quantizers set: []
forward == binaryK_matmul(Q(x), Q(W)^T) + b: True
input grad == binaryK_matmul(dL/dy, Q(W)): True
[2, 5, 256] -> (2, 5, 64)
binaryK_gemm_formats_fma -> (32, 64), cos to float32 layer: 0.9272
superfp_gemm_formats -> (32, 64), cos to float32 layer: 0.5299
superfp_gemm_formats_fma -> (32, 64), cos to float32 layer: 0.5124
The last three lines show the same weights under three other arithmetics, measured against the split BinaryK layer: a fused Binary8p4 step with stochastic rounding, and the two SuperFP cores. The SuperFP format here has two binades of mantissa, which fits these activations poorly, and the error shows it.
Convolutions#
QConv1d, QConv2d and
QConv3d take the same QAffineFormats and apply
its quantizers to the same signals. The equations are the convolution
versions of the linear ones: \(G^{\top} x\) becomes the weight-gradient
convolution, and \(GW\) the input-gradient (transposed) convolution.
Their math hooks receive the convolution’s geometry as keyword arguments
(stride, padding, dilation, groups, nd). With the hooks
unset, the convolution is PyTorch’s own on the quantized operands.
"""QConv2d: the same slots, over a convolution."""
import torch
from torch import nn
from mptorch import BinaryK
from mptorch.quant import QAffineFormats, QConv2d, Quant, Quantizer
torch.manual_seed(0)
binary8p4, binary8p3 = BinaryK(8, 4), BinaryK(8, 3)
formats = QAffineFormats(
weight_quant=Quant(binary8p4),
input_quant=Quant(binary8p4),
igrad_quant=Quant(binary8p3),
wgrad_quant=Quant(binary8p3),
)
conv = QConv2d(3, 8, kernel_size=3, padding=1, formats=formats)
ref = nn.Conv2d(3, 8, kernel_size=3, padding=1)
ref.load_state_dict(conv.state_dict())
x = torch.randn(2, 3, 16, 16, requires_grad=True)
out = conv(x)
out.sum().backward()
print("output", tuple(out.shape), "weight grad", tuple(conv.weight.grad.shape))
# With the math hooks unset the convolution is torch's own, so with the
# operands rounded by hand it is reproduced exactly.
with torch.no_grad():
y = torch.nn.functional.conv2d(
Quant(binary8p4)(x), Quant(binary8p4)(conv.weight), conv.bias, padding=1
)
print("forward == conv2d(Q(x), Q(W)) + b:", torch.equal(out, y))
# How far a quantized layer is from the float32 one, on the same weights.
cos = torch.nn.functional.cosine_similarity
print("cos(out, float32 conv):", f"{cos(out.flatten(), ref(x).flatten(), dim=0):.5f}")
# Activations between layers are quantized with a Quantizer module, which
# also fixes what their gradient is rounded to.
net = nn.Sequential(
conv, nn.ReLU(), Quantizer(binary8p4, binary8p3), QConv2d(8, 4, 3, formats=formats)
)
print("\n", net)
output (2, 8, 16, 16) weight grad (8, 3, 3, 3)
forward == conv2d(Q(x), Q(W)) + b: True
cos(out, float32 conv): 0.99921
Sequential(
(0): QConv2d(
3, 8, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)
(formats): QAffineFormats()
)
(1): ReLU()
(2): Quantizer()
(3): QConv2d(
8, 4, kernel_size=(3, 3), stride=(1, 1)
(formats): QAffineFormats()
)
)
Custom arithmetic in the convolutions#
conv_formats() fills the three hooks with the
convolution’s passes: the forward pass, the input gradient and the weight
gradient. Each runs as products of the core routine in the arithmetic of a
mac, as matmul_formats() does for a matmul.
Each pass is bit for bit the product of that mac over the operands that
F.unfold would build, zeros included. But nothing is unfolded. The kernel
reads each operand element from the convolution’s tensors when it loads its
tile, so a pass allocates only its result. By comparison, the unfolded input
of a 3x3 convolution is nine times the size of the input.
Every format, rounding mode and accumulate algorithm of
Dot-product arithmetic applies, with any stride, padding ("same"
included), dilation and groups. A palette mac takes one prec_idx map
per pass, each shaped like that pass’s result with the spatial dimensions
flattened ([Cout, 1] is one format per output channel). As with the
matmul factories, the operand quantizers are assigned afterwards.
Convolutions describes what the three passes compute: which dot product each one is, in which order its terms are summed, how the input gradient of a strided convolution skips the zeros that a transposed convolution would insert, and what each pass costs.
"""QConv2d whose three convolutions run in custom arithmetic."""
import torch
import torch.nn.functional as F
from mptorch import AccumulateAlgorithm, BinaryK, RoundMode
from mptorch.quant import FusedMac, QConv2d, Quant, SplitMac, conv_formats, qmatmul
torch.manual_seed(0)
binary8p4 = BinaryK(8, 4)
# Binary8p4 products summed in a 12-bit accumulator, for the forward convolution
# and both gradients; operand quantizers are layered on as for QLinear.
mac = SplitMac(binary8p4, BinaryK(12, 7))
formats = conv_formats(mac)
formats.input_quant = Quant(binary8p4)
formats.weight_quant = Quant(binary8p4)
conv = QConv2d(3, 8, kernel_size=3, stride=2, padding=1, formats=formats)
x = torch.randn(4, 3, 16, 16, requires_grad=True)
out = conv(x)
out.sum().backward()
print("output", tuple(out.shape), "input grad", tuple(x.grad.shape))
# The forward is the GEMM of the same mac over the unfolded input, bit for
# bit, although no unfolded input (9x the input here) was ever built.
with torch.no_grad():
qx, qw = Quant(binary8p4)(x), Quant(binary8p4)(conv.weight)
cols = F.unfold(qx, 3, padding=1, stride=2) # [4, 27, 64]
ref = qmatmul(qw.reshape(8, -1), cols, mac).reshape(out.shape) + conv.bias.view(1, 8, 1, 1)
print("forward == qmatmul(Q(W), unfold(Q(x))) + b:", torch.equal(out, ref))
# Any accumulate algorithm and rounding mode, any geometry: here a fused
# multiply-add with Kahan summation, rounded stochastically, over a grouped,
# dilated convolution.
fused = FusedMac(BinaryK(12, 7, prng_bits=8), rounding=RoundMode.SR,
accumulate_algorithm=AccumulateAlgorithm.KAHAN) # fmt: skip
grouped = QConv2d(4, 8, 3, padding=2, dilation=2, groups=2, formats=conv_formats(fused))
y = grouped(torch.randn(2, 4, 10, 10))
print("grouped, dilated, KAHAN under SR:", tuple(y.shape))
# A palette picks a format per output element; a [Cout, 1] map is one per
# output channel. Each pass has its own map, shaped like its own result.
pal = SplitMac([binary8p4, BinaryK(8, 5)], BinaryK(12, 7))
per_channel = conv_formats(
pal,
prec_idx=torch.tensor([[0], [1]] * 4), # the forward's 8 output channels
igrad_prec_idx=torch.zeros(3, 1, dtype=torch.int64), # the 3 input channels
wgrad_prec_idx=torch.zeros(8, 27, dtype=torch.int64), # the weight, [8, 3*3*3]
)
mixed = QConv2d(3, 8, 3, padding=1, formats=per_channel)
print("per-channel palette:", tuple(mixed(torch.randn(1, 3, 6, 6)).shape))
output (4, 8, 8, 8) input grad (4, 3, 16, 16)
forward == qmatmul(Q(W), unfold(Q(x))) + b: True
grouped, dilated, KAHAN under SR: (2, 8, 10, 10)
per-channel palette: (1, 8, 6, 6)
Block formats#
block_gemm_formats() builds a QAffineFormats whose
three matrix products are block products, for
QLinear. Each hook packs what it multiplies along the
dimension it sums over, because a block’s scales can be factored out of the
sum only when the blocks run along that dimension (Block matrix products,
“Why the blocks run along K”). It uses the format of the tensor’s role: the
input’s, the weight’s, or the output gradient’s (which defaults to the
input’s). There are two recipes for the weight:
1D weight blocks. Leave
weight_quantunset. The forward pass packs the weight along its input features, and the input gradient packs it along its output features. Both start from the float weight, as MX training recipes do.Square weight tiles (
dataclasses.replace(NVFP4, block_rows=16)). Setweight_quant = BlockQuant(w16, axis=1).pack. The weight is packed once, and the input gradient reads that packing transposed, so the forward and backward passes see the same quantized weight. The packing is memoized on the weight, its version counter, its device and its dtype, so it is redone once per optimizer step (which writes the weight in place) and after the layer is moved or converted (.to(),.half()). A weight packed in a 1D or non-square format cannot serve the input gradient. It raises there, with a message that names the square-tile spelling. For inference there is no backward pass, and a 1D packed weight is fine. The tile may carry any scale rule, a Four Over Six one included (dataclasses.replace(w16, scale_rounding=ScaleRounding.FOUR_OVER_SIX_MSE)): each tile then makes its choice between two scales once, for both passes.
"""QLinear on the block GEMM, with a 1D weight format and with 16 x 16 tiles."""
import dataclasses
import torch
from mptorch import NVFP4, BinaryK
from mptorch.quant import BlockQuant, QLinear, block_gemm_formats
torch.manual_seed(0)
acc = BinaryK(16, 11)
x = torch.randn(32, 128, requires_grad=True)
# 1D weight blocks: every hook packs what it multiplies along the dimension
# it reduces over, the weight along its input features in the forward and
# along its output features in the input gradient.
layer = QLinear(128, 64, formats=block_gemm_formats(NVFP4, NVFP4, acc=acc))
layer(x).sum().backward()
print("1D weight: forward and both gradients ran")
# 16 x 16 weight tiles: packed once per step by weight_quant, and the input
# gradient reads that packing transposed, so the forward and backward passes
# see the same quantized weight.
w16 = dataclasses.replace(NVFP4, block_rows=16)
formats = block_gemm_formats(NVFP4, w16, acc=acc)
formats.weight_quant = BlockQuant(w16, axis=1).pack
tiled = QLinear(128, 64, formats=formats)
tiled.load_state_dict(layer.state_dict())
x2 = x.detach().clone().requires_grad_()
tiled(x2).sum().backward()
# The same input gradient as re-packing the float weight along the other
# axis: a square tile quantizes it the same either way.
repack = QLinear(128, 64, formats=block_gemm_formats(NVFP4, w16, acc=acc))
repack.load_state_dict(layer.state_dict())
x3 = x.detach().clone().requires_grad_()
repack(x3).sum().backward()
print(
"16 x 16: input gradient from the forward's packing == re-packed:",
torch.equal(x2.grad, x3.grad),
)
1D weight: forward and both gradients ran
16 x 16: input gradient from the forward's packing == re-packed: True
Packing the weight once does not save memory by itself. The layer’s
parameter stays the float weight, and the packing is a second copy beside
it, held by the BlockQuant: 0.504 bytes per element for NVFP4’s 16 x 16
tiles and 1.03 for MXFP8, next to float32’s 4. In training, the float weight
that a 1D layer saves for its backward pass is the parameter itself, and the
16 x 16 packing is an extra allocation, kept alive from the forward pass to
the input gradient. A BlockQuant remembers one weight, so give each layer
its own. What packing once buys is time and consistency: the weight is
quantized once, and every product reads the same codes. Each GEMM’s result is
float32, stored in the input’s dtype. To drop the float weight, freeze the
layer (next section).
Freezing a layer to its codes#
For inference, or to train other layers around a fixed one,
freeze_packed_() replaces a layer’s float weight
by its block codes, in place, and freeze_packed_() does
so for every block-format QLinear of a model, one layer at a time. The
layer becomes a QPackedLinear. It is still a
QLinear, its weight is None, and its codes and scales are two
uint8 buffers, weight_codes and weight_scales, which follow
.to() and stay uint8 under .half(). On a 4096 x 4096 weight that is
8.06 MiB for NVFP4’s 16 x 16 tiles, 9.00 for its 1 x 16 blocks and 16.5 for
MXFP8, where the layer held 64 MiB of float32 and the codes besides. The
codes are what the layer’s forward multiplies (its weight_quant packing,
or the weight packed in the format the layer’s formats name), so the frozen
layer returns what it returned before, word for word.
"""Freezing block-format QLinear layers to their codes, and loading them back."""
import dataclasses
import io
import torch
from torch import nn
from mptorch import NVFP4, BinaryK
from mptorch.quant import QLinear, block_gemm_formats, freeze_packed_
w16 = dataclasses.replace(NVFP4, block_rows=16)
def build(device=None):
def layer(n_in, n_out):
formats = block_gemm_formats(NVFP4, w16, acc=BinaryK(16, 11))
return QLinear(n_in, n_out, device=device, formats=formats)
return nn.Sequential(layer(1024, 1024), nn.ReLU(), layer(1024, 256))
def mib(model):
tensors = [*model.parameters(), *model.buffers()]
return sum(t.nbytes for t in tensors) / 2**20
torch.manual_seed(0)
model = build()
x = torch.randn(8, 1024)
with torch.no_grad():
before = model(x)
print(f"float weights: {mib(model):.3f} MiB")
print("layers frozen:", freeze_packed_(model))
print(f"frozen: {mib(model):.3f} MiB")
with torch.no_grad():
print("same output:", torch.equal(model(x), before))
print("weight:", model[0].weight, "| buffers:", [name for name, _ in model[0].named_buffers()])
# Loading: build the model as it was built, here on the meta device so that no
# float weight is ever allocated, freeze it without packing, and load the codes.
file = io.BytesIO()
torch.save(model.state_dict(), file)
file.seek(0)
loaded = build(device="meta")
freeze_packed_(loaded, pack=False)
loaded.load_state_dict(torch.load(file, weights_only=True), assign=True)
with torch.no_grad():
print("loaded output:", torch.equal(loaded(x), before))
float weights: 5.005 MiB
layers frozen: 2
frozen: 0.635 MiB
same output: True
weight: None | buffers: ['weight_codes', 'weight_scales']
loaded output: True
Gradients. A square-tiled weight still serves the input gradient, so layers below a frozen one can train. A 1D weight raises there, because its packing reads differently along the other axis and there is no float weight left to pack again. A frozen layer has no weight gradient, and its bias stays a float parameter.
Memory. The float weight is freed once nothing else refers to it, so freeze before building an optimizer or any copy of the parameters, which would keep it alive. A model that does not fit on its device as float can be frozen on the CPU and then moved. On CUDA the freed memory returns to torch’s caching allocator;
torch.cuda.empty_cache()hands it back to the driver.Stochastic rounding. A freeze draws once. With the packed-once recipe it keeps the packing the last forward used, draws included. A layer that packs in each hook draws again in every forward.
Checkpoints. The format is code, as every hook of the layer’s formats is. The
state_dictholds the codes, the bias and an_extra_statethat records the packing’s format, shape, tensor scale, dtype and carrier. To load, build the model as it was built, freeze it withpack=False(zeroed codes, nothing packed), and load. A model built on the meta device allocates nothing untilload_state_dict(..., assign=True), so its float weights never exist. A checkpoint frozen in another format or shape raises, naming both, and a float checkpoint does not load into a frozen model, nor the reverse.Code that reads
layer.weight(a model summary, an initializer) meetsNone, andreset_parametersraises.unfreeze_packed_()turns the layer back into aQLinearwhose weight is the decoded codes: the quantized weight, not the original.
tensor_scale_epilogue=True applies a format’s per-tensor scales to each
product’s result instead of in the decode, as NVIDIA’s NVFP4 GEMMs do
(Block matrix products, “Tensor scales”).
Activations between layers#
A layer’s input_quant rounds what enters the layer. The gradient of that
rounding is handled by the layer itself: it flows to the input through the
layer’s bwd_igrad_math. To round a tensor between layers (an
activation, the logits, the output of a block that is not a layer), use a
Quantizer. It is a module, and it also specifies
what its gradient is rounded to (see Quantizers). The last lines of
the convolution run above show one in a Sequential.
What a layer keeps for backward#
The backward pass needs \(Q_{\text{in}}(X)\) again for the weight
gradient and \(Q_{\text{w}}(W)\) for the input gradient. A layer can keep
each as a quantized copy, a tensor the size of the operand, or keep the raw
operand and quantize it again in the backward pass. The second way costs one
more quantization per operand per step and saves the copy. The flags
recompute_input and recompute_weight of
QAffineFormats choose (recompute_a and
recompute_b of QMatmulFormats for a
QMatmul). Each defaults to None, which means the
layer’s own default:
layer |
input ( |
weight ( |
|---|---|---|
|
quantized again |
quantized again |
|
copy kept |
quantized again |
|
copy kept |
copy kept |
The gradients are the same either way, to the bit. Under stochastic rounding the second quantization sees the random generators as the first did, and leaves them as it found them.
Quantizing again saves memory only where the raw operand stays alive anyway.
A weight always does, since it is the layer’s parameter. An input does when
the op that made it keeps its output for its own backward pass: ReLU,
sigmoid, tanh and softmax do, and so does the data batch, which the training
loop holds. GELU, SiLU, ReLU6, LayerNorm, BatchNorm and max pooling keep
their input instead, and an addition keeps nothing. After those, the raw
input would be alive only for this layer, so quantizing it again holds the
same memory and adds the work. That is why the defaults differ. A
convolution’s input is usually a ReLU output or the data. A Linear layer’s
input is usually the output of a LayerNorm or of a GELU or SiLU. A matmul’s
operands are activations of any origin. Set recompute_input=True for a
ReLU MLP, recompute_input=False for a convolution after a GELU, and
recompute_a=True for the product of attention’s softmax probabilities
with \(V\).
The cost is one elementwise pass per recomputed operand. Measured on an RTX 4060, it was within 0.6% of the step when the products run on mptorch’s kernels. With PyTorch’s own products it was a few percent, and 12% for the weights of 4096-wide Linear layers at 256 tokens, the case where recomputing also saved the most memory (from 148 to 20 MiB for three layers).
Three cases keep the copy whatever the default:
A quantizer of your own. Only a
Quant(not in place), aBlockQuantused as a fake quantizer, and aQuantizerover one are run twice by default. A callable with state, such as a QAT observer, would update that state a second time in the backward pass, and could round differently there. Setting the flag toTrueruns any callable again. That is your promise that it depends only on its input and the random generators.A result that is not a tensor. A packed weight (
BlockQuant.pack) is compact already, and its memo holds it anyway.A flag set to
False.
An operand that is kept raw is checked by autograd as nn.Conv2d checks
its own saved input. Writing to it in place between the forward and backward
passes raises “modified by an inplace operation”. With the flag set to
False the layer keeps its own copy and the write does no harm.
The run below counts what four convolution layers keep for the backward
pass, in activations, beyond what the parameters and the input already hold:
four for nn.Conv2d, eight with the copies kept, and four with the
defaults. Then it shows what a Linear layer keeps, by default and with a
quantizer of its own.
"""What a quantized layer keeps for backward: a quantized copy, or the raw operand."""
import torch
from torch import nn
from mptorch import BinaryK, RoundMode
from mptorch.quant import QAffineFormats, QConv2d, QLinear, Quant
q = Quant(BinaryK(8, 4, prng_bits=8), RoundMode.SR)
def held_for_backward(model, x):
"""The bytes the graph keeps for backward that nothing else keeps alive:
every tensor any node saves, once per storage, less the parameters and
the input, which the caller holds anyway."""
saved = {}
def pack(t):
saved[t.untyped_storage().data_ptr()] = t.untyped_storage().nbytes()
return t
with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
out = model(x)
alive = {p.untyped_storage().data_ptr() for p in model.parameters()}
alive.add(x.untyped_storage().data_ptr())
return sum(n for ptr, n in saved.items() if ptr not in alive), out
def stack(recompute):
"""Four conv -> ReLU layers: nn.Conv2d, or QConv2d with SR on every signal."""
torch.manual_seed(1)
layers = []
for _ in range(4):
if recompute == "nn":
layers += [nn.Conv2d(16, 16, 3, padding=1), nn.ReLU()]
continue
f = QAffineFormats(input_quant=q, weight_quant=q, igrad_quant=q, wgrad_quant=q)
if recompute is not None:
f.recompute_input = f.recompute_weight = recompute
layers += [QConv2d(16, 16, 3, padding=1, formats=f), nn.ReLU()]
return nn.Sequential(*layers)
x = torch.randn(8, 16, 32, 32)
activation = x.numel() * x.element_size()
grads = {}
for name, recompute in (("nn.Conv2d", "nn"), ("QConv2d, copies kept", False), ("QConv2d", None)):
model = stack(recompute)
torch.manual_seed(2)
held, out = held_for_backward(model, x)
out.sum().backward()
grads[name] = [p.grad for p in model.parameters()]
print(f"{name:21s} holds {held / activation:.2f} activations for backward")
same = all(map(torch.equal, grads["QConv2d"], grads["QConv2d, copies kept"]))
print("the two QConv2d stacks' gradients, under SR, are identical:", same)
# A Linear keeps its input as a quantized copy and its weight raw.
def shares(saved, raw):
return saved.untyped_storage().data_ptr() == raw.untyped_storage().data_ptr()
layer = QLinear(64, 64, formats=QAffineFormats(input_quant=q, weight_quant=q))
x = torch.randn(32, 64, requires_grad=True)
saved_input, saved_weight = layer(x).grad_fn.saved_tensors
print("\nQLinear keeps its input raw:", shares(saved_input, x))
print("QLinear keeps its weight raw:", shares(saved_weight, layer.weight))
# A quantizer mptorch does not know to be stateless keeps its result, unless
# the flag says it may run twice.
formats = QAffineFormats(weight_quant=lambda w: q(w))
layer = QLinear(64, 64, formats=formats)
print(
"\nwith a callable of its own, the weight raw:",
shares(layer(x).grad_fn.saved_tensors[1], layer.weight),
)
formats.recompute_weight = True
print("and with recompute_weight=True:", shares(layer(x).grad_fn.saved_tensors[1], layer.weight))
nn.Conv2d holds 4.00 activations for backward
QConv2d, copies kept holds 8.05 activations for backward
QConv2d holds 4.00 activations for backward
the two QConv2d stacks' gradients, under SR, are identical: True
QLinear keeps its input raw: False
QLinear keeps its weight raw: True
with a callable of its own, the weight raw: False
and with recompute_weight=True: True
float64 models and the carrier#
A layer computes in its tensors’ carrier (Formats and rounding). By default a
float32, float16 or bfloat16 layer rounds and multiplies in binary32, and a
float64 layer in binary64. This applies to every quantizer and every
product. The formats do not determine the carrier unless they name one; the
dtype does. model.double() therefore moves a whole model into binary64,
and model.float() moves it back. Each hook checks its formats against
the carrier it meets on every call.
A float64 model can use formats that a float32 one cannot: up to 53 bits of precision and ten exponent bits. That is needed to study arithmetic wider than binary32, or to have an exact reference.
A float32 model can get binary64’s arithmetic without changing dtype. Give
carrier=torch.float64 to the factory and to each
Quant. Each hook then widens its operands, computes
in binary64 and narrows its result back. The model’s signals stay float32
and are held to what float32 can store.
The other direction is not a carrier choice. A float64 model computes the float32 way by becoming a float32 model. On a GPU that is also the faster arithmetic for the matrix products (Calling the kernels, “Performance notes”).
The convolutions of conv_formats() and the block
products follow the same rule. A float64 model computes them in binary64:
its block operands are packed, decoded and multiplied there. A float32 model
does so too when its mac (or block_gemm_formats()) names
carrier=torch.float64.
The run compares one float64 reference with a float64 layer in a 30-bit
arithmetic that only binary64 can hold, and a float64 convolution in the same
arithmetic with nn.Conv2d’s float64 one. It then compares the reference
with a float32 layer in each carrier, in three arithmetics:
a 30-bit multiply format under a 24-bit accumulator, which only binary64 can give a float32 layer;
an FP8 recipe. Its operands are rounded to 8 bits before any product, so both carriers compute every intermediate exactly and agree to the bit;
a 22-bit arithmetic on unquantized operands. Binary32 keeps 24 bits of each product and sum before the formats’ rounding, and binary64 keeps 53.
"""A layer's carrier: binary64 for a float64 layer, and for a float32 one that names it."""
import torch
from torch import nn
from mptorch import BinaryK
from mptorch.quant import QConv2d, QLinear, Quant, SplitMac, binaryK_gemm_formats, conv_formats
torch.manual_seed(0)
F32, F64 = torch.float32, torch.float64
# A float64 reference whose weights and inputs are float32 values, so a float32
# layer holds them exactly and what separates it from the reference is its
# arithmetic alone.
reference = nn.Linear(256, 32, dtype=F64)
with torch.no_grad():
for p in reference.parameters():
p.copy_(p.float())
x = torch.randn(64, 256).double()
g = torch.randn(64, 32).double() # the gradient of the output
ref_out = reference(x)
ref_out.backward(g)
assert reference.weight.grad is not None
ref_grad = reference.weight.grad
def run(formats, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
"""A QLinear of ``dtype`` with the reference's weights: its output and weight gradient."""
layer = QLinear(256, 32, formats=formats, dtype=dtype)
layer.load_state_dict(reference.state_dict())
out = layer(x.to(dtype))
out.backward(g.to(dtype))
assert layer.weight.grad is not None
return out.detach().double(), layer.weight.grad.double()
def rel(a: torch.Tensor, b: torch.Tensor) -> str:
return f"{(torch.linalg.norm(a - b) / torch.linalg.norm(b)).item():.1e}"
# Arithmetic only binary64 carries: 30-bit products into a 40-bit accumulator,
# in the forward product and both gradient products, on a float64 layer.
wide = binaryK_gemm_formats(40, 30, acc_K=48, acc_P=40)
out, grad = run(wide, F64)
print(f"float64 layer, 30/40-bit: output {rel(out, ref_out)}, weight grad {rel(grad, ref_grad)}")
# The same arithmetic in a float64 convolution, against nn.Conv2d's float64 one.
conv = nn.Conv2d(8, 16, 3, padding=1, dtype=F64)
wide_conv = conv_formats(SplitMac(BinaryK(40, 30), BinaryK(48, 40)))
qconv = QConv2d(8, 16, 3, padding=1, dtype=F64, formats=wide_conv)
qconv.load_state_dict(conv.state_dict())
img = torch.randn(4, 8, 12, 12, dtype=F64)
print(f"float64 conv, 30/40-bit: output {rel(qconv(img).detach(), conv(img).detach())}")
# A float32 layer cannot have it in binary32, nor store a 40-bit result in
# binary64 -- each says so at the first call.
for carrier in (None, F64):
try:
run(binaryK_gemm_formats(40, 30, acc_K=48, acc_P=40, carrier=carrier), F32)
except ValueError as e:
print(f"float32 layer, carrier={carrier}:", str(e).split(": ")[0])
# What binary64 gives a float32 layer is everything before the stored result: a
# 30-bit multiply format under a 24-bit accumulator, which binary32 refuses.
out, grad = run(binaryK_gemm_formats(40, 30, acc_K=31, acc_P=24, carrier=F64), F32)
print(f"float32 layer, 30/24-bit, binary64: output {rel(out, ref_out)}, grad {rel(grad, ref_grad)}")
# And it changes the answer where the arithmetic sees bits it does not keep. An
# FP8 recipe -- Binary8p4 signals and arithmetic, gradients in E5M2's layout -- rounds every
# signal to 8 bits first, so each product and sum is exact in binary32 as in
# binary64 and the two carriers agree to the bit. A 22-bit arithmetic on
# unquantized operands does not: binary32 rounds each product and sum to 24
# bits before the formats round them to 22 and 23, where binary64 keeps 53.
def fp8(carrier: torch.dtype | None):
formats = binaryK_gemm_formats(8, 4, carrier=carrier)
formats.input_quant = formats.weight_quant = Quant(BinaryK(8, 4), carrier=carrier)
formats.igrad_quant = formats.wgrad_quant = Quant(BinaryK(8, 3, bias=15), carrier=carrier)
return formats
def bits22(carrier: torch.dtype | None):
return binaryK_gemm_formats(26, 22, acc_K=27, acc_P=23, carrier=carrier)
print()
for label, build in (("FP8 recipe", fp8), ("22/23-bit arithmetic", bits22)):
out32, grad32 = run(build(None), F32)
out64, grad64 = run(build(F64), F32)
print(
f"float32 layer, {label}: error {rel(out32, ref_out)} in binary32, "
f"{rel(out64, ref_out)} in binary64"
)
diff = f"output {rel(out64, out32)}, weight grad {rel(grad64, grad32)}"
print(f" binary64 against binary32: {diff}")
float64 layer, 30/40-bit: output 4.0e-10, weight grad 3.9e-10
float64 conv, 30/40-bit: output 3.9e-10
float32 layer, carrier=None: BinaryK(K=40, P=30, bias=512) asks for 30 bits of precision, and it is rounded in binary32, which has 24
float32 layer, carrier=torch.float64: BinaryK(K=48, P=40, bias=128) has 40 bits of precision, and a float32 result holds 24
float32 layer, 30/24-bit, binary64: output 2.9e-07, grad 1.5e-07
float32 layer, FP8 recipe: error 2.7e-01 in binary32, 2.7e-01 in binary64
binary64 against binary32: output 0.0e+00, weight grad 0.0e+00
float32 layer, 22/23-bit arithmetic: error 7.3e-07 in binary32, 6.0e-07 in binary64
binary64 against binary32: output 9.1e-07, weight grad 4.5e-07
Putting a model together#
A mixed-precision model is a set of decisions per layer:
Choose the carrier. By default it is the model’s dtype: float32 for the formats binary32 carries, and float64 for wider formats or an exact reference. Use
carrier=torch.float64where a float32 (or half-precision) model should compute in binary64 and keep its dtype.Choose the format of each signal: a
Quant(or aQuantizer, or a scaled quantizer of your own) forinput_quant,weight_quant,bias_quantand the three gradient paths.Choose the arithmetic of each matrix product and convolution: a
*_gemm_formatsfactory,conv_formats()orblock_gemm_formats()for the*_mathhooks (Quantized numerical kernels). Or leave them as PyTorch’s own.Share one
QAffineFormatsacross layers that should behave the same, or give each layer its own.Round anything else with a
Quantizer.
The Tutorial: training in 8-bit floating point goes through these steps for the 8-bit formats, training a network with each combination and comparing them.