Getting started#
Requirements#
Python >= 3.12 and PyTorch >= 2.1
A C++ compiler (GCC >= 10 on Linux: the extension is compiled as C++20)
CUDA >= 12.0, only if the CUDA kernels are wanted
On macOS, nothing more. The Apple GPU (MPS) kernels are built with the rest and compiled for the GPU when first used, so Xcode is not needed.
MPTorch is a C++/CUDA extension, so installing it compiles the kernels against the PyTorch you have installed.
Installation#
From the root of the repository:
$ pip install -e . --no-build-isolation
or
$ uv pip install -e . --no-build-isolation
if you have uv on your machine.
Always pass --no-build-isolation. Without it, pip builds the extension in a throw-away environment against a freshly downloaded PyTorch, which may not be the one you run. The result then fails to import with an undefined symbol error. With the flag, the build uses your installed PyTorch.
The CUDA kernels are built when torch.cuda.is_available() is true and CUDA_HOME is set. The Apple GPU kernels are built on macOS when PyTorch was built with MPS (USE_MPS=0 leaves them out). To force a CPU-only build, or a debug build:
$ USE_CUDA=0 pip install -e . --no-build-isolation
$ DEBUG=1 pip install -e . --no-build-isolation
The first build compiles about 180 source files and takes several minutes. The compiled objects are kept under build/, so running the same command again after a change recompiles only the files the change reaches, and takes seconds when nothing changed. Delete build/ to start from scratch. If ccache is installed, PyTorch’s extension builder uses it without further setup, and a build from scratch then reuses whatever it has compiled before.
The test suite needs two extra packages, kept in a test extra:
$ pip install -e ".[test]" --no-build-isolation
$ pytest tests/
These commands also have uv equivalents:
$ USE_CUDA=0 uv pip install -e . --no-build-isolation
$ DEBUG=1 uv pip install -e . --no-build-isolation
and
$ uv pip install -e ".[test]" --no-build-isolation
$ pytest tests/
A first example#
Two objects carry most of the library: a format, which is a plain value, and a quantizer, which is that format turned into a function on tensors. Layers take one quantizer per signal, and anything left unset is plain PyTorch.
"""
Thirty seconds with MPTorch: round a tensor, then train
a layer in that format.
"""
import torch
from mptorch import BinaryK
from mptorch.quant import QAffineFormats, QLinear, Quant
torch.manual_seed(0)
# A format is a value; a Quant is that format as a function
# on tensors.
binary8p4 = BinaryK(8, 4) # 8 bits: sign, 4 exponent, 3 mantissa
x = torch.randn(4)
print("x ", x)
print("Binary8p4(x) ", Quant(binary8p4)(x))
# A layer takes one quantizer per signal. Anything left
# None stays binary32.
formats = QAffineFormats(input_quant=Quant(binary8p4), weight_quant=Quant(binary8p4))
layer = QLinear(16, 4, formats=formats)
out = layer(torch.randn(2, 16))
out.sum().backward()
print("output ", out.shape, " weight.grad", layer.weight.grad.shape)
x tensor([ 1.5410, -0.2934, -2.1788, 0.5684])
Binary8p4(x) tensor([ 1.5000, -0.2812, -2.2500, 0.5625])
output torch.Size([2, 4]) weight.grad torch.Size([4, 16])
BinaryK(8, 4) is Binary8p4se from IEEE P3109, the upcoming standard for machine-learning number formats: an 8-bit float with a sign bit, 4 exponent bits and 4 bits of precision (one of them implicit). The OCP format E4M3 has the same field widths, with an exponent bias one less. 1.541 becomes 1.5 because the representable values between 1 and 2 are 1/8 apart. Formats and rounding explains the formats and the rounding, and the guides build on it.
Vocabulary#
A few words are used throughout, with a fixed meaning:
- format
A description of which numbers can be represented:
BinaryK(the IEEE P3109 binary formats),SuperFPorFixedPoint, for example. Frozen, hashable, comparable by value.- rounding mode
How a number that is not representable is mapped to one that is:
RoundMode. A property of an operation, not of a format.- quantize / quantizer
To round every element of a tensor to a format; the function that does it. In MPTorch this is always “compute in the carrier, round the result”.
- carrier
The IEEE 754 format a simulation computes and rounds in. By default it is binary32 for float32, float16 and bfloat16 tensors, and binary64 for float64 ones. It bounds which formats can be simulated in full. A carrier is named
torch.float32ortorch.float64and is never narrower than the dtype of the tensor it computes. The result keeps the tensor’s dtype (see Formats and rounding).- signal
One of the tensors flowing through a layer: its input, weight, bias, the gradient arriving from above, and the gradients it produces.
- arithmetic
What happens inside a matrix product: which format each partial product and each running sum is rounded to. A plain quantizer cannot express this; MPTorch’s kernels exist for it.
- MAC
Multiply-accumulate: the arithmetic of one step of a dot product, as a value. It is a
SplitMac(the product and the sum are rounded separately) or aFusedMac(one fused multiply-add, rounded once). An accumulate algorithm says in what order the terms are summed (see Dot-product arithmetic).- block format
Narrow element codes that share one scale per block of consecutive elements, or per tile of rows of blocks.
BlockFormatcovers OCP’s MX formats and NVIDIA’s NVFP4 (see Block formats). A tensor in a block format is packed in the format’s own bytes.- pass
One of the matrix products of a training step: the forward product, and the two gradient products of the backward pass. Each runs in the arithmetic of its own hook, and each is a product of the one core routine (see Quantized numerical kernels).