Calling the kernels#
This page lists the entry points to the core routine (Quantized numerical kernels), from the value objects that describe an arithmetic to the functions that spell out every argument of a kernel. The equations are in Dot-product arithmetic, Block matrix products and Convolutions. This page explains how to request them.
Saying which arithmetic#
Four value types describe an arithmetic. All are frozen, so build them once and keep them; the library memoizes their resolution.
SplitMac(mul, acc=None, *, rounding=RNE, accumulate_algorithm=NAIVE, carrier=None, block_size=None, outer=None)mulandaccare each a format or a sequence of formats (a palette, Dot-product arithmetic).acccan also beNone. The two may be of different families (a BinaryK multiply with a SuperFP accumulate, or the reverse) when each holds one format.carrierisNone(the operands’ own),torch.float32(binary32) ortorch.float64(binary64).FusedMac(fma=None, *, rounding=RNE, accumulate_algorithm=NAIVE, carrier=None, block_size=None, outer=None)fmais a format, a palette, orNone.Palette(formats)Up to eight formats of one family, selected per output element. A plain list works anywhere a
Palettedoes; the class exists to validate.BlockMac(a, b=None, acc=None, *, fused=False, rounding=RNE, accumulate_algorithm=NAIVE, carrier=None, block_size=None, outer=None, tensor_scale_epilogue=False)A product of two block-format operands.
aandbare each aBlockFormator aBlockQuant(which specifies the rounding and a tensor scale).accis aBinaryKorNone. The multiply is binary32’s own (Block matrix products).tensor_scale_epiloguemoves the operands’ tensor scales out of the loop.
accumulate_algorithm selects how partial products are added to the sum:
NAIVE, the sequential recurrence, or
KAHAN, BLOCK or TREE (Dot-product arithmetic, “Summing differently”).
block_size applies to BLOCK and TREE. outer is the one format
that they round the total to, of the accumulate format’s family (the
multiply’s when acc is None); None leaves the total in the
carrier’s precision. A mac with an algorithm other than NAIVE
holds one format per slot, not a palette.
qmatmul, qmm and qbmm#
qmatmul() is torch.matmul in the arithmetic you
choose, and it is differentiable. Its formats argument accepts, from the
least to the most specific:
None: plaintorch.matmul, for a comparison against float32;a format (
BinaryK(8, 4)): shorthand forSplitMac(f, f);a
SplitMacorFusedMac;a
BlockMac(or a bareBlockFormat), which packs both operands in block formats and multiplies them with the block product (Block products, below);a
QMatmulFormats, which also carries quantizers for the operands and for each gradient (next section).
It accepts everything torch.matmul accepts: matrices, batches of
matrices, broadcasting between leading dimensions, and 1D operands, which
are promoted and squeezed back in the same way. Two common shapes need no
copy:
An operand that is the transpose of a contiguous tensor (
q @ k.mT) sets the kernel’s transpose flag and is not materialized.[..., M, K] @ [K, N]folds its batch intoM, giving one large product instead of a batch of small ones.
Both are bit-identical to the batched spelling, not merely close. Stochastic rounding keys each output element’s random stream on its global index, which is the same either way.
The gradients are the usual ones. Each is computed as a GEMM in the arithmetic of its own hook (by default, the forward’s):
followed by a reduction over any dimensions that the forward pass broadcast.
qmm() and qbmm() are the same
function with the rank checks of torch.mm and torch.bmm.
"""qmatmul: torch.matmul's contract, in the arithmetic you name."""
import torch
from mptorch import BinaryK
from mptorch.quant import QMatmulFormats, SplitMac, qbmm, qmatmul, qmm
torch.manual_seed(0)
binary8p4 = BinaryK(8, 4)
# Every formats spelling, from the loosest to the most specific.
a = torch.randn(4, 8)
b = torch.randn(8, 3)
print("None (plain torch.matmul) ", torch.equal(qmatmul(a, b), a @ b))
print(
"BinaryK == SplitMac(f, f) ",
torch.equal(qmatmul(a, b, binary8p4), qmatmul(a, b, SplitMac(binary8p4, binary8p4))),
)
print("QMatmulFormats() (nothing) ", torch.equal(qmatmul(a, b, QMatmulFormats()), a @ b))
# The operand rules are torch.matmul's: batches, broadcasting, 1D promotion.
cases = [
("2D @ 2D ", (4, 8), (8, 3)),
("batched ", (5, 4, 8), (5, 8, 3)),
("broadcast b ", (5, 4, 8), (8, 3)),
("broadcast leading", (2, 1, 4, 8), (3, 8, 3)),
("1D @ 2D ", (8,), (8, 3)),
("2D @ 1D ", (4, 8), (8,)),
("1D @ 1D ", (8,), (8,)),
]
for name, sa, sb in cases:
x, y = torch.randn(*sa), torch.randn(*sb)
out = qmatmul(x, y, binary8p4)
print(
f"{name} {str(tuple(sa)):<14} @ {str(tuple(sb)):<12} -> {tuple(out.shape)}"
f" shape as torch: {out.shape == (x @ y).shape}"
)
# qmm / qbmm are the rank-checked spellings, like torch.mm / torch.bmm.
print("\nqmm ", torch.equal(qmm(a, b, binary8p4), qmatmul(a, b, binary8p4)))
x3, y3 = torch.randn(5, 4, 8), torch.randn(5, 8, 3)
print("qbmm ", torch.equal(qbmm(x3, y3, binary8p4), qmatmul(x3, y3, binary8p4)))
try:
qbmm(a, b, binary8p4)
except ValueError as e:
print("qbmm on 2D:", e)
# It is differentiable in both operands. With no format the gradients are
# torch's own; with one, each gradient is a GEMM in that arithmetic.
a.requires_grad_(True)
b.requires_grad_(True)
qmatmul(a, b).sum().backward()
ga, gb = a.grad.clone(), b.grad.clone()
a.grad = b.grad = None
(a @ b).sum().backward()
print("\nno format: grads equal torch's:", torch.equal(ga, a.grad), torch.equal(gb, b.grad))
a.grad = b.grad = None
qmatmul(a, b, binary8p4).sum().backward()
cos = torch.nn.functional.cosine_similarity
print("Binary8p4: cos(grad_a, torch) =", f"{cos(a.grad.flatten(), ga.flatten(), dim=0):.4f}")
None (plain torch.matmul) True
BinaryK == SplitMac(f, f) True
QMatmulFormats() (nothing) True
2D @ 2D (4, 8) @ (8, 3) -> (4, 3) shape as torch: True
batched (5, 4, 8) @ (5, 8, 3) -> (5, 4, 3) shape as torch: True
broadcast b (5, 4, 8) @ (8, 3) -> (5, 4, 3) shape as torch: True
broadcast leading (2, 1, 4, 8) @ (3, 8, 3) -> (2, 3, 4, 3) shape as torch: True
1D @ 2D (8,) @ (8, 3) -> (3,) shape as torch: True
2D @ 1D (4, 8) @ (8,) -> (4,) shape as torch: True
1D @ 1D (8,) @ (8,) -> () shape as torch: True
qmm True
qbmm True
qbmm on 2D: qbmm expects 3D tensors, got 2D and 2D
no format: grads equal torch's: True True
Binary8p4: cos(grad_a, torch) = 0.9994
QMatmulFormats and QMatmul#
QMatmulFormats holds everything a quantized matmul
can vary. Its slots mirror the layer formats of Layers, renamed for
an operation whose two operands play the same role:
slot |
what it does |
|---|---|
|
quantizer applied to |
|
quantizer applied to |
|
quantizer applied to \(G\) before |
|
quantizer applied to \(G\) before |
|
the forward product, |
|
|
|
|
Every slot is optional, and None means “plain PyTorch”. There is no
output_quant, on purpose: rounding the result is an elementwise step, so
apply a Quantizer after the product.
matmul_formats() builds a QMatmulFormats with the
three math hooks set to the arithmetic of a SplitMac or FusedMac. It
sets nothing else, so quantizers are added separately.
QMatmul is the module form: an nn.Module holding
a QMatmulFormats, so that a quantizer with state is registered in the
model. A quantized attention head calls two of them:
"""QMatmul: the module form, for quantizers that carry state."""
import torch
from torch import nn
from mptorch import BinaryK
from mptorch.quant import QMatmul, QMatmulFormats, Quant, Quantizer, SplitMac, matmul_formats
torch.manual_seed(0)
class QAttention(nn.Module):
"""One attention head with both matmuls in Binary8p4 arithmetic."""
def __init__(self, dim: int, formats: QMatmulFormats):
super().__init__()
self.scale = dim**-0.5
self.qk = QMatmul(formats) # scores = q @ k^T
self.pv = QMatmul(formats) # out = p @ v
def forward(self, q, k, v):
scores = self.qk(q, k.transpose(-2, -1)) * self.scale # k^T is a view: no copy
p = torch.softmax(scores, dim=-1)
return self.pv(p, v)
binary8p4 = BinaryK(8, 4)
formats = matmul_formats(SplitMac(binary8p4, None)) # Binary8p4 products, float32 sums
formats.a_quant = Quant(binary8p4) # round both operands to Binary8p4 on the way in
formats.b_quant = Quant(binary8p4)
formats.agrad_quant = Quantizer(BinaryK(8, 3, prng_bits=8)) # stochastic Binary8p3 on the gradient
formats.bgrad_quant = formats.agrad_quant
head = QAttention(64, formats)
q, k, v = (torch.randn(2, 128, 64, requires_grad=True) for _ in range(3))
out = head(q, k, v)
out.sum().backward()
print(
"output",
tuple(out.shape),
" grads:",
tuple(q.grad.shape),
tuple(k.grad.shape),
tuple(v.grad.shape),
)
# The Quantizer is registered under the QMatmul that holds it, so any state a
# quantizer keeps travels with the model. (named_modules lists a shared module
# once: both heads hold the same formats, and both gradient slots the same
# Quantizer.)
print("\nsubmodules:")
for name, _ in head.named_modules():
if name:
print(" ", name)
output (2, 128, 64) grads: (2, 128, 64) (2, 128, 64) (2, 128, 64)
submodules:
qk
qk.formats
qk.formats.agrad_quant
pv
Palettes: a map per pass, held and reused#
A palette (Dot-product arithmetic, “Palettes”) picks a format per output element
through an integer map, prec_idx, indexed by output element. The three
passes of a differentiable matmul have three output shapes: [M, N],
[M, K] and [K, N]. A palette that has to differentiate therefore
needs one map per pass, given to matmul_formats as prec_idx,
agrad_prec_idx and bgrad_prec_idx. If a pass’s map is missing, the
pass raises when it is reached and names the argument. It does not fall back
to something unquantized.
Keep the map and reuse it. The bounds check on its values is memoized
against the tensor you pass, and an int32, contiguous map on the
operands’ device is passed to the kernel unchanged. A map rebuilt on every
call is re-checked and re-packed on every call.
Block products#
block_matmul() multiplies two packed tensors, the
BlockPacked objects that
block_pack() returns. a is logically
[..., M, K] and b is [..., K, N]. Each has its own format, so an
MXFP4 weight can multiply an MXFP8 activation. This is the block product of
Block matrix products. It is bit for bit the flat binaryK product on the decoded
operands with a binary32 multiply:
"""The block GEMM: two packed operands, decoded in the kernel's tile loads."""
import warnings
import torch
from mptorch import MXFP4_E2M1, MXFP8_E4M3, BinaryK, FormatRangeWarning
from mptorch.quant import BlockMac, binaryK_matmul, block_matmul, block_pack, qmatmul
torch.manual_seed(0)
x, w = torch.randn(8, 256), torch.randn(32, 256)
xp = block_pack(x, MXFP8_E4M3) # [8, 256], blocks along K
wp = block_pack(w, MXFP4_E2M1) # [32, 256], blocks along K, as a weight is stored
acc = BinaryK(16, 11) # the running sum rounded to binary16's precision
y = block_matmul(xp, wp.mT, acc=acc) # x @ w.T; .mT reads w's codes transposed
# The same numbers as the flat binaryK GEMM on the decoded operands, with a
# binary32 multiply: binary32 itself as a binaryK format, the identity on
# every product here (the warning is that its top, 2^128, is past binary32's).
with warnings.catch_warnings():
warnings.simplefilter("ignore", FormatRangeWarning)
flat = binaryK_matmul(
xp.unpack(), wp.unpack(), trans_b=True, mul_K=32, mul_P=24, mul_bias=127, acc_K=16, acc_P=11
)
print("equal to the flat GEMM on the decoded operands:", torch.equal(y, flat))
ref = x @ w.T
print(f"relative error against float32: {((y - ref).norm() / ref.norm()).item():.3f}")
# The differentiable spelling: qmatmul packs both operands in the forward
# and each gradient pass packs what it multiplies
a = torch.randn(8, 256, requires_grad=True)
b = torch.randn(256, 32, requires_grad=True)
out = qmatmul(a, b, BlockMac(MXFP8_E4M3, MXFP4_E2M1, acc))
out.sum().backward()
print("gradients:", tuple(a.grad.shape), tuple(b.grad.shape))
equal to the flat GEMM on the decoded operands: True
relative error against float32: 0.118
gradients: (8, 256) (256, 32)
Each operand is read along K. An operand packed along its K is the natural
case: a weight [N, K] blocked along K is read through
mT. An operand packed along its other
dimension is read transposed.
BlockMac is the value spelling.
qmatmul() and QMatmul accept
one, and a bare BlockFormat means BlockMac(fmt). The forward pass
packs a and b along their K. Each gradient pass packs what it
multiplies along the dimension it sums over, as Block matrix products explains.
block_matmul_formats() builds the QMatmulFormats,
with one BlockMac per pass. An operand whose format has a square tile is
packed once, in the forward pass, and the gradient passes read that packing
transposed.
tensor_scale_epilogue=True applies the operands’ per-tensor scales to
the result instead of in the decode (Block matrix products, “Tensor scales”). It is
accepted by block_matmul, by a BlockMac and by the layer factory
block_gemm_formats().
Convolutions#
The convolutions have ten operators of their own, custom_conv_*, one
per matrix-product operator family (two of them for the cross-family
SplitMac). They take the convolution’s geometry in
place of the transpose flags. There are no Python functions for them. A
QConv1d/2d/3d reaches them through
conv_formats(), which fills the layer’s three math
hooks from a mac, as matmul_formats() does for a matmul
(Layers, “Convolutions”). Convolutions describes what they
compute.
The schema tier#
Below the value vocabulary there are ten functions, one per kernel. Each
spells out every argument of the kernel’s schema and has no autograd:
binaryK_matmul, superfp_matmul, their _fma variants, the
_mixed (palette) variants of all four, and the two cross-family split
macs, binaryK_superfp_matmul (BinaryK products, SuperFP sums) and
superfp_binaryK_matmul. They are for scripts that need to
state exactly what the kernel receives. The vocabulary resolves to them: the
test suite asserts that a SplitMac and the equivalent flat call produce
the same resolved kernel arguments.
"""The schema tier: one function per op, every argument spelled out."""
import warnings
import torch
from mptorch import FormatRangeWarning, RoundMode, SaturationMode
from mptorch.quant import (
binaryK_matmul,
binaryK_matmul_fma,
binaryK_matmul_mixed,
superfp_matmul,
superfp_matmul_fma,
)
# An 8-exponent-bit binaryK reaches below 2**-126, where the casts cannot tell
# one input from another, so naming one warns (concepts, "What float32 can
# carry"). Nothing here goes anywhere near that small.
warnings.simplefilter("ignore", FormatRangeWarning)
torch.manual_seed(0)
a = torch.randn(4, 16)
b = torch.randn(3, 16) # will be read transposed
# Binary8p4 multiply, Binary16p8 accumulate, no gradient tracking.
out = binaryK_matmul(a, b, trans_b=True, mul_K=8, mul_P=4, acc_K=16, acc_P=8)
cos = torch.nn.functional.cosine_similarity
print(
"binaryK_matmul ",
tuple(out.shape),
f"cos to float32: {cos(out.flatten(), (a @ b.T).flatten(), dim=0):.4f}",
)
# trans_* flags apply to the last two dimensions, with no copy for a view.
print(
"== a @ b.T ",
torch.equal(out, binaryK_matmul(a, b.T, mul_K=8, mul_P=4, acc_K=16, acc_P=8)),
)
# Fused, saturating, round-to-zero.
out = binaryK_matmul_fma(
a,
b,
trans_b=True,
fma_K=8,
fma_P=4,
rounding_mode=RoundMode.RZ,
saturation_mode=SaturationMode.SAT_FINITE,
)
print("binaryK_matmul_fma ", tuple(out.shape))
# superfp needs its bias spelled out: the format has no default rule for one.
out = superfp_matmul(
a, b, trans_b=True, mul_man_bits=3, mul_exp_bits=4, mul_normal_binades=2, mul_bias=7
)
print("superfp_matmul ", tuple(out.shape))
out = superfp_matmul_fma(
a, b, trans_b=True, fma_man_bits=3, fma_exp_bits=4, fma_normal_binades=2, fma_bias=7
)
print("superfp_matmul_fma ", tuple(out.shape))
# The palette ops take per-entry sequences and a prec_idx map.
prec_idx = torch.tensor([[0], [1], [0], [1]])
out = binaryK_matmul_mixed(a, b, prec_idx, trans_b=True, mul_K=[8, 8], mul_P=[4, 3])
print("binaryK_matmul_mixed", tuple(out.shape))
# None of them carries a gradient; that is qmatmul's job.
try:
binaryK_matmul(a.requires_grad_(True), b, trans_b=True, mul_K=8, mul_P=4)
except RuntimeError as e:
print("\nRuntimeError:", str(e)[:120], "...")
binaryK_matmul (4, 3) cos to float32: 0.9998
== a @ b.T True
binaryK_matmul_fma (4, 3)
superfp_matmul (4, 3)
superfp_matmul_fma (4, 3)
binaryK_matmul_mixed (4, 3)
RuntimeError: mptorch::custom_matmul_binaryK is not differentiable: it simulates the arithmetic of its own reduction, so which format ...
The ten functions share their conventions:
mul_*andacc_*give the two formats of a split multiply-accumulate.acc_*default to themul_*values, andaccumulate_quant=Falseleaves the sum unrounded. In the two cross-family functions theacc_*widths are the other family’s, so they are required, and there is noaccumulate_quant.fma_*gives the one format of a fused step, andfma_quant=Falseleaves it unrounded.trans_aandtrans_btranspose the last two dimensions of an operand without copying it.*_prng_bitsset the stochastic bits per format.carrierchooses the arithmetic, as on aSplitMac.The
_mixedvariants take sequences for the width arguments, a scalar for anything the palette shares, andprec_idxas the third positional argument.
The six single-format functions also take accumulate_algorithm, its
block_size and the outer format, spelled outer_* in the same way as
the accumulate format. An algorithm other than NAIVE routes the
call to the kernel’s *_accumulated twin, which is a separate operator. A
NAIVE call is therefore exactly the call it was before the other three
algorithms existed.
Callers that keep one format across many calls should use the factories or
qmatmul instead. These functions re-derive the format’s defaults on
every call, which the resolved objects avoid. The convolutions’ operators
have no functions at this tier (Convolutions, above), and the block
product’s function is block_matmul() itself.
torch.compile and torch.export#
Every operator has a fake (Meta) kernel. It runs the CPU operator’s checks
and allocates a result of the shape, dtype and layout the CPU allocates, but
computes nothing and draws no random state. The meta device,
FakeTensorMode, torch.export.export() and torch.compile()
run it in the operator’s place. Its sizes may be symbolic: a batch, a
matrix extent or a channel count can stay dynamic in a compiled graph or an
exported program. An extent passed to an operator as an integer cannot:
the spatial size of a convolution’s output, and the length of a block
format’s packed axis. Those specialize.
"""The kernels under torch.export and torch.compile."""
import warnings
import torch
from mptorch import RoundMode
from mptorch.quant import QLinear, binaryK_gemm_formats, binaryK_matmul, binaryK_quantize
torch.manual_seed(0)
layer = QLinear(32, 16, formats=binaryK_gemm_formats(8, 4, acc_K=16, acc_P=11))
# Export with a dynamic batch. The program is the forward alone: the layer's
# autograd.Function is inlined and its GEMM operator is in the graph.
x = torch.randn(8, 32)
ep = torch.export.export(layer, (x,), dynamic_shapes=({0: torch.export.Dim.AUTO},))
print([str(n.target) for n in ep.graph.nodes if n.op == "call_function"])
program = ep.module()
with torch.no_grad(): # the forward alone has no gradient to give
for batch in (8, 5):
x = torch.randn(batch, 32)
print(batch, torch.equal(program(x), layer(x)))
# Compile two GEMMs and a quantizer, here under stochastic rounding. The flat
# functions trace into one graph; with fallback_random the random operators
# run in program order, so the compiled result is eager's, draw for draw.
# Dynamo traces through the format checks' lru_cache, which it says once per
# function; the checks are pure, so their cache only saves time.
warnings.filterwarnings("ignore", message="Dynamo detected a call to a `functools.lru_cache`")
SR = RoundMode.SR
def step(a, b):
kw = dict(mul_K=8, mul_P=4, mul_prng_bits=8, acc_K=16, acc_P=11, acc_prng_bits=8)
q = binaryK_quantize(a, 8, 4, prng_bits=8, rounding_mode=SR)
h = binaryK_matmul(q, b, rounding_mode=SR, **kw)
return binaryK_matmul(torch.relu(h), b, trans_b=True, rounding_mode=SR, **kw)
a, b = torch.randn(8, 16), torch.randn(16, 16)
explanation = torch._dynamo.explain(step)(a, b)
print(f"{explanation.graph_count} graph, {explanation.graph_break_count} breaks")
compiled = torch.compile(step)
with torch._inductor.config.patch(fallback_random=True):
torch.manual_seed(1)
got = compiled(a, b)
torch.manual_seed(1)
print("compiled == eager:", torch.equal(got, step(a, b)))
['aten.sym_size.int', 'aten.reshape.default', 'mptorch.custom_matmul_binaryK.default', 'aten.reshape.default', 'aten.add_.Tensor']
8 True
5 True
1 graph, 0 breaks
compiled == eager: True
What to expect:
An exported layer is its forward. Export inlines the layer’s autograd function, so the program holds the GEMM operator and no gradient. Run it under
torch.no_grad(): in grad mode the operator meets a parameter that requires a gradient, and refuses it, as it refuses any (an operator’s gradient is its layer’s to compute).The flat functions compile into one graph. The layers’ autograd functions break the graph on torch 2.14, so each layer runs eagerly between the compiled pieces. The results are the same either way.
Stochastic rounding. Every operator that takes a rounding mode is tagged
nondeterministic_seeded, so a compiled graph never merges two identical stochastic calls into one draw. Inductor may still reorder independent random operators, and it removes one whose result is unused, as it does PyTorch’s own random operators. The compiled draws are then valid but not eager’s.torch._inductor.config.fallback_random = Truekeeps them in program order, and the result is eager’s, bit for bit.The checks that need values run when the operator does. These are a palette’s
prec_idxbounds, CUDA’s alignment check on an in-place quantizer’s view, and the operators that MPS refuses. The fake kernel cannot read tensor values or addresses.
Performance notes#
Resolve once.
SplitMac/FusedMac/BinaryK/SuperFPare frozen and hashable, andqmatmulmemoizes the resolution of theformatsit is given. Constructing a newSplitMacper call still hits the cache. Constructing aQMatmulFormatsper call does not. Keeping aQMatmulmodule, or theQMatmulFormatsthat a factory returned, costs nothing per call beyond the kernel.One launch per batch. A batched call is one kernel launch (one parallel region on the CPU) over the whole batch. On attention-shaped operands it is 2-4x faster than the loop of 2D calls it replaces (
dev/benchmarks/timing/benchmark_qmatmul.py).Stochastic rounding is not free. Each rounding draws from a per-element Philox stream, so a
RoundMode.SRGEMM is slower than a deterministic one.binary64 is slower. On an RTX 4060 a float64 GEMM took 2.7-3.1x the time of the same product computed in binary32 (up to 6x for a stochastic split step). On the CPU the two are within a percent, except where binary32 runs vector code (next item), which binary64 does not. A float64 model whose formats binary32 can carry gets the binary32 speed back as a float32 model. A float32 model with
carrier=torch.float64pays the binary64 time plus the widening and narrowing copies.On the CPU, binaryK under round-to-nearest-even is the fast case. A binaryK split or fused product, or one that quantizes only the products, in binary32 under
RoundMode.RNE, with theNAIVEaccumulator and one format per slot, runs its tiles in vector code (AVX-512 or AVX2 on x86-64, NEON on arm64), and so do the convolutions on it. Its formats must be signed, keep their subnormals, not saturate withSAT_PROPAGATE, and have a precision from 2 to 23 bits and a range well inside binary32’s (in practice at most seven exponent bits). The results are the scalar loop’s, word for word. On a Ryzen 9 7940HS (AVX-512) that is 7-9x the scalar loop on one thread (a split step 7.8 to 1.1 ns) and 7-11x on sixteen; on an M3 Pro (NEON) about 4x at every thread count (0.69 ns a split step on one). Every other mode, format and accumulator runs the scalar loop, and so does any call under the environment variableMPTORCH_CPU_SIMD=0, read when mptorch loads.Block products and convolutions cost what their matrix products cost. Decoding a block operand adds 5-18% to the flat product on the decoded operands (Block matrix products, “How the kernel decodes”). A convolution’s gathered loads add a few percent of address arithmetic (Convolutions, “What it costs”).
The kernels are simulators. They are written for exactness and flexibility, not for speed, and are orders of magnitude slower than cuBLAS. The Linear layers fold their batch into one GEMM, which is the shape the kernels handle best.