mtl5-python
Python bindings for MTL5 — NumPy/SciPy/JAX/PyTorch interop with hardware accelerator dispatch.
Built with nanobind for minimal overhead and zero-copy array interop.
Documentation: https://stillwater-sc.github.io/mtl5-python/. It has a
getting-started guide, executed notebooks on the sparse direct solvers and the
test-matrix catalog, and an API reference.
Install
pip install mtl5
Prebuilt wheels are published for Linux, macOS, and Windows on CPython
3.10–3.12, so no compiler is required. Optional ecosystem integrations are
available as extras:
pip install "mtl5[scipy]" # SciPy sparse interop
pip install "mtl5[all]" # scipy, torch, jax, pandas, scikit-learn
From source
Building the extension yourself — for contributing, or to enable a
build option — needs Python 3.10+ and a C++20 compiler
(GCC 12+, Clang 15+, MSVC 2022):
pip install .
See Development for an editable install.
Upgrading to 5.10.3
5.10.3 changes behaviour. mtl5.vector() and mtl5.matrix() no longer
silently convert their input, so code that worked on 5.10.2 can raise
TypeError. You are affected if you pass a non-contiguous array (a[::2],
a column, a transpose) or a dtype outside float32, float64, int8,
int16, int32, int64, uint8, complex64, complex128.
mtl5.vector(np.ascontiguousarray(a)) # keeps float64
mtl5.vector(a.astype(np.float64)) # or convert deliberately
That is a fix rather than a restriction: the old path silently downcast a
float64 slice to float32 — losing precision — while reporting
is_view=True and aliasing nothing. Full explanation in the
v5.10.3 release notes.
Quick start
import numpy as np
import mtl5
# Vectors and norms
v = mtl5.vector(np.array([3.0, 4.0]))
print(mtl5.norm(np.array([3.0, 4.0]))) # 5.0
# Dot product
a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 5.0, 6.0])
print(mtl5.dot(a, b)) # 32.0
# Solve Ax = b
A = np.array([[2.0, 1.0], [1.0, 3.0]])
b = np.array([5.0, 7.0])
x = mtl5.solve(A, b)
print(x) # [1.6, 1.8]
Passing containers to NumPy and scikit-learn
The dense containers implement __array__, so anything that takes array-like
input through np.asarray accepts them, scikit-learn included:
from sklearn.linear_model import LinearRegression
X, y = np.random.rand(100, 3), np.random.rand(100)
model = LinearRegression().fit(mtl5.matrix(X), mtl5.vector(y))
np.shares_memory(np.asarray(mtl5.matrix(X)), X) # True: a view, not a copy
- Universal containers (posit16, fp16, ...) convert to float64 with a copy,
so
np.asarray(P, copy=False) raises. (That is NumPy 2; NumPy 1.x's
np.asarray has no copy=.) scikit-learn then computes on the rounded
values in float64.
- Sparse matrices have no
__array__, so they aren't densified behind your
back. Pass mtl5.sparse.to_scipy(S).
- A float32 container is upcast to float64 by an estimator that takes
either float type, such as Ridge, because
.dtype is the name "f32", not a
NumPy dtype. np.asarray(M) first is zero-copy and keeps float32.
applications/sklearn_pipeline.py compares the test error of f64, f32, posit16
and fp16 feature storage.
Mixed precision
A mixed-precision operation has three independent precisions. MTL5 supplies the
precision-generic kernels, Universal
supplies the number systems, and this package composes them:
|
chosen by |
| element (storage) |
the container you pass in — mtl5.convert(x, "posit16") |
| accumulator (compute) |
accumulator= |
| result (delivery) |
result= |
import numpy as np, mtl5
x = np.random.default_rng(0).standard_normal(4000)
v = mtl5.convert(x, "posit16") # store narrow
mtl5.mixed.dot(v, v) # accumulate in posit16 too
mtl5.mixed.dot(v, v, accumulator="f64") # ...or in double
mtl5.mixed.dot(v, v, accumulator="quire") # ...or exactly, in Universal's quire
Accumulating 4000 posit16 products, against the exact value of the same
posit16 data:
| accumulator |
relative error |
| none (posit16) |
1.8 × 10⁻¹ |
"f32" |
3.8 × 10⁻⁷ |
"f64" |
1.1 × 10⁻¹⁶ |
"fma" |
1.1 × 10⁻¹⁶ |
"quire" |
0 — bit-exact |
mtl5.mixed.accumulators(dtype) lists what a given element type supports. The
quire is available for f32, f64 and the posit, cfloat, lns and fixpnt
families. Exactness varies by family. It is exact for f32, f64, posit,
cfloat and fixpnt. On f32/f64 the result is the exact dot product rounded
once, to nearest with ties to even, so it is correctly rounded. It is also slow:
every product goes into a 584-bit (f32) or 4226-bit (f64) fixed-point
register, and in mp-blas's level-3 benchmark a quire<double> accumulate runs
about 3900× slower than a float64 one. On f32/f64, accumulator= is
available on dot, norm and frobenius_norm. The lns quire's quire_mul
forms each product through double and rounds it, so it is not exact and can do
worse than the "f64" accumulator (universal#1203; see Universal's
lns/fdp.hpp). Universal supplies the quire's accumulator functions itself;
there is no bridge header in this package.
accumulator= is available on dot, norm (ord=2), frobenius_norm,
matvec and matmul.
Integer operands: accumulator="i32"
The same idea with integers, which is where the hardware is. int8 and int16
operands accumulated in int32 map onto the widening multiply-accumulate —
vpmaddwd / vpdpbusd on x86, SMLAL / SDOT on NEON:
a = np.random.randint(0, 256, 4096, dtype=np.uint8) # activations
w = np.random.randint(-128, 128, 4096, dtype=np.int8) # weights
mtl5.mixed.dot(a, w, accumulator="i32")
u8 × i8 is VNNI's native pairing on x86; ARM implements the symmetric ones
first. Either order works — a dot product is symmetric, so MTL5 swaps the
operands onto whatever the machine has.
The sum wraps, and sooner than vector length suggests. Products are always
exact, but headroom goes as operand magnitude: about 2^(31-2b) terms at b
bits. Measured at full range, one int16 × int16 product uses 2³⁰ of the int32
range so two overflow it, while int8 × int8 holds 131071 terms. That
gap is why quantized inference is 8-bit. The wrap is two's complement, hence
bit-identical across lane counts, backends and thread counts.
accumulator="i32" is required for these dtypes — the default is element
precision, and an 8-bit accumulator overflows almost immediately. Build the
arrays with NumPy: convert() does not target integers, because re-quantizing
reals into 8 bits is a quantization scheme rather than a cast.
Matrix products come in two kernels, chosen by name:
A = np.random.randint(0, 256, (64, 512), dtype=np.uint8) # activations
W = np.random.randint(-128, 128, (512, 32), dtype=np.int8) # weights
mtl5.mixed.matmul(A, W, accumulator="i32") # widen on load -> DenseMatrix_i32
mtl5.mixed.matmul_quad(A, W) # quad multiply-accumulate (VNNI / SDOT)
An integer matmul returns a matrix of the accumulator's type, not the
element type: i8 @ i8 is a DenseMatrix_i32. Both kernels give the same
result bit for bit, equal to the naive triple loop at any size, because integer
addition mod 2³² is associative. Only their speed differs. Upstream measures the
quad kernel at 1.27×–3.64× over widen-on-load, against about 1.2× for the same
instruction on a dot, because a GEMM is compute-bound.
| pairing |
matmul(..., accumulator="i32") |
matmul_quad |
i8 × i8, u8 × i8 |
DenseMatrix_i32 |
DenseMatrix_i32 |
u8 × u8 |
DenseMatrix_i32 |
DenseMatrix_u32 |
i16 × i16 |
DenseMatrix_i32 |
— |
i8 × u8 |
DenseMatrix_i32 |
refused |
matmul_quad refuses i8 × u8 rather than reordering it. The hardware op takes
u8 × i8, and unlike a dot product a GEMM is not symmetric, so no swap of the
operands fixes it for you. The quad kernel is never picked automatically, because
nothing in a result shows which of the two kernels ran.
A released wheel is built at the x86-64 baseline, so it gets int8's bandwidth
win — one byte per element against float64's eight — but not the VNNI
instruction. mtl5.build_info() says which you have:
info = mtl5.build_info()
info["quad_dot"] # 'none', 'partial' or 'all'
info["quad_dot_native"] # {'u8xi8': ..., 'i8xi8': ..., 'u8xu8': ...}
"partial" is the usual answer on hardware that has the instruction at all.
x86 implements u8 × i8 first (AVX3_DL) and the symmetric pairings only at
AVX10.2. ARM is the other way round: i8 × i8 and u8 × u8 come with DotProd,
and u8 × i8 only with I8MM. Build with -C cmake.define.MTL5_NATIVE_ARCH=ON to
reach the instruction, on CPUs Highway will target. Alder Lake has AVX-VNNI but
no AVX-512, so it still reports "none".
Iterative refinement
Factor cheaply in a low precision, then recover accuracy with a residual formed
in float64:
x, info = mtl5.mixed.lu_iterative_refine(A, b, working="posit16", rel_tol=1e-14)
# info -> {'iters': 7, 'rel_residual': ..., 'converged': True}
mtl5.mixed.backward_error(A, x, b)
On a 100×100 system, forward error of the refined solution:
| working precision |
iterations |
forward error |
fp16 |
5 |
1.9 × 10⁻⁸ |
posit16 |
7 |
1.9 × 10⁻¹⁵ |
f32 |
2 |
3.8 × 10⁻¹⁶ |
f64 |
0 |
3.1 × 10⁻¹⁶ |
The result is always the best iterate found, so an over-long max_iter never
degrades the answer.
mtl5.mixed.iterative_refine(A, M, b) is the sparse counterpart, refining
through any factorization exposing solve() — the sparse direct factorizations
below, or the ILU(0)/IC(0) preconditioners.
Arrays from universal_dtypes
universal_dtypes makes the
same number systems real NumPy dtypes. Its arrays go into MTL5 and come back
out bit for bit, without passing through float64:
import numpy as np, universal_dtypes as ud, mtl5 # pip install mtl5[universal]
a = np.array([1.0, 2.0, 3.0], dtype=ud.posit16)
v = mtl5.vector(a) # DenseVector_posit16, the same 16-bit encodings
mtl5.norm(v)
v.to_universal() # ndarray[posit16] again; to_numpy() still gives float64
mtl5.matrix() and the _copy forms work the same way. Supported: posit8,
posit16, posit32, posit64, fixpnt8, fixpnt16, lns16, lns32, takum32,
fp16 and the dd/td/qd cascades. These are the formats whose encoding
matches this build. The test suite checks that every 8- and 16-bit pattern
decodes the same in both libraries. Two dtypes are refused with a TypeError
rather than misread:
fp8e5m2, because MTL5's fp8 is e2m5;
- the formats MTL5 doesn't bind.
The data is copied, not viewed. The two packages are built on different
Universal releases, and those releases share the encoding but not necessarily
the C++ object layout. The named factories (mtl5.vector_posit16(x)) are
unchanged: they round float64 values into a format, which is a different job.
Matrix Market I/O and sparsity pictures
A = mtl5.io.mm_read("circuit.mtx") # -> CSR
D = mtl5.io.mm_read_dense("small.mtx") # -> dense
mtl5.io.mm_write_sparse("out.mtx", A, "comment")
mtl5.io.spy(A, "pattern.png") # binary non-zero pattern
mtl5.io.spy_magnitude(A, "mag.png", log_scale=True)
mtl5.io.spy_density(A, "dens.png", max_pixels=512)
Two things differ from what a SciPy user expects.
The function picks the container, not the file. scipy.io.mmread returns an
ndarray for an array file and COO for a coordinate one. Here mm_read
always gives CSR and mm_read_dense always gives dense, and both accept
either file format — so reading a dense .mtx into CSR is a deliberate call
rather than an error.
The PNGs are uncompressed. MTL5 writes them with a from-scratch encoder
emitting DEFLATE stored blocks, which is what lets spy work with no image
library and no plotting stack in the process. File size is therefore about
width × height × channels — measured at the default max_pixels=1024, that
is ~1.0 MB for spy (grayscale) and ~3.1 MB for spy_magnitude /
spy_density (RGB). Pipe the output through any PNG optimizer if that matters.
.gz inputs are read transparently only when MTL5 is built with zlib
(-C cmake.define.MTL5_WITH_ZLIB=ON); mtl5.build_info()["zlib"] reports it,
and without it a .gz path raises rather than silently mis-parsing.
Test matrices
A named catalog of matrices with known pathologies — the inputs a
mixed-precision experiment actually wants, and tedious to hand-roll correctly:
g = mtl5.generators
g.hilbert(8) # cond ~1.5e10 — the canonical ill-conditioned matrix
g.clement(7) # eigenvalues exactly -6,-4,-2,0,2,4,6
g.randspd(4, [1, 10, 100, 1000]) # SPD with exactly that spectrum
g.randsym(4, [-5, -1, 2, 7]) # controlled *indefinite* matrix
g.randsvd(20, 20, kappa=1e6) # condition number exactly 1e6
g.laplacian_2d(64, 64) # sparse, the usual solver benchmark
Also frank, pascal, wilkinson, rosser, magic, lehmer, lotkin,
minij, ones, forsythe, kahan, moler, companion, vandermonde,
randorth, laplacian_1d, poisson2d, and the published catalog via
testsuite_names() / testsuite_kappa(name).
Every dense generator takes dtype=, which is what makes them useful here:
H = g.hilbert(8, dtype="posit16") # correctly rounded posit16 Hilbert
mtl5.cholesky(H) # ...then watch it fail
Generation happens in float64 and dtype= rounds. That is the right semantics
for a test matrix — the definitions are over the reals, so you want the
correctly rounded representation of the exact entry, not the result of
evaluating the formula in low-precision arithmetic.
Range vectors follow NumPy, and take dtype= too:
mtl5.linspace(0, 1, 5)
mtl5.arange(0, 10, 3)
mtl5.logspace(0, 3, 4)
mtl5.geomspace(1, 1000, 4) # 1, 10, 100, 1000 — a true geometric
# progression, not logspace's exponents
Dense factorizations
qr = mtl5.qr(A) # Householder QR; tall or square
x = qr.solve(b) # least squares
qr.Q, qr.R
lq = mtl5.lq(A) # the row-space counterpart
lq.L, lq.Q
ld = mtl5.ldlt(A) # symmetric, indefinite allowed
ld.solve(b)
ld.diagonal() # D — its signs are the inertia
All accept an MTL5 matrix or a float32/float64 NumPy array, alongside the
existing mtl5.lu and mtl5.cholesky.
Every dense factorization — lu, qr, lq, cholesky, ldlt and
bunch_kaufman — is available for float32, float64 and all fifteen Universal
dtypes, which is what makes a like-for-like comparison across number systems
possible. The integer element types are not supported.
Availability is not usability, though, and the two diverge sharply at narrow
widths. The orthogonalizing pair (qr, lq) fails first: below 16 bits every
Householder reflector rounds to zero, so Q comes back as the exact identity
and the factorization looks perfect while reconstructing nothing. The solving
three (cholesky, ldlt, bunch_kaufman) have no orthogonality to lose and
stay usable to 8 bits. tests/test_universal_factorizations.py records where
each format stops.
Cholesky vs LDLᵀ across number systems