API reference#

The public surface, grouped as the guides are: formats, quantizers, kernels and layers. Everything documented here is importable from the two packages mptorch (formats and enums) and mptorch.quant (quantizers, kernels, layers).

Number formats and modes#

See Formats and rounding. The presets are importable from mptorch: the element and scale formats E8M0, E4M3, E5M2, E2M1, E2M3 and E3M2 (each a BinaryK), and the block formats MXFP8_E4M3, MXFP8_E5M2, MXFP6_E2M3, MXFP6_E3M2, MXFP4_E2M1 and NVFP4 (each a BlockFormat), and bfp() builds block floating point.

Number formats, the modes that round into them, and what a float makes of them.

The enums here (RoundMode, SaturationMode, SubnormalsMode, AccumulateAlgorithm) mirror the C++ enums in csrc/common/modes.h one to one, by name and by integer value. The kernels receive .value across the torch.ops boundary, so the two must stay in sync. Domain exists in Python only: a format object folds it into its SaturationMode when it is built. BinaryK and SuperFP are the frozen value types that describe a format.

The check_* functions report what a carrier (the binary float a cast rounds in) and a storage dtype (the tensor a result is written to) can do with a format. They raise ValueError where the format cannot work at all, and warn with FormatRangeWarning where it works over part of its range.

class mptorch.number.SaturationMode(*values)[source]#

What a format does with a value beyond its largest finite one.

Mirrors SaturationMode in csrc/common/modes.h, by name and value. Each member combines one of IEEE P3109’s three saturation modes with the format’s domain (see Domain), which P3109 chooses separately. The finite domain spends on finite values the code points that the extended domain spends on the infinities, and it admits only SatFinite. That leaves four valid combinations, one member each: SAT_FINITE is the finite domain, and the other three are the extended one.

On a BinaryK or SuperFP the domain can be given with domain= instead: saturation=SAT_FINITE, domain=Domain.EXTENDED is stored as SAT_FINITE_EXTENDED. The flat *_quantize and *_matmul functions take no format object, so they name the combination with the member alone.

The mode is a property of each format slot. A GEMM whose multiply saturates and whose accumulate overflows to infinity can therefore be expressed. A NaN input passes through every mode unchanged.

Example:

>>> from mptorch import BinaryK, SaturationMode
>>> from mptorch.quant import Quant
>>> import torch
>>> x = torch.tensor([1.1, 3.3, 500.0])
>>> Quant(BinaryK(8, 4, bias=7))(x).tolist()
[1.125, 3.25, inf]
>>> sat = SaturationMode.SAT_FINITE
>>> Quant(BinaryK(8, 4, bias=7, saturation=sat))(x).tolist()
[1.125, 3.25, 480.0]
SAT_FINITE = 0#

every result beyond the largest finite value, an infinite input included, clamps to that value.

Type:

P3109 SatFinite, finite domain

SAT_PROPAGATE = 1#

a finite result beyond the largest finite value clamps to it, and an infinite one stays infinite.

Type:

P3109 SatPropagate, extended domain

SAT_NONE = 2#

a result beyond the largest finite value becomes \(\pm\infty\) under every rounding mode, because the overflow test reads the rounded value. This differs from IEEE 754, whose roundTowardZero never rounds a finite value to infinity.

Type:

P3109 SatNone, extended domain, the default

SAT_FINITE_EXTENDED = 3#

the format keeps its infinity codes, so its largest finite value is that of SAT_NONE and SAT_PROPAGATE. Every result beyond it, an infinite input included, clamps to it, as under SAT_FINITE.

Type:

P3109 SatFinite, extended domain

class mptorch.number.Domain(*values)[source]#

Whether a format spends code points on the infinities: P3109’s domain.

The extended domain has \(\pm\infty\) (the top code of each sign). The finite domain spends those codes on finite values, so its largest finite value is one code higher, and it admits only the SatFinite saturation mode. A BinaryK or SuperFP takes the domain as domain= and folds it into its SaturationMode when it is built. If it is left None, it follows from the saturation mode: finite for SAT_FINITE and extended otherwise.

Example:

>>> from mptorch import BinaryK, Domain, SaturationMode
>>> f = BinaryK(8, 4, saturation=SaturationMode.SAT_FINITE, domain=Domain.EXTENDED)
>>> f.saturation, f == BinaryK(8, 4, saturation=SaturationMode.SAT_FINITE_EXTENDED)
(<SaturationMode.SAT_FINITE_EXTENDED: 3>, True)
>>> BinaryK(8, 4, saturation=SaturationMode.SAT_FINITE).domain
<Domain.FINITE: 1>
EXTENDED = 0#

P3109’s e formats (Binary8p4se).

Type:

Has \(\pm\infty\)

FINITE = 1#

the f formats.

Type:

No infinities, and every code a value or the NaN

class mptorch.number.SubnormalsMode(*values)[source]#

How a format handles the range below its smallest normal number.

Mirrors SubnormalsMode in csrc/common/modes.h, by name and value. Only SUBNORMALS is IEEE P3109’s: every P3109 format with more than one bit of precision has subnormals. The other two give formats outside the standard. The three differ only in where the bottom of the range is.

Below the bottom they all behave the same way. An input x has two candidates for its magnitude, zero and the smallest value x_min, and the rounding mode picks between them:

  • RoundMode.RNE and RoundMode.RNA take the nearer one. On a tie, RNE takes the zero and RNA takes x_min.

  • The directed modes take the candidate in their own direction.

  • RoundMode.RO takes x_min, the nonzero candidate.

  • RoundMode.SR takes x_min with probability |x| / x_min.

All three keep the same two special codes, which the casts’ NaN detection and sign handling rely on. The all-zero code is the one zero. It is unsigned, as in P3109, and no cast ever returns -0.0. In a signed format, the code with only the sign bit set (the one that would encode -0.0) is the NaN.

Example:

>>> from mptorch import BinaryK, SubnormalsMode
>>> from mptorch.quant import Quant
>>> import torch
>>> x = torch.tensor([2**-7, 2**-6])  # below and at the smallest normal
>>> Quant(BinaryK(8, 4, bias=7))(x).tolist()
[0.0078125, 0.015625]
>>> flush = SubnormalsMode.NORMALS
>>> Quant(BinaryK(8, 4, bias=7, subnormals=flush))(x).tolist()
[0.0, 0.015625]
SUBNORMALS = 0#

exponent code 0 holds subnormals.

Type:

Gradual underflow, the default

NORMALS = 1#

below the smallest normal, zero or that normal.

Type:

No subnormals

EXTENDED_NORMALS = 2#

No subnormals. Exponent code 0 is one more binade of normal numbers, except its mantissa-zero code, which is still the zero (and with the sign bit the NaN). That binade’s values therefore start one step above the power of two at its foot.

class mptorch.number.RoundMode(*values)[source]#

How a value is rounded onto a format’s grid.

Mirrors RoundMode in csrc/common/modes.h, by name and value. Each member is one of IEEE P3109’s rounding modes, whose name is given in parentheses, and defines the result \(y\) of rounding an input \(x\).

The rounding mode is a property of the operation, not of the format. The kernels take it as a template parameter, because a runtime switch inside a GEMM’s accumulate step cost 1.2 to 2.3 times the kernel time. mptorch.quant.Quant and mptorch.quant.SplitMac therefore carry it next to the format.

Stochastic rounding draws each output element’s random bits from a stream keyed on that element’s index in the output. The result does not depend on how the work is split across threads or batches. P3109 defines three stochastic modes, SR (StochasticA, also spelled SR_A), SR_B and SR_C, which differ in how they read the prng_bits random bits (Formats and rounding, “Stochastic rounding”).

Example:

>>> from mptorch import BinaryK, RoundMode
>>> from mptorch.quant import Quant
>>> import torch
>>> x = torch.tensor([1.1, 3.3])
>>> Quant(BinaryK(8, 4, bias=7), RoundMode.RNE)(x).tolist()
[1.125, 3.25]
>>> Quant(BinaryK(8, 4, bias=7), RoundMode.RZ)(x).tolist()
[1.0, 3.25]
>>> Quant(BinaryK(8, 4, bias=7), RoundMode.RU)(x).tolist()
[1.125, 3.5]
RNE = 0#

Round to nearest, ties to even (NearestTiesToEven)

RNA = 1#

Round to nearest, ties to away from zero (NearestTiesToAway)

RU = 2#

The smallest \(y\) such that \(y \ge x\) (TowardPositive)

RD = 3#

The largest \(y\) such that \(y \le x\) (TowardNegative)

RZ = 4#

The largest \(y\) such that \(|y| \le |x|\) (TowardZero)

RO = 5#

Round to odd (ToOdd)

SR = 6#

Stochastic rounding with prng_bits = \(N\) random bits \(R\) (StochasticA): with \(\eta\) the fraction of \(|x|\) between its two neighbours, rounds away from zero iff \(\lfloor \eta 2^N \rfloor + R \ge 2^N\)

SR_B = 7#

away iff \(\lfloor \eta 2^{N+1} \rfloor + 2R + 1 \ge 2^{N+1}\)

Type:

StochasticB

SR_C = 8#

away iff \(\mathrm{RNITE}(\eta 2^N) + R \ge 2^N\), RNITE rounding to nearest with ties to even

Type:

StochasticC

SR_A = 6#

SR’s other name (an alias)

Type:

StochasticA

property is_stochastic: bool#

SR (SR_A), SR_B or SR_C.

Type:

Whether this mode draws random bits

class mptorch.number.AccumulateAlgorithm(*values)[source]#

How the partial products of a dot product are folded into its sum.

Mirrors AccumulateAlgorithm in csrc/common/modes.h, by name and value. It selects the reduction inside a custom-arithmetic GEMM (mptorch.quant.SplitMac, mptorch.quant.FusedMac, the flat *_matmul wrappers).

Notation: a and b are the two operands of one step, and s is the running sum. round_mul and round_acc are the mac’s two roundings. round_acc is the identity when there is no accumulate format. In a fused mac it is the fused format’s rounding, and the step is round_acc(fma(a, b, s)) in place of round_acc(s + round_mul(a * b)). round_out is the rounding of the mac’s outer format (the identity without one). The products are taken in order, k = 1 .. K:

  • NAIVE: s = round_acc(s + round_mul(a * b)), as a hardware accumulator of the accumulate format does. The result is s.

  • KAHAN: a compensation c is carried next to the sum, also in the accumulate format: y = round_acc(round_mul(a * b) - c), t = round_acc(s + y), c = round_acc(round_acc(t - s) - y), s = t. The result is s. With no accumulate format this is Kahan’s summation in the carrier.

  • BLOCK: the NAIVE step runs on a block’s sum s. After every block_size products, and after the last one, the block is added to a total, tot = round_out(tot + s), and s restarts from zero. This gives two levels of precision: a narrow accumulate format inside a block, and a wider outer format across blocks. The result is tot.

  • TREE: the rounded products p1, p2, ... of a block of block_size = 2**L are summed pairwise, in the order they arrive: round_acc(round_acc(p1 + p2) + round_acc(p3 + p4)) and so on up. The block’s root is added to the total as in BLOCK. A last, partial block merges the subtrees it has, smallest first. The algorithm needs a product term, so a fused mac refuses it.

Under RoundMode.SR every rounding that is not an identity draws once, in the order written. Nothing is padded, so a result does not depend on how a backend tiles K, and the CPU, CUDA and MPS kernels agree to the bit in every deterministic mode (MPS up to the Apple GPU’s flush of binary32 subnormals in the arithmetic between roundings). An MPS result is the CPU’s under SR as well, since both draw from the CPU generator. KAHAN, BLOCK and TREE are implemented for the single-format ops, the cross-family ones, the conv ops and the block GEMM, in both carriers (binary32 only on MPS, which has no float64). A palette raises.

Example:

>>> from mptorch import AccumulateAlgorithm
>>> AccumulateAlgorithm.NAIVE.value
0
NAIVE = 0#

Quantize the running sum after every accumulation step.

KAHAN = 1#

Kahan-compensated summation, the compensation in the accumulate format.

BLOCK = 2#

Two-level (FABSum-style) block summation with an outer format.

TREE = 3#

Pairwise summation within a block, folded with an outer format.

class mptorch.number.Number[source]#

Base class for every simulated number format.

Its subclasses are FloatFormat (the element-by-element float families), FixedPoint (the multiples of a step that a word of bits holds; an elementwise quantizer so far, and no GEMM) and BlockFormat (block minifloats: OCP MX and NVFP4, whose elements share a scale per block). Block floating point with integer mantissas, and logarithmic and tapered (posit) formats would also belong here. Each needs a kernel first, so none is declared as an empty class in the meantime.

Example:

>>> from mptorch import BinaryK, Number
>>> isinstance(BinaryK(8, 4), Number)
True
class mptorch.number.FloatFormat[source]#

Base class for the two floating-point families the kernels implement.

BinaryK and SuperFP are its subclasses. A quantizer or GEMM factory that takes a FloatFormat accepts either.

Example:

>>> from mptorch import FloatFormat, SuperFP
>>> isinstance(SuperFP(3, 4, 2, 7), FloatFormat)
True
class mptorch.number.BinaryK(K, P, *, bias=None, is_signed=True, prng_bits=0, saturation=SaturationMode.SAT_NONE, domain=None, subnormals=SubnormalsMode.SUBNORMALS)[source]#

An IEEE P3109 binaryK float: K total bits of which P are precision.

P3109 is the draft Standard for Arithmetic Formats for Machine Learning (Fitzgibbon, Wintersteiger and Sarnoff give an overview in arXiv:2606.04028). It parameterizes its binary formats by bitwidth, precision (the implicit leading bit included), signedness and domain, and names them Binary<K>p<P><s|u><e|f>. K, P, is_signed and domain are those four. BinaryK(8, 4) is Binary8p4se, and BinaryK(8, 4, domain=Domain.FINITE, saturation=SaturationMode.SAT_FINITE) is Binary8p4sf. The finite domain admits only SAT_FINITE, so that saturation mode alone also selects it.

Three of P3109’s conventions are worth knowing:

  • The format has one zero, unsigned, at the all-zero code. No cast returns -0.0.

  • In a signed format the NaN is the code with only the sign bit set (which would hold -0.0). In an unsigned format it is the top code.

  • The largest finite value is counted in code points. With one or two mantissa bits, the codes reserved for infinity and NaN can push it a binade or two down.

Formats and rounding maps the rest of the standard onto this class and says where MPTorch goes beyond it.

The rounding mode is a property of the operation, not of the format (see mptorch.quant.Quant and mptorch.quant.SplitMac), because the kernels take it as a template parameter shared by a multiply and its accumulate. The instance is frozen, and therefore hashable, because the code that resolves a format memoizes on its value. The derived bias is filled in at construction, not at each call site.

Parameters:
  • K (int) – total bits, sign included.

  • P (int) – bits of precision, the implicit leading bit included, so P - 1 mantissa bits are stored; 1 <= P <= K.

  • bias (int | None) – exponent bias. Default: P3109’s, 2**(K-P-1) signed and 2**(K-P) unsigned, which encodes 1.0 at the middle code point. Any other bias gives a format outside the standard. The layout of OCP’s E4M3 is spelled this way: BinaryK(8, 4, bias=7).

  • is_signed (bool) – whether the format has a sign bit. Default: True.

  • prng_bits (int) – width of the random mantissa drawn by RoundMode.SR, ignored under every other rounding mode. Default: 0.

  • saturation (SaturationMode) – overflow behaviour. Default: SaturationMode.SAT_NONE.

  • domain (Domain | None) – whether the format has infinities. Domain.FINITE admits only SAT_FINITE. Domain.EXTENDED with SAT_FINITE is stored as SaturationMode.SAT_FINITE_EXTENDED. Default: None, which follows from saturation: finite for SAT_FINITE, extended otherwise. The instance stores the resolved domain.

  • subnormals (SubnormalsMode) – what lies below the smallest normal. Any value other than SUBNORMALS gives a format outside the standard. Default: SubnormalsMode.SUBNORMALS.

Raises:
  • ValueError – for the finite domain with a saturation mode other than SAT_FINITE. Otherwise only for a format that neither carrier can simulate: more than 53 bits of precision, P - 1 + prng_bits above 52, an exponent field past 30 bits, a negative prng_bits, or no finite value that binary64 holds. Nothing warns here. Whether float32 or float64 arithmetic carries the format depends on the call, so each call checks the format against its own carrier (see FormatRangeWarning).

  • TypeError – if saturation is not a SaturationMode or domain is not a Domain.

Example:

>>> from mptorch import BinaryK
>>> BinaryK(8, 4).bias  # P3109 Binary8p4se
8
>>> BinaryK(8, 4, is_signed=False).bias  # Binary8p4ue
16
>>> BinaryK(8, 4, bias=7).man_bits  # OCP E4M3's layout
3
K: int#
P: int#
bias: int | None = None#
is_signed: bool = True#
prng_bits: int = 0#
saturation: SaturationMode = 2#
domain: Domain | None = None#
subnormals: SubnormalsMode = 0#
property man_bits: int#

Mantissa bits, as the cast counts them (the implicit bit is not one).

class mptorch.number.SuperFP(man_bits, exp_bits, normal_binades, bias, *, is_signed=True, prng_bits=0, saturation=SaturationMode.SAT_NONE, domain=None)[source]#

A supernormal float, as common/cast_superfp.h implements it.

The top normal_binades binades of the exponent range keep a full man_bits-bit mantissa. The remaining binades would have spent n = (2**exp_bits - normal_binades) * 2**man_bits codes on mantissas. Those codes instead encode the zero and n - 1 further powers of two below the normal binades (the supernormals). Everything below those flushes to zero. The format therefore trades precision at the bottom of the range for dynamic range at the same width.

The class is deliberately not symmetric with BinaryK:

  • bias is required and has no default, because the cast has no rule to derive one.

  • There is a single normal_binades, not one per end of the range.

  • There is no subnormals mode, because the format has no subnormals.

The format spends no code point on a NaN, so signedness does not move the top of the range. Its one zero is unsigned, like binaryK’s. The instance is frozen, and therefore hashable, because the code that resolves a format memoizes on its value, as for BinaryK.

Parameters:
  • man_bits (int) – stored mantissa bits in the normal region.

  • exp_bits (int) – exponent field width, at least 1.

  • normal_binades (int) – binades at the top of the range that keep their mantissa. At least 1 and at most 2**exp_bits - 1, so that at least one supernormal code remains.

  • bias (int) – exponent bias.

  • is_signed (bool) – whether the format has a sign bit. Default: True.

  • prng_bits (int) – width of the random mantissa drawn by RoundMode.SR. Default: 0.

  • saturation (SaturationMode) – overflow behaviour. Default: SaturationMode.SAT_NONE.

  • domain (Domain | None) – whether the top code is an infinity, as for BinaryK. Default: None, which follows from saturation.

Raises:
  • ValueError – for the finite domain with a saturation mode other than SAT_FINITE; for a format that neither carrier can simulate, as for BinaryK; and for a normal_binades that leaves no supernormal codes. Each call checks the format against its own carrier (see FormatRangeWarning).

  • TypeError – as for BinaryK.

Example:

>>> from mptorch import SuperFP
>>> from mptorch.quant import Quant
>>> import torch
>>> f = SuperFP(man_bits=3, exp_bits=4, normal_binades=2, bias=7)
>>> x = torch.tensor([300.0, 3.0, 0.001])  # normal, supernormal, supernormal
>>> Quant(f)(x).tolist()
[288.0, 4.0, 0.0009765625]
man_bits: int#
exp_bits: int#
normal_binades: int#
bias: int#
is_signed: bool = True#
prng_bits: int = 0#
saturation: SaturationMode = 2#
domain: Domain | None = None#
class mptorch.number.BlockFormat(elem, scale, block_size, *, block_rows=1, elem_max=None, nan_code=None, inf_code=None, scale_rounding=None)[source]#

A block format: narrow element codes that share one scale per block.

Covers OCP’s Microscaling (MX) formats and NVIDIA’s NVFP4, and the same construction over SuperFP elements and scales. A tensor is split into blocks of block_size consecutive elements along one axis, the packed axis. The functions that take a block format name that axis with axis. Each block stores one scale code and block_size element codes, and an element decodes to its elem value times its block’s scale. mptorch.quant.block_quantize() rounds a tensor to the format, mptorch.quant.block_pack() stores it in uint8 codes, and mptorch.quant.block_matmul() multiplies two packed operands.

The kind of scale decides whether the tensor has a second scale. The tensor scale is not an option of its own:

  • A power-of-two scale (scale.P == 1: E8M0, the MX presets) reaches from 2**-127 to 2**127, so the block scale is enough. The format has no tensor scale, and tensor_scale= raises.

  • A cast scale is a binaryK with a mantissa (NVFP4’s E4M3) or a superfp. It follows a block’s largest magnitude more closely, but over a much shorter range (E4M3: 2**-9 to 448). The format therefore also has one scale per tensor, a value of the carrier (float32 in binary32, float64 in binary64), which brings the tensor into that range. A block’s scale is then its scale code’s value times the tensor scale, one product in the carrier. The functions that quantize or pack take it as tensor_scale (its default is given below). tensor_scale=1.0 leaves the block scales alone.

  • scale=None stores the element codes unscaled.

A tensor scale without block scales is not available.

With block_rows > 1 a scale is shared by a tile of block_rows consecutive rows of block_size elements. The rows run along the axis before the packed one, never across a batch dimension. A square tile (block_rows == block_size) quantizes a matrix to the same values whichever of its two axes is packed, in every deterministic rounding mode. One packed weight can therefore serve a layer’s forward pass and its input gradient, which reads it transposed. dataclasses.replace(NVFP4, block_rows=16) is NVFP4 with 16 x 16 weight tiles.

Choosing the scale. The block scale is chosen from the block’s largest magnitude amax by scale_rounding (ScaleRounding). The defaults are:

  • A power-of-two scale (scale.P == 1, E8M0) is 2**(floor(log2(amax)) - emax), clamped to its codes, where emax = floor(log2(elem_max)). This is OCP MX’s rule.

  • A BinaryK scale with a mantissa (E4M3) is amax / (elem_max * tensor_scale) rounded to nearest even by the scale format’s cast. This is NVFP4’s rule.

  • A SuperFP scale rounds that ratio the same way, except where the block’s largest element would then saturate further than rounding to nearest allows. There it takes the next scale up.

A cast scale is clamped to its largest value and raised to its smallest positive one. The tensor scale defaults to max(|x|) / (elem_max * top_scale) over the whole tensor x.

Rounding the elements. Each element is divided by its scale and rounded, in the call’s rounding mode, by elem’s cast (binaryK or superfp) under SaturationMode.SAT_FINITE. It is then clamped to elem_max. elem’s own saturation is not read; its subnormals and prng_bits are.

Special values. An infinite input saturates to elem_max. A NaN input takes nan_code when the element format has one. Otherwise the block’s scale becomes the scale format’s NaN, and the whole block (every element of a 2D tile) decodes to NaN. With neither (scale=None and no nan_code) the NaN becomes elem_max. No value decodes to -0.0.

Superfp codes. A superfp code follows its format’s layout: the normal binades’ codes as in a binaryK, and below them, from code 1, the supernormal powers of two (see SuperFP). It spends no code on NaN or infinity unless nan_code or inf_code says so, as for a binaryK element. A superfp scale spends its all-ones code on NaN, like every cast scale.

Carriers. The block ops round in binary32, or in binary64 for a float64 tensor or carrier=torch.float64, and a format has to be one the call’s carrier holds: its element and a cast scale entirely, and a power-of-two scale’s codes within 2**-127 .. 2**127 in binary32 and 2**-1023 .. 2**1023 in binary64. Building a format checks binary64’s bounds, and a call that rounds in binary32 checks binary32’s, so an element with nine or ten exponent bits, or an E8M0-style scale biased past binary32’s range, is a format of float64 tensors.

Parameters:
  • elem (BinaryK | SuperFP | FixedPoint) – the element format. At most 16 bits, and a format that binary64 holds entirely (binary32 too, for a call that rounds in it).

  • scale (BinaryK | SuperFP | None) – the scale format, one byte. It is E8M0 (BinaryK(8, 1, bias=127, is_signed=False, subnormals=SubnormalsMode.EXTENDED_NORMALS)), a binaryK with a mantissa such as E4M3, or a superfp. The last two also bring a per-tensor scale. None stores the element codes unscaled.

  • block_size (int) – elements per block along the packed axis. A power of two in [2, 128], with elem_bits * block_size a multiple of 8.

  • block_rows (int) – rows per scale tile. A power of two in [1, 128], with block_rows * block_size <= 16384; 1 without a scale. Default: 1

  • elem_max (float | None) – the largest magnitude an element takes, a value of elem. Default: None, elem’s largest finite value under SAT_FINITE.

  • nan_code (int | None) – the magnitude code (sign bit clear) that the element format spends on NaN, above elem_max’s. Default: None

  • inf_code (int | None) – the magnitude code it spends on infinity. It is decoded but never produced. Default: None

  • scale_rounding (ScaleRounding | None) – how a block’s scale is chosen. OCP needs a power-of-two scale. A FOUR_OVER_SIX rule needs a cast scale. Default: None, the scale’s own rule: OCP for a power-of-two scale, NEAREST for a binaryK with a mantissa, SELECTIVE for a superfp. The default is resolved against the scale each time the format is built, so dataclasses.replace(NVFP4, scale=SuperFP(...)) takes the superfp’s rule.

These attributes are derived when the format is built and are read-only:

  • scale_rule: the ScaleRounding in effect (None without a scale). Formats compare by it, so leaving scale_rounding at its default and naming that default give equal formats.

  • elem_bits: the bits per element code, sign included (elem.K for a binaryK, elem.wl for a fixed point).

  • emax: floor(log2(elem_max)).

  • scale_max: the largest scale, the value of the code below the scale’s NaN (448 for E4M3, 2**127 for E8M0, 0 without a scale).

  • top_scale: the scale that the default tensor scale gives the tensor’s largest block. It is scale_max, or under a FOUR_OVER_SIX rule the largest scale v for which v * elem_max / 2**emax is also a scale (256 for E4M3, since 384 is one).

  • has_tensor_scale: whether the scale is cast (anything but E8M0-style), which brings the per-tensor scale.

  • bytes_per_block: the bytes of element codes in one row of a block.

  • is_square: block_rows == block_size.

Raises:
  • ValueError – for any of the following: sizes outside the ranges above; an element over 16 bits or a scale over 8; an element or cast scale that binary64 does not hold entirely; an elem_max that is not a value of elem; a nan_code or inf_code at or below elem_max’s code; a power-of-two scale that is signed or reaches past 2**-1023 or 2**1023 (the pack multiplies by its reciprocal); scale_rounding=OCP on a cast scale; a FOUR_OVER_SIX rule on a power-of-two scale; or any scale_rounding without a scale.

  • TypeError – if elem or scale is not a BinaryK or a SuperFP.

Parameters:

Example:

>>> from mptorch import MXFP8_E4M3, NVFP4
>>> MXFP8_E4M3.elem_max, MXFP8_E4M3.emax, MXFP8_E4M3.bytes_per_block
(448.0, 8, 32)
>>> NVFP4.scale_max, NVFP4.has_tensor_scale
(448.0, True)
>>> import dataclasses
>>> dataclasses.replace(NVFP4, block_rows=16).is_square
True
>>> from mptorch import E2M1, E8M0, BlockFormat, SuperFP
>>> sfp4 = BlockFormat(SuperFP(1, 2, 1, 1), E8M0, 32)  # 0 .. 6, down to 1/8
>>> sfp4.elem_bits, sfp4.elem_max, sfp4.emax
(4, 6.0, 2)
>>> BlockFormat(E2M1, SuperFP(3, 4, 2, 7), 16).scale_rule
<ScaleRounding.SELECTIVE: 3>
elem: BinaryK | SuperFP | FixedPoint#
scale: BinaryK | SuperFP | None#
block_size: int#
block_rows: int = 1#
elem_max: float | None = None#
nan_code: int | None = None#
inf_code: int | None = None#
scale_rounding: ScaleRounding | None = None#
scale_rule: ScaleRounding | None#
elem_bits: int#
emax: int#
scale_max: float#
top_scale: float#
has_tensor_scale: bool#
bytes_per_block: int#
is_square: bool#
class mptorch.number.FixedPoint(wl, fl, *, is_signed=True, symmetric=False, prng_bits=0)[source]#

A fixed-point format: wl bits, of which fl are fractional.

Defined as in Gupta et al., Deep Learning with Limited Numerical Precision (arXiv:1502.02551). Its values are the multiples of the step 2**-fl that a wl-bit integer holds: with n = wl - 1 magnitude bits in a signed format and n = wl in an unsigned one, the range is [-2**(n - fl), 2**(n - fl) - 2**-fl] in two’s complement, [-(2**(n - fl) - 2**-fl), 2**(n - fl) - 2**-fl] with symmetric, and [0, 2**(n - fl) - 2**-fl] unsigned. fl may be any integer: negative for a step coarser than 1, above wl for a format of pure fractions.

Every RoundMode applies, as for BinaryK. Below the step the two candidates are zero and 2**-fl, picked as SubnormalsMode describes. A result beyond the range saturates to its end, an infinite input included, because a fixed-point word has no code for an infinity, so there is no saturation field. A NaN passes through, the one zero is unsigned (no cast returns -0.0), and an unsigned format rounds every negative value to zero. The instance is frozen for the same reason BinaryK is.

Parameters:
  • wl (int) – word length, the sign bit included; at least 2 signed and 1 unsigned.

  • fl (int) – fractional length; the step between values is 2**-fl.

  • is_signed (bool) – whether the format has a sign bit. Default: True.

  • symmetric (bool) – drop the most negative code, so the range is symmetric about zero; signed formats only. Default: False.

  • prng_bits (int) – width of the random bits drawn by RoundMode.SR below the step, ignored under every other rounding mode. Default: 0.

Raises:

ValueError – for a wl too short, a symmetric unsigned format, a negative prng_bits, or what binary64 cannot simulate: more than 52 magnitude bits, with or without prng_bits, a largest value below its normals, or a range reaching its top binade. Each call checks the format against its own carrier (see FormatRangeWarning).

Example:

>>> from mptorch import FixedPoint
>>> f = FixedPoint(8, 4)  # steps of 1/16
>>> f.min_value, f.max_value, f.step
(-8.0, 7.9375, 0.0625)
>>> FixedPoint(8, 4, symmetric=True).min_value
-7.9375
wl: int#
fl: int#
is_signed: bool = True#
symmetric: bool = False#
prng_bits: int = 0#
property mag_bits: int#

wl less the sign bit, if there is one.

Type:

Magnitude bits

property step: float#

The step between neighbouring values, 2**-fl.

property max_value: float#

The largest value, (2**mag_bits - 1) * 2**-fl.

property min_value: float#

0 unsigned, -max_value symmetric, else one step below it.

Type:

The smallest value

exception mptorch.number.FormatRangeWarning[source]#

Warns that a format’s range outruns the float it is rounded or stored in.

Quantizing to such a format is partial: the cast is correct over the part of the format that the carrier holds, and some of the format’s values are never returned. The carrier is the operand’s: binary64 for a float64 tensor, and binary32 for float32, float16 and bfloat16, unless the call names binary64 with carrier=torch.float64.

The quantizers and GEMMs of mptorch.quant warn per call when a format does one of three things: reaches above the carrier’s largest finite value; spaces its values finer than the carrier’s smallest subnormal (\(2^{-149}\) in binary32, \(2^{-1074}\) in binary64); or has a smallest positive value below the floor the carrier gives it. That floor depends on how the cast finds the bottom of the format:

  • \(2^{-125}\) (\(2^{-1021}\)) for a BinaryK with SubnormalsMode.SUBNORMALS and for a SuperFP. Their casts place an input on the subnormal or supernormal grid using its exponent field, which all of the carrier’s subnormals share. A format reaching lower would have its bottom binade rounded onto the wrong grid.

  • \(2^{-126}\) (\(2^{-1022}\)), the carrier’s smallest normal, for a BinaryK with SubnormalsMode.NORMALS or SubnormalsMode.EXTENDED_NORMALS. Their casts find the bottom by comparing magnitudes and read no field. Two cases stop a binade earlier, at the first floor: P = 1 under NORMALS, and EXTENDED_NORMALS at the carrier’s full precision (P = 24, P = 53).

Formats and rounding (“What the carrier can hold”) derives both. BinaryK and SuperFP do not warn when they are built, because a format does not know which carrier it will meet. They raise only for what neither carrier can do.

The same warning is issued when the result is stored in a dtype narrower than the carrier (float16 or bfloat16 under binary32, and float32 as well under binary64) and the format’s range exceeds that dtype: above its largest finite value, or spaced finer than its smallest subnormal. The cast rounds in the carrier, and storing the result rounds a second time, onto the dtype’s grid. A value above the dtype’s range is stored as an infinity, whatever the format’s saturation mode.

This is a warning and not an error because such a format is still useful. A wide binaryK is a reasonable precision-only target, and its unreachable top is then intended. Each warning names the line that made the call, so the default filter reports it once per line, not once per training step.

Example:

>>> import warnings
>>> import torch
>>> from mptorch import BinaryK, FormatRangeWarning
>>> from mptorch.quant import Quant
>>> q = Quant(BinaryK(16, 8, bias=255))  # values down to 2**-261
>>> warnings.simplefilter("ignore", FormatRangeWarning)
>>> y = q(torch.ones(2))  # rounded in binary32, without the warning
mptorch.number.bfp(bits, block_size=16, *, block_rows=1)[source]#

Block floating point: bits-bit integer elements sharing a power-of-two scale.

The elements are FixedPoint(bits, bits - 2, symmetric=True): a sign and bits - 1 magnitude bits, one step of 2**-(bits - 2) from zero to the largest value, 2 - 2**-(bits - 2), so emax is 0 and a block’s E8M0 scale is 2**floor(log2(amax)), OCP’s rule. Any other fl gives the same block values and only moves emax; build the BlockFormat directly for one.

bfp(8, 32) is OCP’s MXINT8 but for one code: MXINT8’s elements are two’s complement, and -2 has no sign-magnitude code. The block GEMM takes element codes of up to 8 bits; bfp(9) to bfp(16) pack, unpack and quantize only.

Parameters:
  • bits (int) – the element’s word length, sign included, 2 to 16.

  • block_size (int) – elements per block, a power of two in [2, 128] with bits * block_size a multiple of 8.

  • block_rows (int) – rows per tile; block_rows > 1 shares a scale over a block_rows x block_size tile.

Return type:

BlockFormat

Quantizers#

See Quantizers.

mptorch.quant.binaryK_quantize(x, K, P, bias=None, prng_bits=0, is_signed=True, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, *, carrier=None)[source]#

Round every element of x to a binaryK floating-point format.

binaryK is the parameterized family of IEEE P3109, the draft Standard for Arithmetic Formats for Machine Learning (see mptorch.BinaryK). A format has K bits in total. P of them are precision (P - 1 stored mantissa bits plus the implicit one), and K - P are exponent bits (K - P + 1 when is_signed is false, because there is no sign bit). Pass bias explicitly for a format outside P3109. The layouts of the OCP 8-bit formats are K=8, P=4, bias=7 (E4M3) and K=8, P=3, bias=15 (E5M2).

The rounding happens in a carrier, the binary format the arithmetic runs in. It is binary64 for a float64 x. For float32, float16 and bfloat16 it is binary32, applied to their float32 value. Every call checks the format against what its carrier can hold: at most 24 bits of precision and seven exponent bits in binary32, and 53 and ten in binary64 (see Formats and rounding). The random bits of RoundMode.SR are drawn in the carrier too, so P - 1 + prng_bits is limited to its 23 or 52 mantissa bits.

A result narrower than its carrier (float16 or bfloat16, or float32 under binary64) is rounded a second time when it is stored, so the format is also checked against that dtype. The inputs are already values of the dtype, so only a result at an edge of the format’s range can land off its grid, and that case warns.

NaN inputs pass through. So do infinities, except under SaturationMode.SAT_FINITE and SAT_FINITE_EXTENDED (P3109’s SatFinite in its two domains), which clamp them to the largest finite value.

The function is not differentiable: rounding to a coarse grid has a zero derivative almost everywhere. On a tensor that requires grad under grad mode it raises and points at mptorch.quant.Quantizer, the straight-through estimator. mptorch.quant.Quant is the format-object spelling of the same call.

Parameters:
  • x (Tensor) – the tensor to round; float32, float64, float16 or bfloat16.

  • K (int) – the format’s width in bits.

  • P (int) – the format’s precision: P - 1 stored mantissa bits plus the implicit one.

  • bias (int | None) – the exponent bias. Default: None, which is P3109’s 2**(K - P - 1) signed and 2**(K - P) unsigned, one more than IEEE 754 gives the same exponent width.

  • prng_bits (int) – random bits RoundMode.SR draws below the target mantissa; ignored by every other mode. Default: 0

  • is_signed (bool) – whether the format has a sign bit. Default: True

  • rounding_mode (RoundMode) – how a value between two of the format’s is rounded. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – what a value past the largest finite one becomes. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – how the bottom of the range is filled in. Default: SubnormalsMode.SUBNORMALS

  • carrier (dtype | None) – torch.float64 rounds any x in binary64. A narrower x is widened first, and the result is narrowed back to its dtype with one rounding. torch.float32 names binary32. A float64 x refuses it, because the carrier is never narrower than the tensor. Default: None, x’s own carrier.

Returns:

a new tensor of x’s shape and dtype holding the rounded values.

Return type:

Tensor

Raises:
  • ValueError – if the carrier cannot hold the format (precision above the carrier’s, P - 1 + prng_bits above its mantissa bits, an exponent field past 30 bits, no finite normal value), or if carrier is a dtype that names no carrier or is narrower than x.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if x requires grad under grad mode.

Warns:

FormatRangeWarning – if the format’s range exceeds the carrier’s, or a result at an edge of the range lands off a narrower storage dtype’s grid. The format still quantizes correctly over the part that fits.

Example:

>>> x = torch.tensor([1.0, 1.1, 0.5])
>>> binaryK_quantize(x, K=8, P=4)
tensor([1.0000, 1.1250, 0.5000])
>>> binaryK_quantize(x.half(), K=8, P=4, carrier=torch.float64)
tensor([1.0000, 1.1250, 0.5000], dtype=torch.float16)
mptorch.quant.superfp_quantize(x, man_bits, exp_bits, normal_binades, bias, prng_bits=0, is_signed=True, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, *, carrier=None)[source]#

Round every element of x to a superfp (supernormal) format.

The format has man_bits stored mantissa bits and exp_bits exponent bits, but only the top normal_binades binades carry the mantissa. The codes of the lower binades become the zero and further powers of two below the normal region, the supernormals. Values below those flush to zero. There are no subnormals, and so no subnormals_mode. bias is required, because the format has no default rule for it. See mptorch.SuperFP.

Dtypes, the carrier, the storage check, prng_bits and differentiability are as for binaryK_quantize().

Parameters:
  • x (Tensor) – the tensor to round; float32, float64, float16 or bfloat16.

  • man_bits (int) – stored mantissa bits of a normal binade.

  • exp_bits (int) – exponent bits.

  • normal_binades (int) – how many of the top binades carry the mantissa; each lower binade holds one power of two.

  • bias (int) – the exponent bias.

  • prng_bits (int) – random bits RoundMode.SR draws below the target mantissa; ignored by every other mode. Default: 0

  • is_signed (bool) – whether the format has a sign bit. Default: True

  • rounding_mode (RoundMode) – how a value between two of the format’s is rounded. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – what a value past the largest finite one becomes. Default: SaturationMode.SAT_NONE

  • carrier (dtype | None) – as for binaryK_quantize(). Default: None, x’s own carrier.

Returns:

a new tensor of x’s shape and dtype holding the rounded values.

Return type:

Tensor

Raises:
  • ValueError – if the carrier cannot hold the format (precision above the carrier’s, man_bits + prng_bits above its mantissa bits, an over-wide exponent field, a normal_binades that leaves no supernormal code, no finite normal value), or if carrier is a dtype that names no carrier or is narrower than x.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if x requires grad under grad mode.

Warns:

FormatRangeWarning – if the format’s range outruns the carrier’s, or a result at an edge of the range lands off a narrower storage dtype’s grid.

Example:

>>> x = torch.tensor([1.1, 3.3, 0.05])
>>> superfp_quantize(x, man_bits=3, exp_bits=4, normal_binades=8, bias=7)
tensor([1.0000, 3.2500, 0.0625])

With bias=7 the eight normal binades start at 2, so 3.3 is rounded on a grid of step 0.25. 1.1 and 0.05 fall in the supernormal region and are rounded to a power of two.

mptorch.quant.fixedpoint_quantize(x, wl, fl, prng_bits=0, is_signed=True, symmetric=False, rounding_mode=RoundMode.RNE, *, carrier=None)[source]#

Round every element of x to a fixed-point format.

The format holds the multiples of the step 2**-fl that a wl-bit integer holds: [-2**(wl - 1 - fl), 2**(wl - 1 - fl) - 2**-fl] in two’s complement, one step narrower at the bottom with symmetric, and [0, 2**(wl - fl) - 2**-fl] unsigned (see mptorch.FixedPoint). A value past the range saturates to its end, an infinite one included, since a fixed-point word has no code for an infinity, so there is no saturation_mode. NaN inputs pass through.

Dtypes, the carrier, the storage check, prng_bits and differentiability are as for binaryK_quantize().

Parameters:
  • x (Tensor) – the tensor to round; float32, float64, float16 or bfloat16.

  • wl (int) – word length, the sign bit included.

  • fl (int) – fractional length; the step between values is 2**-fl.

  • prng_bits (int) – random bits RoundMode.SR draws below the step; ignored by every other mode. Default: 0

  • is_signed (bool) – whether the format has a sign bit. Default: True

  • symmetric (bool) – drop the most negative code, so the range is symmetric about zero; signed formats only. Default: False

  • rounding_mode (RoundMode) – how a value between two of the format’s is rounded. Default: RoundMode.RNE

  • carrier (dtype | None) – as for binaryK_quantize(). Default: None, x’s own carrier.

Returns:

a new tensor of x’s shape and dtype holding the rounded values.

Return type:

Tensor

Raises:
  • ValueError – if the carrier cannot hold the format (more magnitude bits than its mantissa has, with or without prng_bits, a largest value below its normals, or a range reaching its top binade), for a layout with no values (wl too short, a symmetric unsigned format, negative prng_bits), or if carrier is a dtype that names no carrier or is narrower than x.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if x requires grad under grad mode.

Warns:

FormatRangeWarning – if the format’s range outruns the carrier’s, or a result at an edge of the range lands off a narrower storage dtype’s grid.

Example:

>>> x = torch.tensor([1.1, 3.3, -9.0, 0.03])
>>> fixedpoint_quantize(x, wl=8, fl=4)
tensor([ 1.1250,  3.3125, -8.0000,  0.0000])

With fl=4 the step is 1/16: 1.1 and 3.3 round to the nearest sixteenth, -9.0 saturates to the bottom of the range, -8, and 0.03 is nearer to zero than to the step.

mptorch.quant.binaryK_quantize_(x, K, P, bias=None, prng_bits=0, is_signed=True, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, *, carrier=None)[source]#

Round every element of x to a binaryK format, in place.

This is the in-place spelling of binaryK_quantize(). It takes the same arguments, makes the same per-call format checks, and gives the same result element for element, written over x. That includes RoundMode.SR with the same seed, because each element’s random word is keyed on its index. No output is allocated, so peak memory is one tensor instead of two. The time is the same, because the kernel reads and writes the same bytes either way. Use it when the caller owns x: a weight quantized once at load, or an activation that nothing else will read.

binaryK_quantize() handles some inputs by copying them. This function refuses those inputs, because the kernel would write the copy and leave x unchanged:

  • a tensor that is not contiguous;

  • on CUDA, a view that does not start on a 16-byte boundary (x[1:]), which the kernel’s vector loads cannot address;

  • 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, which is its own carrier.

Parameters:
  • x (Tensor) – the tensor to round and overwrite; float32, float64, float16 or bfloat16, contiguous. The format and mode arguments between it and carrier are binaryK_quantize()’s.

  • carrier (dtype | None) – None or the carrier x already has (torch.float32 for float32, float16 and bfloat16, torch.float64 for float64). Default: None

  • K (int)

  • P (int)

  • bias (int | None)

  • prng_bits (int)

  • is_signed (bool)

  • rounding_mode (RoundMode)

  • saturation_mode (SaturationMode)

  • subnormals_mode (SubnormalsMode)

Returns:

x itself, holding the rounded values.

Return type:

Tensor

Raises:
  • ValueError – as for binaryK_quantize(), and if carrier is wider than x.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if x requires grad under grad mode, is not contiguous, or is a CUDA view off a 16-byte boundary.

Warns:

FormatRangeWarning – as for binaryK_quantize().

Example:

>>> x = torch.tensor([1.0, 1.1, 0.5])
>>> binaryK_quantize_(x, K=8, P=4) is x
True
>>> x
tensor([1.0000, 1.1250, 0.5000])
mptorch.quant.superfp_quantize_(x, man_bits, exp_bits, normal_binades, bias, prng_bits=0, is_signed=True, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, *, carrier=None)[source]#

Round every element of x to a superfp format, in place.

This is the in-place spelling of superfp_quantize(): the same arguments, checks and result, written over x, with no output allocation. Its purpose and the inputs it refuses are the same as for binaryK_quantize_(): a tensor that is not contiguous, a CUDA view off a 16-byte boundary, and a carrier wider than x.

Parameters:
  • x (Tensor) – the tensor to round and overwrite; float32, float64, float16 or bfloat16, contiguous. The format and mode arguments between it and carrier are superfp_quantize()’s.

  • carrier (dtype | None) – None or the carrier x already has. Default: None

  • man_bits (int)

  • exp_bits (int)

  • normal_binades (int)

  • bias (int)

  • prng_bits (int)

  • is_signed (bool)

  • rounding_mode (RoundMode)

  • saturation_mode (SaturationMode)

Returns:

x itself, holding the rounded values.

Return type:

Tensor

Raises:
  • ValueError – as for superfp_quantize(), and if carrier is wider than x.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if x requires grad under grad mode, is not contiguous, or is a CUDA view off a 16-byte boundary.

Warns:

FormatRangeWarning – as for superfp_quantize().

Example:

>>> x = torch.tensor([1.1, 3.3, 0.05])
>>> superfp_quantize_(x, man_bits=3, exp_bits=4, normal_binades=8, bias=7)
tensor([1.0000, 3.2500, 0.0625])
>>> x
tensor([1.0000, 3.2500, 0.0625])
mptorch.quant.fixedpoint_quantize_(x, wl, fl, prng_bits=0, is_signed=True, symmetric=False, rounding_mode=RoundMode.RNE, *, carrier=None)[source]#

Round every element of x to a fixed-point format, in place.

The in-place spelling of fixedpoint_quantize(): the same arguments, checks and result, written over x, with no output allocation. What it is for and what it refuses (a tensor that is not contiguous, a CUDA view off a 16-byte boundary, a carrier wider than x) are as for binaryK_quantize_().

Parameters:
  • x (Tensor) – the tensor to round and overwrite; float32, float64, float16 or bfloat16, contiguous. The format and mode arguments between it and carrier are fixedpoint_quantize()’s.

  • carrier (dtype | None) – None or the carrier x already has. Default: None

  • wl (int)

  • fl (int)

  • prng_bits (int)

  • is_signed (bool)

  • symmetric (bool)

  • rounding_mode (RoundMode)

Returns:

x itself, holding the rounded values.

Return type:

Tensor

Raises:
Warns:

FormatRangeWarning – as for fixedpoint_quantize().

Example:

>>> x = torch.tensor([1.1, 3.3, -9.0, 0.03])
>>> fixedpoint_quantize_(x, wl=8, fl=4)
tensor([ 1.1250,  3.3125, -8.0000,  0.0000])
>>> x
tensor([ 1.1250,  3.3125, -8.0000,  0.0000])
class mptorch.quant.Quant(fmt, rounding=RoundMode.RNE, *, carrier=None, inplace=False)[source]#

A format plus a rounding mode, as a callable Tensor -> Tensor.

Calling it rounds every element of a tensor to the format, in the carrier, and returns a tensor of the same dtype and shape. Every *_quant slot of a QAffineFormats or QMatmulFormats takes one, and a straight-through mptorch.quant.Quantizer or a QAT observer wraps one. The call is bound at construction, so each call costs only the op. The class is frozen, so a Quant can be a dictionary key and a memoization key, like the mac objects.

Parameters:
  • fmt (Number) – the format to round to: a mptorch.BinaryK, a mptorch.SuperFP, a mptorch.FixedPoint, or a mptorch.BlockFormat. A block format’s blocks run along the last axis; use BlockQuant for another axis or a tensor scale.

  • rounding (RoundMode) – the rounding mode. Default: RoundMode.RNE

  • carrier (dtype | None) – the float arithmetic the cast rounds in, as the argument of the same name of mptorch.quant.binaryK_quantize(). None rounds in the tensor’s own default carrier: binary32 for float16, bfloat16 and float32 tensors, and binary64 for float64 ones. torch.float64 rounds in binary64 whatever the tensor. torch.float32 rounds in binary32 and refuses a float64 tensor. Default: None

  • inplace (bool) – round the tensor in place and return it, instead of allocating a result. This goes through mptorch.quant.binaryK_quantize_(), mptorch.quant.superfp_quantize_() or mptorch.quant.fixedpoint_quantize_(). Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a *_quant slot of a layer’s formats, because a layer’s input belongs to the graph of whatever produced it. The call refuses what the in-place ops refuse: a tensor that is not contiguous, a CUDA view off a 16-byte boundary, and a carrier wider than the tensor. Default: False

Raises:
  • TypeError – for a format with no elementwise quantizer, or a carrier that is not a torch.dtype.

  • ValueError – for a carrier dtype that names no carrier.

Example:

>>> import torch
>>> from mptorch import BinaryK, RoundMode, SuperFP
>>> from mptorch.quant import QAffineFormats, Quant
>>> q = Quant(BinaryK(8, 4))
>>> q(torch.tensor([1.0, 0.3, 0.7]))
tensor([1.0000, 0.3125, 0.6875])
>>> formats = QAffineFormats()
>>> formats.input_quant = Quant(SuperFP(3, 4, 8, 7), RoundMode.SR)
fmt: Number#
rounding: RoundMode = 0#
carrier: dtype | None = None#
inplace: bool = False#
class mptorch.quant.Quantizer(forward_quant=None, backward_quant=None)[source]#

Quantize in the forward pass, quantize (or pass through) in the backward.

This is the module form of the straight-through estimator. The output is forward_quant(x), and the gradient that reaches x is backward_quant(grad). A direction whose quantizer is None is left alone. Because it is an nn.Module, it can sit in any *_quant slot of a QAffineFormats or QMatmulFormats and is registered with the parent model. That matters as soon as the quantizer carries state of its own.

Parameters:
  • forward_quant (Number | Callable | None) – the forward pass’s quantizer. A format is wrapped in a mptorch.quant.Quant with round-to-nearest-even. Any Tensor -> Tensor callable is used as it is. None leaves the forward pass alone. Default: None

  • backward_quant (Number | Callable | None) – the backward’s quantizer, in the same forms. Default: None

Shape:
  • Input: any shape.

  • Output: the same shape and dtype.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QAffineFormats, Quantizer
>>> act = Quantizer(BinaryK(8, 4), BinaryK(8, 5))   # narrow fwd, wider bwd
>>> x = torch.tensor([0.3], requires_grad=True)
>>> y = act(x)
>>> y
tensor([0.3125], grad_fn=<_StraightThroughBackward>)
>>> y.backward()
>>> x.grad
tensor([1.])
>>> formats = QAffineFormats()
>>> formats.input_quant = act   # a module, so it is in the state_dict

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(x)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

Block quantizers#

mptorch.quant.block_quantize(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#

Round x to a block format along axis and return the decoded values.

This is block_pack() and block_unpack() fused, with no packed intermediate. It is the fake quantizer that a *_quant slot of a layer’s formats takes, and mptorch.quant.BlockQuant is its value spelling. The arguments are those of block_pack(), and the result has x’s shape, dtype and layout. The function is not differentiable: wrap it in mptorch.quant.Quantizer for a straight-through gradient.

Example:

>>> import torch
>>> from mptorch import NVFP4
>>> from mptorch.quant import block_quantize
>>> block_quantize(torch.tensor([[0.3, -1.0, 2.5, 6.0] * 4]), NVFP4)[0, :4]
tensor([ 0.5000, -1.0000,  2.0000,  6.0000])
Return type:

Tensor

Parameters:
mptorch.quant.block_quantize_(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#

block_quantize(), written over x in place; returns x.

Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a *_quant slot, because a layer’s input belongs to the graph of whatever produced it. x must have no overlapping elements. A tensor of rank 4 or more must be able to fold its leading dimensions as a view with axis moved last. The out-of-place op has neither restriction. The result equals that of block_quantize() word for word.

Example:

>>> import torch
>>> from mptorch import MXFP8_E4M3
>>> from mptorch.quant import block_quantize_
>>> w = torch.tensor([[1.0, 0.1, -3.3, 100.0]])
>>> block_quantize_(w, MXFP8_E4M3) is w
True
Return type:

Tensor

Parameters:
mptorch.quant.block_pack(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#

Round x to a block format along axis and store it packed.

Each run of fmt.block_size consecutive elements along axis shares one scale. For a 2D format the run also spans fmt.block_rows rows along the axis before it. The scale is chosen from the block’s values as mptorch.BlockFormat describes. Each element is then divided by the scale and rounded to the element format in rounding. The result stores the codes, which take a quarter to an eighth of float32’s bytes; BlockPacked describes the layout. A transposed view is packed without a copy, and so is any axis, because the kernel reads x through its strides.

Under RoundMode.SR an element’s random bits are keyed on its index in the packed orientation (the tensor with axis moved last). block_quantize() with the same generator state therefore draws the same bits.

Parameters:
  • x (Tensor) – float32, float64, float16 or bfloat16, of any rank.

  • fmt (BlockFormat) – the format.

  • axis (int) – the axis to pack along. Default: -1

  • rounding (RoundMode) – the elements’ rounding mode. The scale is always chosen by the format’s rule. Default: RoundMode.RNE

  • tensor_scale (float | None) – the per-tensor scale of a format whose block scale has a mantissa (NVFP4). None takes max(|x|) / (elem_max * top_scale), which reads x once more and, on a GPU, synchronizes with it. Default: None

  • carrier (dtype | None) – the arithmetic the rounding runs in: torch.float64 packs any x in binary64, widening a narrower one first (the default tensor scale is then a float64 quotient), and torch.float32 names binary32, which a float64 x refuses. Default: None, x’s own: binary64 for float64, binary32 otherwise.

Returns:

the codes, the scales and what describes them.

Return type:

BlockPacked

Raises:
  • ValueError – for a format the carrier does not hold (mptorch.number.check_block_carrier()), carrier=torch.float32 on a float64 x, or a tensor_scale given to a format without one.

  • RuntimeError – on a tensor that requires grad under grad mode.

Example:

>>> import torch
>>> from mptorch import MXFP4_E2M1
>>> from mptorch.quant import block_pack
>>> p = block_pack(torch.tensor([[0.3, -1.0, 2.5, 6.0] * 8]), MXFP4_E2M1)
>>> p.data.shape, p.scales.tolist()
(torch.Size([1, 16]), [[127]])
>>> p.unpack()[0, :4]
tensor([ 0.5000, -1.0000,  2.0000,  6.0000])
mptorch.quant.block_unpack(p, *, dtype=None, carrier=None)[source]#

Decode a BlockPacked into a tensor of its logical shape.

Each element is its code’s value times its block’s scale (times the tensor scale), one product in the carrier, stored in dtype. The carrier is the one p was packed in, or binary64 when dtype is float64 or carrier=torch.float64. A result narrower than its carrier rounds that product a second time where the dtype does not hold it (once: a binary64 product reaches a narrower dtype through narrow_float64), and mptorch.FormatRangeWarning reports it. block_unpack(block_pack(x, fmt, axis)) equals block_quantize(x, fmt, axis) element for element, under the same generator state.

Parameters:
  • p (BlockPacked) – the packed tensor.

  • dtype (dtype | None) – float32, float64, float16 or bfloat16. Default: None, the dtype p was packed from.

  • carrier (dtype | None) – torch.float64 decodes in binary64; torch.float32 refuses a p packed in binary64 and a float64 dtype. Default: None, p’s carrier, or binary64 for a float64 dtype.

Returns:

the decoded values, of shape p.shape (a view with the packed axis moved back into place).

Return type:

Tensor

Example:

>>> import torch
>>> from mptorch import MXFP8_E4M3
>>> from mptorch.quant import block_pack, block_unpack
>>> x = torch.tensor([[1.0, 0.1, -3.3, 100.0]])
>>> block_unpack(block_pack(x, MXFP8_E4M3, axis=0))  # a block per element
tensor([[ 1.0000,  0.1016, -3.2500, 96.0000]])
class mptorch.quant.BlockPacked(data, scales, fmt, shape, axis, tensor_scale, dtype, carrier=None)[source]#

A tensor stored in a mptorch.BlockFormat: uint8 codes and scales.

This is what block_pack() returns. Its fields are:

  • data: the element codes of the logical tensor with its packed axis moved last, [..., rows, row_bytes]. The leading dimensions are folded into one, and a 1D tensor is stored as one row.

  • scales: the scale codes, [..., row_tiles, n_blocks]. A format without a scale has no columns.

  • shape, axis and dtype: the logical tensor’s shape, the axis it was packed along, and the dtype it was packed from, which unpack() returns.

  • tensor_scale: the per-tensor scale it was packed with (1 for a format without one).

  • carrier: the carrier it was packed in, torch.float32 (binary32) or torch.float64 (binary64). unpack() and block_matmul() decode it in that carrier or a wider one. It defaults to dtype’s: binary64 for float64, binary32 otherwise.

mT is the logical transpose of the last two dimensions. It reads the same codes the other way: nothing is copied, and only shape and axis change. This lets block_matmul() read one packed weight in both a layer’s forward pass and its input gradient.

Example:

>>> import torch
>>> from mptorch import MXFP8_E4M3
>>> from mptorch.quant import block_pack
>>> w = torch.randn(64, 256)
>>> p = block_pack(w, MXFP8_E4M3)
>>> p.data.shape, p.scales.shape, p.nbytes
(torch.Size([64, 256]), torch.Size([64, 8]), 16896)
>>> p.mT.shape, p.mT.axis, p.mT.data.data_ptr() == p.data.data_ptr()
((256, 64), 0, True)
Parameters:
data#
scales#
fmt#
shape#
axis#
tensor_scale#
dtype#
carrier#
property device: device#

The device the codes live on.

property nbytes: int#

Bytes of codes and scales together.

property cols: int#

The length of the packed axis. The rows of data round it up to whole blocks.

property mT: BlockPacked#

The logical transpose of the last two dimensions, without a copy.

to(device)[source]#

The same codes on device.

Return type:

BlockPacked

Parameters:

device (device | str)

unpack(dtype=None)[source]#

block_unpack() of this tensor.

Return type:

Tensor

Parameters:

dtype (dtype | None)

class mptorch.quant.BlockQuant(fmt, rounding=RoundMode.RNE, *, axis=-1, tensor_scale=None, carrier=None)[source]#

A block format plus a rounding mode: a fake quantizer, and a packer.

Calling it is mptorch.quant.block_quantize() along axis. It returns the decoded values, with the tensor’s shape and dtype. That is what a *_quant slot of a layer’s formats or a mptorch.quant.Quantizer takes.

pack() is mptorch.quant.block_pack() instead. It returns the codes themselves, which mptorch.quant.block_gemm_formats() and mptorch.quant.block_matmul_formats() multiply without decoding them first. Use BlockQuant(fmt, axis=1).pack as a QLinear’s weight_quant to pack its weight once instead of in every hook. The packing is memoized on the tensor, its version counter, its device and its dtype. It is therefore redone after each optimizer step (which writes the weight in place) and after the module is moved or converted (.to(), .cuda(), .half(), which keep the parameter and its version), and not otherwise. The memo does not see a write that the version counter does not see (one made through .data).

Parameters:
  • fmt (BlockFormat) – the format.

  • rounding (RoundMode) – the elements’ rounding mode. Default: RoundMode.RNE

  • axis (int) – the axis the blocks run along. Default: -1

  • tensor_scale (float | None) – a static per-tensor scale, for a format that has one (NVFP4). None derives it per call. Default: None

  • carrier (dtype | None) – as for mptorch.quant.block_quantize(). Default: None

Example:

>>> import torch
>>> from mptorch import MXFP8_E4M3
>>> from mptorch.quant import BlockQuant
>>> q = BlockQuant(MXFP8_E4M3)
>>> q(torch.tensor([[1.0, 0.1, -3.3, 100.0]]))
tensor([[ 1.0000,  0.1016, -3.2500, 96.0000]])
>>> w = torch.randn(16, 64)
>>> q.pack(w, axis=1) is q.pack(w, axis=1)
True
fmt: BlockFormat#
rounding: RoundMode = 0#
axis: int = -1#
tensor_scale: float | None = None#
carrier: dtype | None = None#
pack(x, axis=None)[source]#

mptorch.quant.block_pack() of x along axis, memoized on x, its version, its device and its dtype. axis defaults to this quantizer’s.

Return type:

BlockPacked

Parameters:
pack_fresh(x, axis)[source]#

mptorch.quant.block_pack() of x along axis, not memoized. Use it for an activation or a gradient, which is a new tensor on every call.

Return type:

BlockPacked

Parameters:

Kernels#

See Quantized numerical kernels.

The arithmetic of a dot product#

The value types a quantized computation is spelled with: Quant for an elementwise step, SplitMac and FusedMac for a reduction, and Palette for a set of formats selected per output element.

Every step of a quantized layer is one of exactly two things, and only one of them needs an arithmetic policy:

  • an elementwise step (a weight, activation or gradient quantizer) computes in the carrier and rounds the result to a format. That is a format plus a rounding mode, and it yields a callable: Quant.

  • a reduction step is the only place the internal arithmetic is simulated, so it is the only place a multiply/accumulate policy means anything. That is the GEMM: SplitMac and FusedMac, named after the two policies the kernels implement (common/gemm_policy.h).

The vocabulary is therefore two value types that do not grow with the number of ops, rather than one formats class per layer kind, each with its own slots and its own bookkeeping of which slots are in use.

Two things follow from spelling a reduction as a value:

  • accumulate_quant and fma_quant stop being booleans. SplitMac(mul=f, acc=None) is the full-precision-sum case, so the state where an accumulate format is present but ignored cannot be expressed.

  • the palette stops being a separate op family. Any format slot takes a Number or a sequence of them, and a sequence anywhere selects the _mixed op and requires a prec_idx; op choice is a table keyed on (family, mac kind, is palette) rather than eight function names. A SplitMac whose two formats are of different families selects one of the cross-family ops, which take one format per slot.

Resolution to a _GemmSpec happens once and is memoized on the value: the classes are frozen dataclasses, so they hash by value, and spec_for_mac() caches on them. Re-deriving a format’s defaults and carrier checks costs 2.3 to 6.4 microseconds per call, more than the rest of the Python call path, so an object API that resolved per call would be slower than the flat wrappers it sits over.

class mptorch.quant.mac.Quant(fmt, rounding=RoundMode.RNE, *, carrier=None, inplace=False)[source]#

A format plus a rounding mode, as a callable Tensor -> Tensor.

Calling it rounds every element of a tensor to the format, in the carrier, and returns a tensor of the same dtype and shape. Every *_quant slot of a QAffineFormats or QMatmulFormats takes one, and a straight-through mptorch.quant.Quantizer or a QAT observer wraps one. The call is bound at construction, so each call costs only the op. The class is frozen, so a Quant can be a dictionary key and a memoization key, like the mac objects.

Parameters:
  • fmt (Number) – the format to round to: a mptorch.BinaryK, a mptorch.SuperFP, a mptorch.FixedPoint, or a mptorch.BlockFormat. A block format’s blocks run along the last axis; use BlockQuant for another axis or a tensor scale.

  • rounding (RoundMode) – the rounding mode. Default: RoundMode.RNE

  • carrier (dtype | None) – the float arithmetic the cast rounds in, as the argument of the same name of mptorch.quant.binaryK_quantize(). None rounds in the tensor’s own default carrier: binary32 for float16, bfloat16 and float32 tensors, and binary64 for float64 ones. torch.float64 rounds in binary64 whatever the tensor. torch.float32 rounds in binary32 and refuses a float64 tensor. Default: None

  • inplace (bool) – round the tensor in place and return it, instead of allocating a result. This goes through mptorch.quant.binaryK_quantize_(), mptorch.quant.superfp_quantize_() or mptorch.quant.fixedpoint_quantize_(). Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a *_quant slot of a layer’s formats, because a layer’s input belongs to the graph of whatever produced it. The call refuses what the in-place ops refuse: a tensor that is not contiguous, a CUDA view off a 16-byte boundary, and a carrier wider than the tensor. Default: False

Raises:
  • TypeError – for a format with no elementwise quantizer, or a carrier that is not a torch.dtype.

  • ValueError – for a carrier dtype that names no carrier.

Example:

>>> import torch
>>> from mptorch import BinaryK, RoundMode, SuperFP
>>> from mptorch.quant import QAffineFormats, Quant
>>> q = Quant(BinaryK(8, 4))
>>> q(torch.tensor([1.0, 0.3, 0.7]))
tensor([1.0000, 0.3125, 0.6875])
>>> formats = QAffineFormats()
>>> formats.input_quant = Quant(SuperFP(3, 4, 8, 7), RoundMode.SR)
class mptorch.quant.mac.Palette(formats)[source]#

Up to eight formats of one family, selected per output element.

A GEMM slot holds a palette when the format varies across the output. The _mixed ops take the palette’s widths as a table, and a prec_idx map picks one entry per output element. A plain sequence of formats works anywhere a Palette does and is converted to one; the class exists for the validation. Every entry must be of the same family. Some fields are shared across the palette by the schema: sign, stochastic bits, saturation and subnormals. Entries that disagree on one of them are rejected here, with an error naming the first such entry. The palette does not silently take entry 0’s value.

Parameters:

formats (Number | Sequence[Number] | Palette) – one format, a sequence of up to MAX_PALETTE formats, or another palette (copied).

Raises:
  • ValueError – for an empty sequence, more than eight formats, or entries that disagree on a shared field.

  • TypeError – for a format family no GEMM kernel takes, or a mix of families.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import Palette, SplitMac, qmm
>>> palette = Palette([BinaryK(8, 4), BinaryK(8, 5), BinaryK(16, 11)])
>>> len(palette)
3
>>> prec_idx = torch.randint(3, (4, 3))
>>> qmm(torch.randn(4, 8), torch.randn(8, 3), SplitMac(palette, palette),
...     prec_idx=prec_idx).shape
torch.Size([4, 3])
class mptorch.quant.mac.SplitMac(mul, acc=None, *, rounding=RoundMode.RNE, accumulate_algorithm=AccumulateAlgorithm.NAIVE, carrier=None, block_size=None, outer=None, carrier_rounding=RoundMode.RNE)[source]#

Quantize the product and the running sum separately: two roundings.

Each step of a dot product computes s = round_acc(s + round_mul(a * b)) in the carrier. The product is rounded to the mul format and the new partial sum to the acc format. mul and acc are each a format or a sequence of formats. A sequence is a palette; it selects the _mixed op and requires a prec_idx at the call. acc alone may also be None, which leaves the running sum in the carrier’s full precision. The two may be of different families, a BinaryK multiply with a SuperFP accumulate or the reverse, as long as each slot holds one format: the cross-family ops (mptorch.quant.binaryK_superfp_matmul(), mptorch.quant.superfp_binaryK_matmul()) have no palette variant.

rounding is one mode for both halves. The kernels take the rounding mode as a template parameter, because a runtime switch inside the accumulate step cost 1.2 to 2.3 times the kernel time, and a mode per format would square the number of kernel instantiations. Saturation, subnormals and the stochastic-rounding width are per format, and are set on the format objects.

Parameters:
  • mul (Number | Sequence[Number] | Palette) – the multiply format, or a palette of them.

  • acc (Number | Sequence[Number] | Palette | None) – the accumulate format, or a palette of them; None leaves the running sum unrounded. Default: None

  • rounding (RoundMode) – rounding mode of both halves. Default: RoundMode.RNE

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed. NAIVE is the step above, in order. KAHAN carries a compensation term next to the sum, in the acc format. BLOCK runs the step above over blocks of block_size products and adds each block’s sum to a total with a third rounding, outer. TREE sums each block’s products pairwise, rounding every pair’s sum to acc, and adds the block’s root to the total in the same way. mptorch.AccumulateAlgorithm states each precisely. KAHAN, BLOCK and TREE run in both carriers; a palette in any slot raises. Default: AccumulateAlgorithm.NAIVE

  • carrier (dtype | None) – the float arithmetic that both halves and everything between them are computed in, as the argument of the same name of mptorch.quant.binaryK_matmul(). None takes the operands’ carrier (binary64 for float64, binary32 for the rest). torch.float64 widens narrower operands to binary64 and narrows the result back to their dtype. torch.float32 refuses float64 operands. Every call checks the formats against that carrier. Default: None

  • block_size (int | None) – products per block. BLOCK requires one, which must divide 16 or be a multiple of 16. TREE takes a power of two in [2, 256] and defaults to 16. NAIVE and KAHAN take none. Default: None

  • outer (Number | None) – the format, of the accumulate format’s family (the multiply’s when acc is None), that BLOCK and TREE round the total to after each block is added. None leaves the total in the carrier’s precision, as acc=None does for the sum. When given, the result holds this format’s values. Default: None

  • carrier_rounding (RoundMode) – how the carrier rounds the product and the sum before the formats do. RoundMode.RNE is the carrier’s nearest multiply and add. RoundMode.RO rounds both to odd instead, so each format rounds the exact product and the exact sum (see Dot-product arithmetic, “What the carrier rounds”), for formats narrow enough: P at most 22 under RNE and RNA, 23 under the directed modes and RO, and P + prng_bits at most 23 under SR, in binary32 (51, 52 and 52 in binary64); a call outside those raises. RO is implemented for NAIVE, one format per slot and one family, on CPU and CUDA tensors. With acc=None only the product is rounded to odd, since no format rounds the sum after it. Default: RoundMode.RNE

Raises:
  • ValueError – if mul is None, if both slots are palettes of different lengths, if mul and acc are of different families and either is a palette, if carrier names no carrier, if block_size or outer does not fit the algorithm, or if carrier_rounding is neither RNE nor RO or is RO with something it does not implement.

  • TypeError – if outer is of another family than the accumulate format or not a single format, or carrier is not a torch.dtype.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import SplitMac, qmm
>>> binary8p4 = BinaryK(8, 4)
>>> mac = SplitMac(binary8p4, BinaryK(16, 11))   # Binary8p4 products, 11-bit sums
>>> qmm(torch.randn(4, 8), torch.randn(8, 3), mac).shape
torch.Size([4, 3])
>>> exact_sum = SplitMac(binary8p4, None)   # products rounded, sum exact
>>> from mptorch import AccumulateAlgorithm
>>> blocked = SplitMac(binary8p4, binary8p4, block_size=8, outer=BinaryK(16, 11),
...                    accumulate_algorithm=AccumulateAlgorithm.BLOCK)
>>> qmm(torch.randn(4, 64), torch.randn(64, 3), blocked).shape
torch.Size([4, 3])
>>> from mptorch import SuperFP
>>> cross = SplitMac(binary8p4, SuperFP(3, 4, 8, 7))   # binaryK products, superfp sums
>>> qmm(torch.randn(4, 8), torch.randn(8, 3), cross).shape
torch.Size([4, 3])
class mptorch.quant.mac.FusedMac(fma, *, rounding=RoundMode.RNE, accumulate_algorithm=AccumulateAlgorithm.NAIVE, carrier=None, block_size=None, outer=None, carrier_rounding=RoundMode.RNE)[source]#

One hardware-style fused multiply-add per K-step, rounded once.

Each step computes s = round_fma(s + a * b) with the product exact, so there is one rounding per step where SplitMac has two. The carrier’s FMA rounds s + a * b to nearest before the format does, unless carrier_rounding=RoundMode.RO. fma is a format, a palette, or None. None gives an unrounded fused step: the carrier’s own FMA, in order. It has no format for prec_idx to select, so it never selects a _mixed op.

Parameters:
  • fma (Number | Sequence[Number] | Palette | None) – the format each fused step is rounded to, a palette of them, or None.

  • rounding (RoundMode) – rounding mode of the fused step. Default: RoundMode.RNE

  • accumulate_algorithm (AccumulateAlgorithm) – as for SplitMac, with the fused step in place of the split one. TREE raises, because a fused multiply-add has no product term to sum pairwise. Default: AccumulateAlgorithm.NAIVE

  • carrier (dtype | None) – as for SplitMac. Default: None

  • block_size (int | None) – as for SplitMac. Default: None

  • outer (Number | None) – as for SplitMac. With fma=None it may be of either family. Default: None

  • carrier_rounding (RoundMode) – as for SplitMac, for the fused step’s one carrier rounding. RoundMode.RO needs a format (fma=None raises). Default: RoundMode.RNE

Raises:
  • ValueError – if carrier names no carrier, a palette is invalid, block_size or outer does not fit the algorithm, or carrier_rounding does not fit the mac.

  • TypeError – if carrier is not a torch.dtype, or outer is of another family or not a single format.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import FusedMac, qmm
>>> qmm(torch.randn(4, 8), torch.randn(8, 3), FusedMac(BinaryK(8, 4))).shape
torch.Size([4, 3])
>>> unrounded = FusedMac(None)   # unrounded FMAs in the carrier
class mptorch.quant.mac.BlockQuant(fmt, rounding=RoundMode.RNE, *, axis=-1, tensor_scale=None, carrier=None)[source]#

A block format plus a rounding mode: a fake quantizer, and a packer.

Calling it is mptorch.quant.block_quantize() along axis. It returns the decoded values, with the tensor’s shape and dtype. That is what a *_quant slot of a layer’s formats or a mptorch.quant.Quantizer takes.

pack() is mptorch.quant.block_pack() instead. It returns the codes themselves, which mptorch.quant.block_gemm_formats() and mptorch.quant.block_matmul_formats() multiply without decoding them first. Use BlockQuant(fmt, axis=1).pack as a QLinear’s weight_quant to pack its weight once instead of in every hook. The packing is memoized on the tensor, its version counter, its device and its dtype. It is therefore redone after each optimizer step (which writes the weight in place) and after the module is moved or converted (.to(), .cuda(), .half(), which keep the parameter and its version), and not otherwise. The memo does not see a write that the version counter does not see (one made through .data).

Parameters:
  • fmt (BlockFormat) – the format.

  • rounding (RoundMode) – the elements’ rounding mode. Default: RoundMode.RNE

  • axis (int) – the axis the blocks run along. Default: -1

  • tensor_scale (float | None) – a static per-tensor scale, for a format that has one (NVFP4). None derives it per call. Default: None

  • carrier (dtype | None) – as for mptorch.quant.block_quantize(). Default: None

Example:

>>> import torch
>>> from mptorch import MXFP8_E4M3
>>> from mptorch.quant import BlockQuant
>>> q = BlockQuant(MXFP8_E4M3)
>>> q(torch.tensor([[1.0, 0.1, -3.3, 100.0]]))
tensor([[ 1.0000,  0.1016, -3.2500, 96.0000]])
>>> w = torch.randn(16, 64)
>>> q.pack(w, axis=1) is q.pack(w, axis=1)
True
pack(x, axis=None)[source]#

mptorch.quant.block_pack() of x along axis, memoized on x, its version, its device and its dtype. axis defaults to this quantizer’s.

Return type:

BlockPacked

Parameters:
pack_fresh(x, axis)[source]#

mptorch.quant.block_pack() of x along axis, not memoized. Use it for an activation or a gradient, which is a new tensor on every call.

Return type:

BlockPacked

Parameters:
class mptorch.quant.mac.BlockMac(a, b=None, acc=None, *, fused=False, rounding=RoundMode.RNE, accumulate_algorithm=AccumulateAlgorithm.NAIVE, carrier=None, block_size=None, outer=None, tensor_scale_epilogue=False)[source]#

The block GEMM: two block-format operands and the arithmetic of their product.

a and b are the formats that the left and right operands are packed in. Each is a mptorch.BlockFormat (packed to nearest even) or a BlockQuant (which specifies the rounding and a tensor scale). b defaults to a.

The product decodes both operands in the carrier and sums their products as mptorch.quant.block_matmul() describes. In a split mac, each product is rounded to the carrier and the sum to acc. With fused=True, each fused multiply-add is rounded to acc. acc=None leaves the sum in the carrier. The accumulate algorithms are those of SplitMac.

mptorch.quant.qmatmul() and mptorch.quant.QMatmul accept a BlockMac (mptorch.quant.block_matmul_formats() builds their formats). They also accept a bare BlockFormat, which means BlockMac(fmt).

Parameters:
  • a (BlockFormat | BlockQuant) – the left operand’s format.

  • b (BlockFormat | BlockQuant | None) – the right operand’s. Default: None, a’s.

  • acc (BinaryK | None) – the accumulate format. Default: None

  • fused (bool) – a fused multiply-add per step. Default: False

  • rounding (RoundMode) – the sum’s rounding mode. Default: RoundMode.RNE

  • accumulate_algorithm (AccumulateAlgorithm) – as for SplitMac (TREE needs fused=False). Default: AccumulateAlgorithm.NAIVE

  • carrier (dtype | None) – torch.float64 packs the operands and multiplies them in binary64, whatever their dtype (an operand BlockQuant that names a carrier of its own keeps it). Default: None, the operands’: binary64 for float64 tensors, binary32 otherwise.

  • block_size (int | None) – as for SplitMac. Default: None

  • outer (BinaryK | None) – as for SplitMac. Default: None

  • tensor_scale_epilogue (bool) – apply the operands’ per-tensor scales once, to the result, as NVIDIA’s NVFP4 GEMMs do, instead of in each decoded element (mptorch.quant.block_matmul()). Default: False

Example:

>>> import torch
>>> from mptorch import BinaryK, MXFP8_E4M3, MXFP4_E2M1
>>> from mptorch.quant import BlockMac, qmm
>>> mac = BlockMac(MXFP8_E4M3, MXFP4_E2M1, BinaryK(16, 11))
>>> qmm(torch.randn(4, 64), torch.randn(64, 8), mac).shape
torch.Size([4, 8])

Matrix products#

The differentiable matmul entry points: qmm, qbmm and qmatmul.

These are the functions to reach for. The eight *_matmul* wrappers in mptorch.quant.ops are the schema-faithful tier, one function per op with every schema argument spelled out and no autograd; these sit above them, taking a format object instead of twenty integers and carrying a gradient.

formats accepts, in increasing order of specificity:

  • None: plain torch.matmul, which is what an A/B against unquantized arithmetic wants;

  • a Number (BinaryK(8, 4)): shorthand for SplitMac(mul=fmt, acc=fmt), the common case where one format is used for both halves of the dot product, and for a BlockFormat, BlockMac(fmt): both operands packed in it, the sum in binary32;

  • a BlockMac: two packed block-format operands and the arithmetic of their product (mptorch.quant.block_matmul_formats());

  • a SplitMac / FusedMac: the dot-product arithmetic, with a palette in any slot selecting the per-output-element op and requiring prec_idx, and a carrier choosing the float arithmetic it is computed in (binary64 for any operands with torch.float64, never narrower than theirs);

  • a QMatmulFormats: per-pass arithmetic and operand quantizers, that is, everything the layer can vary.

The first three are resolved (and memoized) into the fourth, so there is one implementation and one thing to test.

mptorch.quant.matmul.qmm(a, b, formats=None, *, prec_idx=None)[source]#

qmatmul() restricted to two matrices, as torch.mm is.

Parameters:
Returns:

the [M, N] product.

Return type:

Tensor

Raises:

ValueError – if either operand is not 2D, plus qmatmul()’s.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import qmm
>>> qmm(torch.randn(4, 8), torch.randn(8, 3), BinaryK(8, 4)).shape
torch.Size([4, 3])
mptorch.quant.matmul.qbmm(a, b, formats=None, *, prec_idx=None)[source]#

qmatmul() restricted to two batches of matrices, as torch.bmm is.

There is no broadcasting: both batch dimensions must be equal. torch.bmm makes this check and qmatmul does not.

Parameters:
Returns:

the [B, M, N] batch of products.

Return type:

Tensor

Raises:

ValueError – if either operand is not 3D or the batch sizes differ, plus qmatmul()’s.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import FusedMac, qbmm
>>> a, b = torch.randn(2, 4, 8), torch.randn(2, 8, 3)
>>> qbmm(a, b, FusedMac(BinaryK(8, 4))).shape
torch.Size([2, 4, 3])
mptorch.quant.matmul.qmatmul(a, b, formats=None, *, prec_idx=None)[source]#

torch.matmul’s contract, computed in the arithmetic formats names.

It accepts everything torch.matmul accepts: 1D promotion on either operand, and leading dimensions of any rank broadcast against each other. It is differentiable in both operands, and each gradient is computed in the arithmetic of its own hook. Float64 operands are computed in binary64. The others are computed in binary32, unless a mac’s carrier asks for binary64. In both cases each pass checks the formats against its carrier and warns (mptorch.FormatRangeWarning) about what the carrier cannot hold.

Two 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 into M, giving one large GEMM instead of a batch of small ones.

Both are bit-identical to the batched spelling, stochastic rounding included, because each output element’s random stream is keyed on its index into the output.

Parameters:
  • a (Tensor) – the left operand, 1D or higher.

  • b (Tensor) – the right operand, 1D or higher, of the same dtype.

  • formats (Any) – the arithmetic. The module docstring says what each spelling means. Default: None (plain torch.matmul)

  • prec_idx (Tensor | None) – an integer map of the forward pass’s output shape ([M, N], [M, 1] or [1, N], optionally batched) that selects a palette entry per output element. It is required by a palette format and by nothing else. It is the forward’s map. A palette that also has to differentiate needs one map per pass; use the agrad_prec_idx and bgrad_prec_idx arguments of mptorch.quant.matmul_formats() for those. Default: None

Returns:

a @ b in the operands’ dtype, with torch.matmul’s output shape.

Return type:

Tensor

Raises:
  • ValueError – for a palette without prec_idx, a prec_idx with no palette, or a carrier narrower than the operands.

  • TypeError – for a formats value of another type.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import SplitMac, qmatmul
>>> a, b = torch.randn(5, 2, 4, 8), torch.randn(8, 3)
>>> qmatmul(a, b, BinaryK(8, 4)).shape
torch.Size([5, 2, 4, 3])
>>> qmatmul(a, b, SplitMac(BinaryK(8, 4), acc=None)).shape
torch.Size([5, 2, 4, 3])
mptorch.quant.matmul.as_matmul_formats(formats, prec_idx=None)[source]#

Normalize whatever a caller passed as formats to a QMatmulFormats.

The four spellings listed in the module docstring are told apart here and nowhere else, so qmatmul() and mptorch.quant.QMatmul accept exactly the same values.

Parameters:
  • formats (Any) – the arithmetic, in any of the accepted spellings.

  • prec_idx (Tensor | None) – the forward’s palette map, for a SplitMac/FusedMac holding a palette. Default: None

Returns:

formats itself if it already was one, an empty QMatmulFormats() for None, or the memoized one for a mac.

Return type:

QMatmulFormats

Raises:
class mptorch.quant.QMatmulFormats(a_quant=None, b_quant=None, agrad_quant=None, bgrad_quant=None, fwd_math=None, bwd_agrad_math=None, bwd_bgrad_math=None, recompute_a=None, recompute_b=None)[source]#

Quantizers and custom math for a quantized matmul.

QMatmul and mptorch.quant.qmatmul() read this container. Its slots mirror those of QAffineFormats, renamed for an op whose two operands play the same role: a/b instead of input/weight, and one gradient quantizer per operand, because the two gradient GEMMs may need different formats. Every slot is optional, and None means plain PyTorch. A QMatmulFormats() with nothing set computes torch.matmul and its ordinary gradients.

There is no output_quant, on purpose. Rounding the result of the op is an elementwise step, so the caller applies a quantizer for it; it is not a slot on every op’s formats.

The class inherits from nn.Module, which registers a stateful quantizer (a QAT observer) in the parent model’s state_dict.

The recompute_* flags are QAffineFormats’ for the two operands: keep a (b) raw for backward and quantize it again there, instead of keeping a quantized copy. Both default to keeping the copy, since a matmul’s operands are activations and whether anything else keeps one alive depends on the model.

Parameters:
  • a_quant (Callable | None) – applied to a in the forward. Default: None

  • b_quant (Callable | None) – applied to b in the forward. Default: None

  • agrad_quant (Callable | None) – applied to the output gradient before a’s gradient GEMM. Default: None

  • bgrad_quant (Callable | None) – applied to the output gradient before b’s gradient GEMM. Default: None

  • fwd_math (Callable | None) – fwd_math(q_a, q_b) -> a @ b. Default: None

  • bwd_agrad_math (Callable | None) – bwd_agrad_math(q_grad, q_b) -> grad @ b^T. Default: None

  • bwd_bgrad_math (Callable | None) – bwd_bgrad_math(q_grad, q_a) -> a^T @ grad. Default: None

  • recompute_a (bool | None) – keep a raw for backward and run a_quant on it again there. None keeps the copy. Set it where something else keeps a alive, as attention’s softmax keeps the probabilities that multiply V. True runs any callable again, as for QAffineFormats. Default: None

  • recompute_b (bool | None) – the same for b and b_quant. Default: None

Example:

>>> from mptorch import BinaryK
>>> from mptorch.quant import QMatmul, Quant, SplitMac, matmul_formats
>>> formats = matmul_formats(SplitMac(BinaryK(8, 4), BinaryK(16, 11)))
>>> formats.a_quant = Quant(BinaryK(8, 4))
>>> formats.b_quant = Quant(BinaryK(8, 4))
>>> attn = QMatmul(formats)

Initialize internal Module state, shared by both nn.Module and ScriptModule.

class mptorch.quant.QMatmul(formats=None)[source]#

torch.matmul with the arithmetic of one QMatmulFormats.

This is the module form of mptorch.quant.qmatmul(). Like QLinear, it is a module because its formats are one: a QMatmulFormats is an nn.Module, so a quantizer that carries state (a QAT observer) is registered in the parent model’s state_dict when the matmul is held as a submodule. A quantized attention block calls two of these per head. For backward it keeps quantized copies of both operands, unless the formats’ recompute_a / recompute_b say to keep an operand raw and quantize it again there (worth it for the softmax probabilities, which softmax keeps alive anyway).

Parameters:

formats (None or Number or SplitMac or FusedMac or QMatmulFormats) – everything mptorch.quant.qmatmul() accepts, converted once here by mptorch.quant.matmul.as_matmul_formats(). Default: None (plain torch.matmul)

Shape:
  • Input: a and b in any shapes torch.matmul accepts.

  • Output: torch.matmul’s output shape.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QMatmul, SplitMac
>>> mm = QMatmul(SplitMac(BinaryK(8, 4), BinaryK(16, 11)))
>>> mm(torch.randn(2, 4, 8), torch.randn(8, 3)).shape
torch.Size([2, 4, 3])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(a, b)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:
mptorch.quant.matmul_formats(mac, *, prec_idx=None, agrad_prec_idx=None, bgrad_prec_idx=None)[source]#

Build a QMatmulFormats whose three passes run in mac’s arithmetic.

The forward product a @ b, a’s gradient grad @ b^T and b’s gradient a^T @ grad each run through the GEMM op that mac resolves to.

A palette in any of mac’s slots selects the per-output-element op, which needs one prec_idx map per pass. The maps are bound into the hooks here instead of being passed through every call. A gradient pass whose map is missing raises when it is reached; it does not fall back to unquantized arithmetic.

Like the four *_gemm_formats factories, this sets only the math hooks. The caller adds elementwise operand quantization (a_quant, b_quant, agrad_quant, bgrad_quant) separately.

Parameters:
  • mac (SplitMac | FusedMac) – the dot-product arithmetic, resolved once through mptorch.quant.mac.spec_for_mac().

  • prec_idx (Tensor | None) – integer map selecting a palette entry per element of the forward’s output, shaped like a @ b ([M, N], [M, 1] or [1, N], optionally batched). Required by, and only by, a palette mac. Default: None

  • agrad_prec_idx (Tensor | None) – the map for a’s gradient, shaped like grad @ b^T. Default: None

  • bgrad_prec_idx (Tensor | None) – the map for b’s gradient, shaped like a^T @ grad. Default: None

Returns:

with fwd_math, bwd_agrad_math and bwd_bgrad_math set and every *_quant slot left None.

Return type:

QMatmulFormats

Raises:

ValueError – if mac holds a palette and prec_idx is None, or if a map is given for a mac with no palette to select from.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import Palette, QMatmul, SplitMac, matmul_formats
>>> palette = Palette([BinaryK(8, 4), BinaryK(8, 5)])
>>> prec_idx = torch.zeros(4, 3, dtype=torch.int64)
>>> formats = matmul_formats(SplitMac(palette, palette), prec_idx=prec_idx)
>>> QMatmul(formats)(torch.randn(4, 8), torch.randn(8, 3)).shape
torch.Size([4, 3])
mptorch.quant.block_matmul(a, b, *, acc=None, fused=False, rounding=RoundMode.RNE, accumulate_algorithm=AccumulateAlgorithm.NAIVE, block_size=None, outer=None, carrier=None, tensor_scale_epilogue=False)[source]#

Multiply two block-format tensors: a @ b of their logical values.

a is logically [..., M, K] and b is [..., K, N]. The kernel decodes each element as it loads it (its value times its block’s scale, as block_unpack() would) and multiplies in the carrier: binary64 when carrier=torch.float64 or either operand was packed in binary64 (from a float64 tensor, or with that carrier), and binary32 otherwise. A split mac (fused=False) rounds each product to the carrier and the running sum to acc. A fused mac rounds each fused multiply-add to acc. acc=None leaves the sum in the carrier.

Each operand is read along K. It may be packed along its K (a along its last axis, b along its second-to-last) or along its other dimension, which the kernel reads transposed. One packed weight therefore serves both x @ w.T and g @ w; BlockPacked.mT is the transpose, without a copy. The two operands may have different formats. Leading dimensions must be equal, or absent on one side. The function is not differentiable: see mptorch.quant.qmatmul() with a mptorch.quant.BlockMac.

A format with a per-tensor scale (NVFP4’s E4M3, or a superfp scale) decodes each element as its value times its block’s scale times the tensor scale, inside the loop. tensor_scale_epilogue=True does what NVIDIA’s NVFP4 GEMMs do instead. The loop sees the elements times their block scales only, and the result is multiplied once by the product of the two tensor scales, rounded to the carrier. The two agree in exact arithmetic and round differently. In the second, the accumulate format sees products that the tensor scales have not scaled, so it needs their range.

Parameters:
  • a (BlockPacked) – the left operand.

  • b (BlockPacked) – the right operand.

  • acc (BinaryK | None) – the accumulate format. Default: None

  • fused (bool) – one rounding per step (a fused multiply-add) instead of two. Default: False

  • rounding (RoundMode) – the rounding mode of the sum. Default: RoundMode.RNE

  • accumulate_algorithm (AccumulateAlgorithm) – as for mptorch.quant.SplitMac. Default: AccumulateAlgorithm.NAIVE

  • block_size (int | None) – BLOCK’s and TREE’s block size. Default: None

  • outer (BinaryK | None) – BLOCK’s and TREE’s outer format. Default: None

  • carrier (dtype | None) – torch.float64 multiplies in binary64; torch.float32 refuses an operand packed in binary64. Default: None, the operands’ carrier.

  • tensor_scale_epilogue (bool) – apply the operands’ tensor scales to the result instead of in the decode. It has no effect on formats without a tensor scale (E8M0). Default: False

Returns:

[..., M, N], float32 in binary32 and float64 in binary64.

Return type:

Tensor

Example:

>>> import torch
>>> from mptorch import BinaryK, MXFP8_E4M3
>>> from mptorch.quant import block_matmul, block_pack
>>> x, w = torch.randn(4, 64), torch.randn(16, 64)
>>> y = block_matmul(block_pack(x, MXFP8_E4M3), block_pack(w, MXFP8_E4M3).mT,
...                  acc=BinaryK(16, 11))
>>> y.shape
torch.Size([4, 16])
mptorch.quant.block_matmul_formats(mac, *, agrad_mac=None, bgrad_mac=None)[source]#

Build a QMatmulFormats whose three passes are block GEMMs.

Each pass packs its operands along the dimension it sums over:

  • The forward product a @ b packs a along its last dimension and b along its second-to-last (their K), in mac’s two formats.

  • a’s gradient grad @ b^T packs grad along its last dimension and b along its last.

  • b’s gradient a^T @ grad packs a along its second-to-last dimension and grad along its second-to-last.

A gradient pass takes the formats of the slots it fills from agrad_mac / bgrad_mac, which default to mac. An operand whose format has square tiles is packed once, by the a_quant / b_quant slot that this function sets for it. The gradient passes read that packing through mptorch.quant.BlockPacked.mT. Each pass’s result is in the carrier (float32, or float64 in binary64), stored in the operands’ dtype.

Parameters:
  • mac (BlockMac) – the forward’s operand formats and arithmetic.

  • agrad_mac (BlockMac | None) – a’s gradient’s. Default: None

  • bgrad_mac (BlockMac | None) – b’s gradient’s. Default: None

Returns:

the three math hooks, and a_quant / b_quant for square-tiled operands.

Return type:

QMatmulFormats

Example:

>>> import torch
>>> from mptorch import BinaryK, MXFP8_E4M3
>>> from mptorch.quant import BlockMac, QMatmul, block_matmul_formats
>>> layer = QMatmul(block_matmul_formats(BlockMac(MXFP8_E4M3, acc=BinaryK(16, 11))))
>>> layer(torch.randn(4, 64), torch.randn(64, 8)).shape
torch.Size([4, 8])

The schema tier#

One function per kernel, with every schema argument spelled out and no autograd. See Calling the kernels for when to use these instead of qmatmul.

mptorch.quant.binaryK_matmul(a, b, *, trans_a=False, trans_b=False, mul_K, mul_P, mul_bias=None, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_K=None, acc_P=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, acc_saturation_mode=None, acc_subnormals_mode=None, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Quantized GEMM with a split multiply-accumulate in binaryK formats.

Computes op(a) @ op(b), where op(x) = x.T when the corresponding trans_* flag is set, and op(x) = x otherwise. This is not the same as quantizing a and b and then calling torch.matmul. It quantizes the arithmetic of each dot product. Every partial product is rounded to the binaryK format given by mul_K/mul_P. When accumulate_quant is true, the running sum is rounded to the format given by acc_K/acc_P after every accumulation step. With accumulate_quant=False the running sum stays at the carrier’s precision and only the multiply is quantized.

Everything the formats do not round (a product or a sum before its rounding) is computed in a carrier, and so are the roundings. The carrier is binary64 for float64 operands and binary32 for float32, float16 and bfloat16. Every call checks both formats against that carrier. The result holds the accumulate format’s values, so that format is also checked against a result dtype narrower than the carrier, as in binaryK_quantize().

a and b follow torch.matmul’s operand rules: 1D operands are promoted (and their dimension is dropped from the result), leading dimensions broadcast against each other, and trans_a/trans_b apply to the last two dimensions. Three cases need no copy:

  • A shared operand is read at stride 0 instead of being expanded.

  • An operand that is the transpose of a contiguous tensor flips the kernel’s flag instead of being copied.

  • [..., M, K] @ [K, N] folds its batch into M as a view.

The two shapes that a quantized attention block uses are covered by these. Under RoundMode.SR each output element’s random stream is keyed on its index into the [batch, M, N] result, so the folded and the batched spellings are bit-identical.

This function resolves the format on every call. A caller that keeps one format across many calls should use the factories of mptorch.quant.gemm, which resolve it once per layer. mptorch.quant.qmatmul() is the differentiable entry point.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_K (int) – width in bits of the multiply format.

  • mul_P (int) – precision of the multiply format.

  • mul_bias (int | None) – exponent bias of the multiply format. Default: None, P3109’s 2**(K - P - 1) signed and 2**(K - P) unsigned.

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding, as binaryK_quantize()’s prng_bits. Default: 0

  • accumulate_quant (bool) – whether the running sum is rounded to the accumulate format after every step. Default: True

  • acc_K (int | None) – width of the accumulate format. Default: None, mul_K.

  • acc_P (int | None) – precision of the accumulate format. Default: None, mul_P.

  • acc_bias (int | None) – exponent bias of the accumulate format. Default: None, P3109’s for acc_K/acc_P.

  • acc_is_signed (bool | None) – whether the accumulate format has a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed. NAIVE is the step above, in order. KAHAN carries a compensation term next to the sum, rounded to the accumulate format. BLOCK runs the step above over blocks of block_size products and adds each block’s sum to a total, which the outer format rounds. TREE sums each block’s products pairwise, rounding every pair’s sum to the accumulate format, and adds the block’s root to the total in the same way. mptorch.AccumulateAlgorithm states each precisely. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of both formats. There is one mode per op, because the kernel is instantiated on it. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – the multiply format’s bottom of range. Default: SubnormalsMode.SUBNORMALS

  • acc_saturation_mode (SaturationMode | None) – the accumulate format’s overflow behavior. Default: None, saturation_mode.

  • acc_subnormals_mode (SubnormalsMode | None) – the accumulate format’s bottom of range. Default: None, subnormals_mode.

  • block_size (int | None) – products per block. BLOCK requires one, which must divide 16 or be a multiple of 16 (the kernels count in slabs of 16 steps). TREE takes a power of two in [2, 256] and defaults to 16. NAIVE and KAHAN take none. Default: None

  • outer_K (int | None) – width of the outer format. This is the rounding that BLOCK and TREE apply to the total after each block is added. None (with outer_P) leaves the total in the carrier’s precision. When given, it is the format whose values the result holds, and the one checked against a narrower result dtype. Default: None

  • outer_P (int | None) – precision of the outer format; given together with outer_K. Default: None

  • outer_bias (int | None) – exponent bias of the outer format. Default: None, P3109’s for outer_K/outer_P.

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, the accumulate format’s.

  • outer_prng_bits (int) – random bits RoundMode.SR draws for the outer rounding. Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, the accumulate format’s.

  • outer_subnormals_mode (SubnormalsMode | None) – the outer format’s bottom of range. Default: None, the accumulate format’s.

  • carrier (dtype | None) – as for binaryK_quantize(). torch.float64 widens narrower operands to binary64 and narrows the result back to their dtype with one rounding. torch.float32 refuses float64 operands. Default: None, the operands’ own carrier.

  • carrier_rounding (RoundMode) – how the carrier rounds each product and sum before the formats do. RoundMode.RNE is the carrier’s nearest multiply and add, which the directed modes can then round to the wrong neighbour. RoundMode.RO rounds them to odd, so each format rounds the exact product and the exact sum, for formats with P at most 22 under RNE/RNA, 23 under the directed modes and RO, and P + prng_bits at most 23 under SR in binary32 (51, 52 and 52 in binary64); a call outside those raises. RO runs the custom_matmul_*_odd ops: NAIVE only, on CPU and CUDA tensors. With accumulate_quant=False only the product is rounded to odd. See Dot-product arithmetic, “What the carrier rounds”. Default: RoundMode.RNE

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold a format (as for binaryK_quantize()), if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode (use mptorch.quant.qmatmul()).

Warns:

FormatRangeWarning – if a format’s range exceeds the carrier’s, or the accumulate format’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> binaryK_matmul(a, a, mul_K=8, mul_P=4)
tensor([[ 7., 10.],
        [15., 22.]])
>>> binaryK_matmul(a, a, mul_K=8, mul_P=3)
tensor([[ 7., 10.],
        [16., 24.]])

With three stored mantissa bits (P=4) every product and sum is exact. With two (P=3) the sums 15 and 22 are rounded to 16 and 24.

mptorch.quant.superfp_matmul(a, b, *, trans_a=False, trans_b=False, mul_man_bits, mul_exp_bits, mul_normal_binades, mul_bias, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_man_bits=None, acc_exp_bits=None, acc_normal_binades=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, acc_saturation_mode=None, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Quantized GEMM with a split multiply-accumulate in superfp formats.

The superfp analog of binaryK_matmul(). Every partial product is rounded to the superfp format given by mul_man_bits, mul_exp_bits, mul_normal_binades and mul_bias. When accumulate_quant is true, the running sum is rounded to the acc_* format after every step. binaryK_matmul() describes the general contract: torch.matmul’s operand rules, the transpose flags, the carrier, the storage check and the per-call resolution. superfp_quantize() describes the format.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_man_bits (int) – stored mantissa bits of the multiply format.

  • mul_exp_bits (int) – exponent bits of the multiply format.

  • mul_normal_binades (int) – binades of the multiply format that carry the mantissa.

  • mul_bias (int) – exponent bias of the multiply format.

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding. Default: 0

  • accumulate_quant (bool) – whether the running sum is rounded to the accumulate format after every step. Default: True

  • acc_man_bits (int | None) – the accumulate format’s mantissa bits. Default: None, mul_man_bits.

  • acc_exp_bits (int | None) – the accumulate format’s exponent bits. Default: None, mul_exp_bits.

  • acc_normal_binades (int | None) – the accumulate format’s normal binades. Default: None, mul_normal_binades.

  • acc_bias (int | None) – the accumulate format’s exponent bias. Default: None, mul_bias.

  • acc_is_signed (bool | None) – whether the accumulate format has a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – as for binaryK_matmul(). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of both formats. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • acc_saturation_mode (SaturationMode | None) – the accumulate format’s overflow behavior. Default: None, saturation_mode.

  • block_size (int | None) – as for binaryK_matmul(). Default: None

  • outer_man_bits (int | None) – mantissa bits of the outer format, the rounding BLOCK and TREE apply to the total after each block is folded in (binaryK_matmul()’s outer_K). The four widths are given together, or none of them, which leaves the total in the carrier’s precision. Default: None

  • outer_exp_bits (int | None) – exponent bits of the outer format. Default: None

  • outer_normal_binades (int | None) – normal binades of the outer format. Default: None

  • outer_bias (int | None) – exponent bias of the outer format. Default: None

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, the accumulate format’s.

  • outer_prng_bits (int) – random bits RoundMode.SR draws for the outer rounding. Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, the accumulate format’s.

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

  • carrier_rounding (RoundMode) – as for binaryK_matmul(). Default: RoundMode.RNE

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold a format (as for superfp_quantize()), if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if a format’s range outruns the carrier’s, or the accumulate format’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> superfp_matmul(
...     a, a, mul_man_bits=3, mul_exp_bits=4, mul_normal_binades=8, mul_bias=7
... )
tensor([[ 7., 10.],
        [15., 22.]])
mptorch.quant.binaryK_matmul_fma(a, b, *, trans_a=False, trans_b=False, fma_K, fma_P, fma_bias=None, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Quantized GEMM with a fused multiply-add in a binaryK format.

The fused analog of binaryK_matmul(). Every dot-product step is a single hardware-style fused multiply-add: s + a * b, with s the running sum, rounded once. The multiply and the accumulate are not rounded separately. A real FMA unit has one output rounding, so there is a single fma_K/fma_P format instead of a mul_*/acc_* pair. With fma_quant=False the fused step runs at the carrier’s own precision, like accumulate_quant=False in binaryK_matmul().

a and b follow torch.matmul’s operand rules. The carrier, the storage check and the per-call resolution are as for binaryK_matmul().

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • fma_K (int) – width in bits of the fused step’s format.

  • fma_P (int) – precision of the fused step’s format.

  • fma_bias (int | None) – its exponent bias. Default: None, P3109’s 2**(K - P - 1) signed and 2**(K - P) unsigned.

  • fma_is_signed (bool) – whether the format has a sign bit. Default: True

  • fma_quant (bool) – whether the fused step is rounded to the format at all. Default: True

  • fma_prng_bits (int) – random bits RoundMode.SR draws for the fused rounding, as binaryK_quantize()’s prng_bits. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – as for binaryK_matmul(), with the fused step in place of the split one, except TREE, which raises: a fused multiply-add has no product term to sum pairwise. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the fused step’s rounding. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – the format’s bottom of range. Default: SubnormalsMode.SUBNORMALS

  • block_size (int | None) – as for binaryK_matmul(). Default: None

  • outer_K (int | None) – as for binaryK_matmul(). Default: None

  • outer_P (int | None) – as for binaryK_matmul(). Default: None

  • outer_bias (int | None) – as for binaryK_matmul(). Default: None

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, fma_is_signed.

  • outer_prng_bits (int) – as for binaryK_matmul(). Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, saturation_mode.

  • outer_subnormals_mode (SubnormalsMode | None) – the outer format’s bottom of range. Default: None, subnormals_mode.

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

  • carrier_rounding (RoundMode) – as for binaryK_matmul(). The fused step needs fma_quant=True. Default: RoundMode.RNE

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold the format, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if the format’s range outruns the carrier’s or reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> binaryK_matmul_fma(a, a, fma_K=8, fma_P=3)
tensor([[ 7., 10.],
        [16., 24.]])
mptorch.quant.superfp_matmul_fma(a, b, *, trans_a=False, trans_b=False, fma_man_bits, fma_exp_bits, fma_normal_binades, fma_bias, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Quantized GEMM with a fused multiply-add in a superfp format.

The superfp analog of binaryK_matmul_fma(). Every dot-product step is one fused multiply-add, rounded once to the format given by fma_man_bits, fma_exp_bits, fma_normal_binades and fma_bias (see superfp_quantize()). With fma_quant=False it is left at the carrier’s precision. a and b follow torch.matmul’s operand rules. The carrier, the storage check and the per-call resolution are as for binaryK_matmul().

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • fma_man_bits (int) – stored mantissa bits of the fused step’s format.

  • fma_exp_bits (int) – its exponent bits.

  • fma_normal_binades (int) – its binades that carry the mantissa.

  • fma_bias (int) – its exponent bias.

  • fma_is_signed (bool) – whether the format has a sign bit. Default: True

  • fma_quant (bool) – whether the fused step is rounded to the format at all. Default: True

  • fma_prng_bits (int) – random bits RoundMode.SR draws for the fused rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – as for binaryK_matmul(), with the fused step in place of the split one, except TREE, which raises: a fused multiply-add has no product term to sum pairwise. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the fused step’s rounding. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • block_size (int | None) – as for binaryK_matmul(). Default: None

  • outer_man_bits (int | None) – mantissa bits of the outer format, the rounding BLOCK and TREE apply to the total after each block is folded in (binaryK_matmul()’s outer_K). The four widths are given together, or none of them, which leaves the total in the carrier’s precision. Default: None

  • outer_exp_bits (int | None) – exponent bits of the outer format. Default: None

  • outer_normal_binades (int | None) – normal binades of the outer format. Default: None

  • outer_bias (int | None) – exponent bias of the outer format. Default: None

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, fma_is_signed.

  • outer_prng_bits (int) – random bits RoundMode.SR draws for the outer rounding. Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, saturation_mode.

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

  • carrier_rounding (RoundMode) – as for binaryK_matmul(). The fused step needs fma_quant=True. Default: RoundMode.RNE

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold the format, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if the format’s range outruns the carrier’s or reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> superfp_matmul_fma(
...     a, a, fma_man_bits=2, fma_exp_bits=4, fma_normal_binades=8, fma_bias=7
... )
tensor([[ 7., 10.],
        [16., 24.]])
mptorch.quant.binaryK_matmul_mixed(a, b, prec_idx, *, trans_a=False, trans_b=False, mul_K, mul_P, mul_bias=None, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_K=None, acc_P=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, acc_saturation_mode=None, acc_subnormals_mode=None, carrier=None)[source]#

Quantized GEMM whose binaryK format varies per output element.

The palette analog of binaryK_matmul(). The arithmetic is the same split one, a rounded multiply followed by a rounded accumulate. The difference is that the binaryK format of each output element’s dot product is chosen by prec_idx from a palette of up to 8 formats.

mul_K and mul_P are per-entry sequences, and their common length is the palette size n. Each of the other palette arguments may be a scalar (used for every entry), an n-length sequence, or None. None defaults per entry as in binaryK_matmul(): acc_* fall back to the mul_* entry, and a bias to P3109’s. Every entry is checked against the call’s carrier, and every accumulate entry against a narrower result dtype.

prec_idx selects a palette entry per output element. Its shape must be the GEMM’s output shape [M, N] (dense), [M, 1] (per row) or [1, N] (per column). It may have a leading batch dimension of B (one map per batch element) or 1. The batch is never folded into M here, because the map is indexed by output element.

Any integer dtype and layout is accepted. A map that is already int32, contiguous and on a’s device is passed through unchanged. Any other map is narrowed and packed on every call. On CUDA the bounds check reads the map’s extremes back to the host, so it is memoized on the map tensor’s identity and version. Keep one map and reuse it across calls; a map rebuilt per call is re-checked per call.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • prec_idx (Tensor) – the palette index of each output element, in [0, n).

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_K (Sequence[int]) – width in bits of each entry’s multiply format.

  • mul_P (Sequence[int]) – precision of each entry’s multiply format.

  • mul_bias (int | Sequence[int] | None) – exponent bias of each entry’s multiply format. Default: None, P3109’s per entry.

  • mul_is_signed (bool) – whether the multiply formats have a sign bit; shared by the palette. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding; shared by the palette. Default: 0

  • accumulate_quant (bool) – whether the running sum is rounded to the accumulate format after every step. Default: True

  • acc_K (int | Sequence[int] | None) – width of each entry’s accumulate format. Default: None, the mul_K entry.

  • acc_P (int | Sequence[int] | None) – precision of each entry’s accumulate format. Default: None, the mul_P entry.

  • acc_bias (int | Sequence[int] | None) – exponent bias of each entry’s accumulate format. Default: None, P3109’s per entry.

  • acc_is_signed (bool | None) – whether the accumulate formats have a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed; the palette ops implement NAIVE only. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of every format. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply formats’ overflow behavior. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – the multiply formats’ bottom of range. Default: SubnormalsMode.SUBNORMALS

  • acc_saturation_mode (SaturationMode | None) – the accumulate formats’ overflow behavior. Default: None, saturation_mode.

  • acc_subnormals_mode (SubnormalsMode | None) – the accumulate formats’ bottom of range. Default: None, subnormals_mode.

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if the palette is empty or a palette argument’s length is not n, if a carrier cannot hold an entry, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if n is above 8, prec_idx has the wrong shape or an entry outside [0, n), the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if an entry’s range outruns the carrier’s, or an accumulate entry’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> prec_idx = torch.tensor([[0, 0], [0, 1]])
>>> binaryK_matmul_mixed(a, a, prec_idx, mul_K=[8, 8], mul_P=[4, 3])
tensor([[ 7., 10.],
        [15., 24.]])

Three output elements use the P=4 entry and are exact. The last uses the P=3 entry, whose two mantissa bits round the sum 22 to 24.

mptorch.quant.superfp_matmul_mixed(a, b, prec_idx, *, trans_a=False, trans_b=False, mul_man_bits, mul_exp_bits, mul_normal_binades, mul_bias, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_man_bits=None, acc_exp_bits=None, acc_normal_binades=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, acc_saturation_mode=None, carrier=None)[source]#

Quantized GEMM whose superfp format varies per output element.

The superfp analog of binaryK_matmul_mixed(), which describes the palette, prec_idx and the carrier contract. mul_man_bits and mul_exp_bits are per-entry sequences, and their common length is the palette size n. mul_normal_binades, mul_bias and every acc_* may be a scalar or an n-length sequence. An acc_* may also be None, which falls back to the corresponding mul_* entry.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • prec_idx (Tensor) – the palette index of each output element, in [0, n).

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_man_bits (Sequence[int]) – stored mantissa bits of each entry’s multiply format.

  • mul_exp_bits (Sequence[int]) – exponent bits of each entry’s multiply format.

  • mul_normal_binades (int | Sequence[int]) – binades of each entry’s multiply format that carry the mantissa.

  • mul_bias (int | Sequence[int]) – exponent bias of each entry’s multiply format.

  • mul_is_signed (bool) – whether the multiply formats have a sign bit; shared by the palette. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding; shared by the palette. Default: 0

  • accumulate_quant (bool) – whether the running sum is rounded to the accumulate format after every step. Default: True

  • acc_man_bits (int | Sequence[int] | None) – the accumulate formats’ mantissa bits. Default: None, the mul_man_bits entry.

  • acc_exp_bits (int | Sequence[int] | None) – the accumulate formats’ exponent bits. Default: None, the mul_exp_bits entry.

  • acc_normal_binades (int | Sequence[int] | None) – the accumulate formats’ normal binades. Default: None, the mul_normal_binades entry.

  • acc_bias (int | Sequence[int] | None) – the accumulate formats’ exponent bias. Default: None, the mul_bias entry.

  • acc_is_signed (bool | None) – whether the accumulate formats have a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed; the palette ops implement NAIVE only. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of every format. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply formats’ overflow behavior. Default: SaturationMode.SAT_NONE

  • acc_saturation_mode (SaturationMode | None) – the accumulate formats’ overflow behavior. Default: None, saturation_mode.

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if the palette is empty or a palette argument’s length is not n, if a carrier cannot hold an entry, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if n is above 8, prec_idx has the wrong shape or an entry outside [0, n), the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if an entry’s range outruns the carrier’s, or an accumulate entry’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> prec_idx = torch.tensor([[0, 0], [0, 1]])
>>> superfp_matmul_mixed(
...     a, a, prec_idx, mul_man_bits=[3, 2], mul_exp_bits=[4, 4],
...     mul_normal_binades=8, mul_bias=7,
... )
tensor([[ 7., 10.],
        [15., 24.]])
mptorch.quant.binaryK_matmul_fma_mixed(a, b, prec_idx, *, trans_a=False, trans_b=False, fma_K, fma_P, fma_bias=None, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, carrier=None)[source]#

Quantized fused-multiply-add GEMM whose binaryK format varies per element.

The palette analog of binaryK_matmul_fma(). Each dot-product step is a single fused multiply-add, rounded once. The binaryK format of that rounding is chosen per output element by prec_idx, from a palette of up to 8 formats. prec_idx follows the contract of binaryK_matmul_mixed().

fma_K and fma_P are per-entry sequences, and their common length is the palette size n. fma_bias may be a scalar, an n-length sequence, or None for P3109’s bias per entry.

fma_quant=False is rejected. An unrounded fused step has no format, so a palette would leave prec_idx nothing to choose. Use binaryK_matmul_fma() for the unquantized fused step.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • prec_idx (Tensor) – the palette index of each output element, in [0, n).

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • fma_K (Sequence[int]) – width in bits of each entry’s format.

  • fma_P (Sequence[int]) – precision of each entry’s format.

  • fma_bias (int | Sequence[int] | None) – exponent bias of each entry’s format. Default: None, P3109’s per entry.

  • fma_is_signed (bool) – whether the formats have a sign bit; shared by the palette. Default: True

  • fma_quant (bool) – must be True. Default: True

  • fma_prng_bits (int) – random bits RoundMode.SR draws for the fused rounding; shared by the palette. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the fused steps are summed; the palette ops implement NAIVE only. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of every entry. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the formats’ overflow behavior. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – the formats’ bottom of range. Default: SubnormalsMode.SUBNORMALS

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if the palette is empty or a palette argument’s length is not n, if a carrier cannot hold an entry, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if fma_quant is false, n is above 8, prec_idx has the wrong shape or an entry outside [0, n), the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if an entry’s range outruns the carrier’s or reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> prec_idx = torch.tensor([[0, 0], [0, 1]])
>>> binaryK_matmul_fma_mixed(a, a, prec_idx, fma_K=[8, 8], fma_P=[4, 3])
tensor([[ 7., 10.],
        [15., 24.]])
mptorch.quant.superfp_matmul_fma_mixed(a, b, prec_idx, *, trans_a=False, trans_b=False, fma_man_bits, fma_exp_bits, fma_normal_binades, fma_bias, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, carrier=None)[source]#

Quantized fused-multiply-add GEMM whose superfp format varies per element.

The superfp analog of binaryK_matmul_fma_mixed(), which describes the palette, prec_idx and the carrier contract. fma_quant=False is rejected here too, because an unrounded fused step has no format for prec_idx to choose. fma_man_bits and fma_exp_bits are per-entry sequences, and their common length is the palette size n. fma_normal_binades and fma_bias may each be a scalar or an n-length sequence.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • prec_idx (Tensor) – the palette index of each output element, in [0, n).

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • fma_man_bits (Sequence[int]) – stored mantissa bits of each entry’s format.

  • fma_exp_bits (Sequence[int]) – exponent bits of each entry’s format.

  • fma_normal_binades (int | Sequence[int]) – binades of each entry’s format that carry the mantissa.

  • fma_bias (int | Sequence[int]) – exponent bias of each entry’s format.

  • fma_is_signed (bool) – whether the formats have a sign bit; shared by the palette. Default: True

  • fma_quant (bool) – must be True. Default: True

  • fma_prng_bits (int) – random bits RoundMode.SR draws for the fused rounding; shared by the palette. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the fused steps are summed; the palette ops implement NAIVE only. Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of every entry. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the formats’ overflow behavior. Default: SaturationMode.SAT_NONE

  • carrier (dtype | None) – as for binaryK_matmul(). Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if the palette is empty or a palette argument’s length is not n, if a carrier cannot hold an entry, if carrier names no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if fma_quant is false, n is above 8, prec_idx has the wrong shape or an entry outside [0, n), the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if an entry’s range outruns the carrier’s or reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> prec_idx = torch.tensor([[0, 0], [0, 1]])
>>> superfp_matmul_fma_mixed(
...     a, a, prec_idx, fma_man_bits=[3, 2], fma_exp_bits=[4, 4],
...     fma_normal_binades=8, fma_bias=7,
... )
tensor([[ 7., 10.],
        [15., 24.]])
mptorch.quant.binaryK_superfp_matmul(a, b, *, trans_a=False, trans_b=False, mul_K, mul_P, mul_bias=None, mul_is_signed=True, mul_prng_bits=0, acc_man_bits, acc_exp_bits, acc_normal_binades, acc_bias, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, acc_saturation_mode=None, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None)[source]#

Quantized GEMM whose products are binaryK and whose sums are superfp.

The cross-family split multiply-accumulate: each step computes s = round_acc(s + round_mul(a * b)) in the carrier, as binaryK_matmul() does, with the product rounded to the binaryK format mul_K/mul_P and the partial sum to the superfp format given by the four acc_* widths. The accumulate format is required: a sum left in the carrier is binaryK_matmul() with accumulate_quant=False. binaryK_matmul() describes the general contract (torch.matmul’s operand rules, the transpose flags, the carrier, the storage check, the per-call resolution) and superfp_quantize() the accumulate format. The result holds the accumulate format’s values, or with BLOCK or TREE and an outer format, the outer format’s, which is of the accumulate’s family.

mptorch.quant.SplitMac with a mptorch.BinaryK multiply and a mptorch.SuperFP accumulate resolves to this op.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_K (int) – width in bits of the binaryK multiply format.

  • mul_P (int) – precision of the multiply format.

  • mul_bias (int | None) – exponent bias of the multiply format. Default: None, P3109’s 2**(K - P - 1) signed and 2**(K - P) unsigned.

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding. Default: 0

  • acc_man_bits (int) – stored mantissa bits of the superfp accumulate format.

  • acc_exp_bits (int) – exponent bits of the accumulate format.

  • acc_normal_binades (int) – binades of the accumulate format that carry the mantissa.

  • acc_bias (int) – exponent bias of the accumulate format.

  • acc_is_signed (bool | None) – whether the accumulate format has a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – as for binaryK_matmul(). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of both formats. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – the multiply format’s bottom of range. Default: SubnormalsMode.SUBNORMALS

  • acc_saturation_mode (SaturationMode | None) – the accumulate format’s overflow behavior. Default: None, saturation_mode.

  • block_size (int | None) – as for binaryK_matmul(). Default: None

  • outer_man_bits (int | None) – mantissa bits of the superfp outer format, as superfp_matmul()’s. The four widths are given together, or none of them. Default: None

  • outer_exp_bits (int | None) – exponent bits of the outer format. Default: None

  • outer_normal_binades (int | None) – normal binades of the outer format. Default: None

  • outer_bias (int | None) – exponent bias of the outer format. Default: None

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, the accumulate format’s.

  • outer_prng_bits (int) – random bits RoundMode.SR draws for the outer rounding. Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, the accumulate format’s.

  • carrier (dtype | None) – as for binaryK_quantize(). torch.float64 widens narrower operands to binary64 and narrows the result back to their dtype with one rounding. torch.float32 refuses float64 operands. Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold a format, if carrier is torch.float64 or names no carrier, if the operands are float64, or if their leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if a format’s range outruns the carrier’s, or the accumulate format’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> binaryK_superfp_matmul(
...     a, a, mul_K=8, mul_P=4,
...     acc_man_bits=2, acc_exp_bits=4, acc_normal_binades=8, acc_bias=7,
... )
tensor([[ 7., 10.],
        [16., 24.]])

Every product is exact in Binary8p4. The sums 15 and 22 fall halfway between values of the superfp accumulate format, whose two mantissa bits space them 2 apart in [8, 16) and 4 apart in [16, 32), and round to the even mantissa: 16 and 24.

mptorch.quant.superfp_binaryK_matmul(a, b, *, trans_a=False, trans_b=False, mul_man_bits, mul_exp_bits, mul_normal_binades, mul_bias, mul_is_signed=True, mul_prng_bits=0, acc_K, acc_P, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, acc_saturation_mode=None, acc_subnormals_mode=SubnormalsMode.SUBNORMALS, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None)[source]#

Quantized GEMM whose products are superfp and whose sums are binaryK.

binaryK_superfp_matmul() with the families exchanged: each product is rounded to the superfp format given by the four mul_* widths and each partial sum to the binaryK format acc_K/acc_P, which is required (a sum left in the carrier is superfp_matmul() with accumulate_quant=False). With BLOCK or TREE the outer format is a binaryK one, as binaryK_matmul()’s. mptorch.quant.SplitMac with a mptorch.SuperFP multiply and a mptorch.BinaryK accumulate resolves to this op.

Parameters:
  • a (Tensor) – the left operand; float32, float64, float16 or bfloat16.

  • b (Tensor) – the right operand, of a’s dtype and device.

  • trans_a (bool) – read a transposed in its last two dimensions. Default: False

  • trans_b (bool) – read b transposed in its last two dimensions. Default: False

  • mul_man_bits (int) – stored mantissa bits of the superfp multiply format.

  • mul_exp_bits (int) – exponent bits of the multiply format.

  • mul_normal_binades (int) – binades of the multiply format that carry the mantissa.

  • mul_bias (int) – exponent bias of the multiply format.

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits RoundMode.SR draws for the multiply rounding. Default: 0

  • acc_K (int) – width in bits of the binaryK accumulate format.

  • acc_P (int) – precision of the accumulate format.

  • acc_bias (int | None) – exponent bias of the accumulate format. Default: None, P3109’s for acc_K/acc_P.

  • acc_is_signed (bool | None) – whether the accumulate format has a sign bit. Default: None, mul_is_signed.

  • acc_prng_bits (int) – random bits RoundMode.SR draws for the accumulate rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – as for binaryK_matmul(). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – the rounding of both formats. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – the multiply format’s overflow behavior. Default: SaturationMode.SAT_NONE

  • acc_saturation_mode (SaturationMode | None) – the accumulate format’s overflow behavior. Default: None, saturation_mode.

  • acc_subnormals_mode (SubnormalsMode) – the accumulate format’s bottom of range. A superfp multiply has none to default to. Default: SubnormalsMode.SUBNORMALS

  • block_size (int | None) – as for binaryK_matmul(). Default: None

  • outer_K (int | None) – width of the binaryK outer format, as binaryK_matmul()’s. Default: None

  • outer_P (int | None) – precision of the outer format; given together with outer_K. Default: None

  • outer_bias (int | None) – exponent bias of the outer format. Default: None, P3109’s for outer_K/outer_P.

  • outer_is_signed (bool | None) – whether the outer format has a sign bit. Default: None, the accumulate format’s.

  • outer_prng_bits (int) – random bits RoundMode.SR draws for the outer rounding. Default: 0

  • outer_saturation_mode (SaturationMode | None) – the outer format’s overflow behavior. Default: None, the accumulate format’s.

  • outer_subnormals_mode (SubnormalsMode | None) – the outer format’s bottom of range. Default: None, the accumulate format’s.

  • carrier (dtype | None) – as for binaryK_quantize(). torch.float64 widens narrower operands to binary64 and narrows the result back to their dtype with one rounding. torch.float32 refuses float64 operands. Default: None, the operands’ own carrier.

Returns:

the product, in the operands’ dtype, with the shape torch.matmul would give.

Return type:

Tensor

Raises:
  • ValueError – if a carrier cannot hold a format, if carrier is torch.float64 or names no carrier, if the operands are float64, or if their leading dimensions do not broadcast.

  • TypeError – if carrier is neither a torch.dtype nor None.

  • RuntimeError – if the inner dimensions do not match, the operands differ in dtype or device, or an operand requires grad under grad mode.

Warns:

FormatRangeWarning – if a format’s range outruns the carrier’s, or the accumulate format’s range reaches past a narrower result dtype’s.

Example:

>>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> superfp_binaryK_matmul(
...     a, a, mul_man_bits=3, mul_exp_bits=4, mul_normal_binades=8, mul_bias=7,
...     acc_K=8, acc_P=3,
... )
tensor([[ 7., 10.],
        [16., 24.]])

Layers#

See Layers.

class mptorch.quant.QAffineFormats(weight_quant=None, input_quant=None, bias_quant=None, wgrad_quant=None, igrad_quant=None, bgrad_quant=None, fwd_math=None, bwd_igrad_math=None, bwd_wgrad_math=None, recompute_input=None, recompute_weight=None)[source]#

Quantizers and custom math for an affine layer (Linear, Conv1d/2d/3d).

Every slot is optional, and None means plain PyTorch behaviour for that step. Quantization is therefore opt-in per tensor and per pass: with a QAffineFormats() that has nothing set, QLinear behaves exactly as nn.Linear.

The forward pass quantizes the input, the weight and the bias through their *_quant slots, then runs fwd_math (or the plain op). The backward pass quantizes the incoming gradient separately for the input-gradient path (igrad_quant) and the weight-gradient path (wgrad_quant), because the two GEMMs may need different formats. It then runs bwd_igrad_math and bwd_wgrad_math (or PyTorch’s defaults).

The class inherits from nn.Module. A quantizer that is itself an nn.Module (a QAT observer with running statistics) is therefore registered with the parent model and appears in its state_dict.

Backward needs the quantized input (for the weight gradient) and the quantized weight (for the input gradient) again. The 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 backward, which saves the copy wherever the raw operand is alive anyway: the weight always is, and an input is when the op that made it keeps its output (ReLU does). The two recompute_* flags choose; None is the layer’s default (both for QConv1d/2d/3d, the weight only for QLinear). Gradients are bit-identical either way: under stochastic rounding the second call sees the random generators as the first did. Layers (“What a layer keeps for backward”) says when each choice saves memory.

Parameters:
  • weight_quant (Callable | None) – applied to the weight in the forward. Default: None

  • input_quant (Callable | None) – applied to the input in the forward. Default: None

  • bias_quant (Callable | None) – applied to the bias in the forward. Default: None

  • wgrad_quant (Callable | None) – applied to the output gradient before the weight-gradient GEMM. Default: None

  • igrad_quant (Callable | None) – applied to the output gradient before the input-gradient GEMM. Default: None

  • bgrad_quant (Callable | None) – applied to the output gradient before the bias-gradient sum. Default: None

  • fwd_math (Callable | None) – the forward’s arithmetic. For Linear, fwd_math(q_input, q_weight, q_bias); for Conv, the same plus stride, padding, dilation, groups and nd as keywords. Default: None

  • bwd_igrad_math (Callable | None) – the input gradient’s arithmetic, bwd_igrad_math(q_grad_output, q_weight) for Linear (Conv adds input_size and the convolution keywords). Default: None

  • bwd_wgrad_math (Callable | None) – the weight gradient’s arithmetic, bwd_wgrad_math(q_grad_output, q_input) for Linear (Conv adds weight_size and the convolution keywords). Default: None

  • recompute_input (bool | None) – keep the raw input for backward and run input_quant on it again there, instead of keeping its result. None is the layer’s default: True for a convolution, False for QLinear. Under None only a quantizer known to be stateless is run twice – a mptorch.quant.Quant (not in place), a mptorch.quant.BlockQuant called as a fake quantizer, or a mptorch.quant.Quantizer over one – and any other callable keeps its result saved, since one with state (a QAT observer) would update it twice. True runs any callable again, which is the caller’s promise that it depends only on its input and the random generators. A quantizer whose result is not a tensor (a packed block format) keeps it saved. Default: None

  • recompute_weight (bool | None) – the same for the weight and weight_quant. None is True for every layer, since the raw weight is alive anyway as the layer’s parameter. Default: None

Example:

>>> from mptorch import BinaryK
>>> from mptorch.quant import QAffineFormats, QLinear, Quant, binaryK_gemm_formats
>>> formats = binaryK_gemm_formats(mul_K=8, mul_P=4, accumulate_quant=False)
>>> formats.input_quant = Quant(BinaryK(8, 4))
>>> formats.weight_quant = Quant(BinaryK(8, 4))
>>> layer = QLinear(256, 64, formats=formats)
>>> plain = QLinear(256, 64, formats=QAffineFormats())   # as nn.Linear

Initialize internal Module state, shared by both nn.Module and ScriptModule.

class mptorch.quant.QLinear(in_features, out_features, bias=True, device=None, dtype=None, formats=None)[source]#

torch.nn.Linear with per-tensor quantization and custom arithmetic.

It holds the same parameters as nn.Linear and computes the same input @ weight.T + bias, but through CustomArithLinear. The input, the weight, the bias and each gradient can therefore be rounded by the quantizers in formats, and each GEMM can run in custom arithmetic (see mptorch.quant.binaryK_gemm_formats()). With formats left None, or with a QAffineFormats whose slots are all None, the layer is numerically identical to nn.Linear. formats is a submodule, so a stateful quantizer in it appears in the layer’s state_dict. For backward the layer keeps a quantized copy of its input and its raw weight, which it quantizes again there, unless formats’ recompute_input / recompute_weight say otherwise. A layer over mptorch.quant.block_gemm_formats() can drop its float weight for its block codes with freeze_packed_().

Parameters:
  • in_features (int) – size of each input sample.

  • out_features (int) – size of each output sample.

  • bias (bool) – whether the layer learns an additive bias. Default: True

  • device – as for nn.Linear. Default: None

  • dtype – as for nn.Linear. Default: None

  • formats (QAffineFormats | None) – the quantizers and math hooks. None builds an empty QAffineFormats(). Default: None

Shape:
  • Input: (*, in_features), any number of leading dimensions.

  • Output: (*, out_features).

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QLinear, Quant, binaryK_gemm_formats
>>> formats = binaryK_gemm_formats(mul_K=8, mul_P=4, acc_K=16, acc_P=11)
>>> formats.input_quant = Quant(BinaryK(8, 4))
>>> formats.weight_quant = Quant(BinaryK(8, 4))
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(input)[source]#

Runs the forward pass.

Return type:

Tensor

Parameters:

input (Tensor)

freeze_packed_(*, pack=True)[source]#

Replace the float weight by its block codes, in place.

The layer becomes a QPackedLinear: its weight is None, and two uint8 buffers, weight_codes and weight_scales, hold the weight packed along its input features. The codes are what the layer’s forward multiplies, so the frozen layer returns what it returned before:

  • with formats.weight_quant unset, the weight packed in the weight format of mptorch.quant.block_gemm_formats();

  • with weight_quant = BlockQuant(fmt, axis=1).pack, that packing: the memoized one, if the weight has not changed since the last forward (its stochastic draws included), and the memo is then cleared, since it would keep the codes alive;

  • with another quantizer, the weight format’s packing of its result.

Nothing is kept of the float weight, so its memory is freed once nothing else refers to it: freeze before building an optimizer or any copy of the parameters. A square-tiled weight still serves the input gradient, so layers below a frozen one can train; there is no weight gradient, and the bias stays a float parameter.

Parameters:

pack (bool) – pack the weight. False allocates zeroed buffers of the right shapes instead, on the weight’s device, for load_state_dict() of a frozen checkpoint to fill; on the meta device it allocates nothing. Default: True

Returns:

this layer.

Return type:

QPackedLinear

Raises:
  • ValueError – for formats that do not come from mptorch.quant.block_gemm_formats(), for pack=True on a weight on the meta device, which has no values, and for a weight_quant result the block hooks cannot multiply.

  • TypeError – for a layer that is frozen already (quantizing twice is not always the identity), or of a subclass of QLinear, whose class the switch would drop.

Example:

>>> import torch
>>> from mptorch import BinaryK, MXFP8_E4M3
>>> from mptorch.quant import QLinear, block_gemm_formats
>>> layer = QLinear(64, 32, formats=block_gemm_formats(MXFP8_E4M3, MXFP8_E4M3))
>>> x = torch.randn(4, 64)
>>> with torch.no_grad():
...     before = layer(x)
...     _ = layer.freeze_packed_()
...     torch.equal(layer(x), before), layer.weight
(True, None)
>>> sorted(layer.state_dict())
['_extra_state', 'bias', 'weight_codes', 'weight_scales']
class mptorch.quant.QPackedLinear(*args, **kwargs)[source]#

A QLinear whose weight is stored only as its block codes.

QLinear.freeze_packed_() and mptorch.quant.freeze_packed_() make one, in place, from a QLinear over mptorch.quant.block_gemm_formats(); the class is not constructed directly. It is still a QLinear (isinstance holds) and returns what the layer returned before the freeze, from a fraction of the memory: the weight’s codes and scales are uint8 buffers, weight_codes and weight_scales, which follow .to() and stay uint8 under .half(), and weight is None. The packing’s format, shape, tensor scale, dtype and carrier are in the state_dict’s _extra_state, as plain values.

The format itself is code, as every hook of the layer’s formats is. To load a frozen checkpoint, build the model as it was built, freeze it with pack=False, which allocates zeroed codes and packs nothing, and load the state_dict. A model built on the meta device and frozen that way allocates its codes only when the state is loaded with assign=True, so the float model never exists. A checkpoint frozen in another format or shape raises, naming both.

packed_weight is the codes as a mptorch.quant.BlockPacked, and unfreeze_packed_() turns the layer back into a QLinear.

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
weight_codes: Tensor#
weight_scales: Tensor#
property packed_weight: BlockPacked#

The weight as a mptorch.quant.BlockPacked over the two buffers, built per call, so that it follows the buffers through .to().

forward(input)[source]#

Runs the forward pass.

Return type:

Tensor

Parameters:

input (Tensor)

reset_parameters()[source]#

Resets parameters based on their initialization used in __init__.

Return type:

None

extra_repr()[source]#

Return the extra representation of the module.

Return type:

str

get_extra_state()[source]#

Return any extra state to include in the module’s state_dict.

Implement this and a corresponding set_extra_state() for your module if you need to store extra state. This function is called when building the module’s state_dict().

Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.

Returns:

Any extra state to store in the module’s state_dict

Return type:

dict[str, Any]

set_extra_state(state)[source]#

Set extra state contained in the loaded state_dict.

This function is called from load_state_dict() to handle any extra state found within the state_dict. Implement this function and a corresponding get_extra_state() for your module if you need to store extra state within its state_dict.

Parameters:

state (Any) – Extra state from the state_dict

Return type:

None

unfreeze_packed_()[source]#

Turn the layer back into a QLinear, in place, whose float weight is the decoded codes (mptorch.quant.block_unpack()): the quantized weight, not the one the layer was frozen from, in the dtype it was packed from. For fine-tuning from a frozen checkpoint, or exporting to tools that read a plain nn.Linear.

Return type:

QLinear

mptorch.quant.freeze_packed_(model, *, pack=True)[source]#

QLinear.freeze_packed_() on every QLinear of model whose formats come from mptorch.quant.block_gemm_formats().

The layers are frozen one at a time, so the freeze holds at most one layer’s float weight and its codes at once beyond the model. A model that does not fit on its device as float can be frozen on the CPU and then moved. Other modules are left as they are.

Parameters:
  • model (Module) – the model, or one layer.

  • pack (bool) – as for QLinear.freeze_packed_(): False allocates zeroed codes for a frozen checkpoint to fill. Default: True

Returns:

how many layers were frozen.

Return type:

int

Example:

>>> import torch
>>> from torch import nn
>>> from mptorch import BinaryK, MXFP8_E4M3
>>> from mptorch.quant import QLinear, block_gemm_formats, freeze_packed_
>>> def mlp():
...     return nn.Sequential(
...         QLinear(64, 64, formats=block_gemm_formats(MXFP8_E4M3, MXFP8_E4M3)),
...         nn.ReLU(),
...         QLinear(64, 8, formats=block_gemm_formats(MXFP8_E4M3, MXFP8_E4M3)),
...     )
>>> model = mlp()
>>> freeze_packed_(model)
2
>>> skeleton = mlp()  # load: build, freeze without packing, then load
>>> freeze_packed_(skeleton, pack=False)
2
>>> skeleton.load_state_dict(model.state_dict())
<All keys matched successfully>
class mptorch.quant.QConv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, formats=None)[source]#

torch.nn.Conv1d with per-tensor quantization and custom arithmetic.

It holds the same parameters as nn.Conv1d and computes the same convolution, but through CustomArithConvNd. The input, the weight, the bias and each gradient can therefore be rounded by the quantizers in formats, and each convolution can run in custom arithmetic. With formats left None, or with a QAffineFormats whose slots are all None, the layer is numerically identical to nn.Conv1d. A padding_mode other than "zeros" is applied with F.pad before the Function, as nn.Conv1d does, so the Function only ever sees zero padding. For backward the layer keeps its raw input and weight, which it quantizes again there, unless formats’ recompute_input / recompute_weight say otherwise.

Parameters:
  • in_channels (int) – channels of the input.

  • out_channels (int) – channels of the output.

  • kernel_size (int | tuple[int]) – size of the convolving kernel.

  • stride (int | tuple[int]) – stride of the convolution. Default: 1

  • padding (int | tuple[int] | str) – padding added to both sides of the input. Default: 0

  • dilation (int | tuple[int]) – spacing between kernel elements. Default: 1

  • groups (int) – blocked connections from input to output channels. Default: 1

  • bias (bool) – whether the layer learns an additive bias. Default: True

  • padding_mode (Literal['zeros', 'reflect', 'replicate', 'circular']) – "zeros", "reflect", "replicate" or "circular". Default: "zeros"

  • device – as for nn.Conv1d. Default: None

  • dtype – as for nn.Conv1d. Default: None

  • formats (QAffineFormats | None) – the quantizers and math hooks; mptorch.quant.conv_formats() builds hooks that run the three convolutions in a custom arithmetic. None builds an empty QAffineFormats(). Default: None

Shape:
  • Input: (N, C_in, L_in) or (C_in, L_in).

  • Output: (N, C_out, L_out) or (C_out, L_out), as for nn.Conv1d.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QAffineFormats, QConv1d, Quant
>>> formats = QAffineFormats(weight_quant=Quant(BinaryK(8, 4)))
>>> conv = QConv1d(3, 8, 3, formats=formats)
>>> conv(torch.randn(1, 3, 16)).shape
torch.Size([1, 8, 14])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(input)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

input (Tensor)

class mptorch.quant.QConv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, formats=None)[source]#

torch.nn.Conv2d with per-tensor quantization and custom arithmetic.

The 2D twin of QConv1d. It has the same parameters as nn.Conv2d and computes the same convolution, through CustomArithConvNd, so the quantizers and math hooks in formats apply. With empty formats it is numerically identical to nn.Conv2d.

Parameters:
  • in_channels (int) – channels of the input.

  • out_channels (int) – channels of the output.

  • kernel_size (int | tuple[int, int]) – size of the convolving kernel.

  • stride (int | tuple[int, int]) – stride of the convolution. Default: 1

  • padding (int | tuple[int, int] | str) – padding added to all four sides of the input. Default: 0

  • dilation (int | tuple[int, int]) – spacing between kernel elements. Default: 1

  • groups (int) – blocked connections from input to output channels. Default: 1

  • bias (bool) – whether the layer learns an additive bias. Default: True

  • padding_mode (Literal['zeros', 'reflect', 'replicate', 'circular']) – "zeros", "reflect", "replicate" or "circular". Default: "zeros"

  • device – as for nn.Conv2d. Default: None

  • dtype – as for nn.Conv2d. Default: None

  • formats (QAffineFormats | None) – the quantizers and math hooks. None builds an empty QAffineFormats(). Default: None

Shape:
  • Input: (N, C_in, H_in, W_in) or (C_in, H_in, W_in).

  • Output: (N, C_out, H_out, W_out) or (C_out, H_out, W_out), as for nn.Conv2d.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QAffineFormats, QConv2d, Quant
>>> formats = QAffineFormats(weight_quant=Quant(BinaryK(8, 4)))
>>> conv = QConv2d(3, 8, 3, formats=formats)
>>> conv(torch.randn(1, 3, 16, 16)).shape
torch.Size([1, 8, 14, 14])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(input)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

input (Tensor)

class mptorch.quant.QConv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None, formats=None)[source]#

torch.nn.Conv3d with per-tensor quantization and custom arithmetic.

The 3D twin of QConv1d. It has the same parameters as nn.Conv3d and computes the same convolution, through CustomArithConvNd, so the quantizers and math hooks in formats apply. With empty formats it is numerically identical to nn.Conv3d.

Parameters:
  • in_channels (int) – channels of the input.

  • out_channels (int) – channels of the output.

  • kernel_size (int | tuple[int, int, int]) – size of the convolving kernel.

  • stride (int | tuple[int, int, int]) – stride of the convolution. Default: 1

  • padding (int | tuple[int, int, int] | str) – padding added to all six sides of the input. Default: 0

  • dilation (int | tuple[int, int, int]) – spacing between kernel elements. Default: 1

  • groups (int) – blocked connections from input to output channels. Default: 1

  • bias (bool) – whether the layer learns an additive bias. Default: True

  • padding_mode (Literal['zeros', 'reflect', 'replicate', 'circular']) – "zeros", "reflect", "replicate" or "circular". Default: "zeros"

  • device – as for nn.Conv3d. Default: None

  • dtype – as for nn.Conv3d. Default: None

  • formats (QAffineFormats | None) – the quantizers and math hooks. None builds an empty QAffineFormats(). Default: None

Shape:
  • Input: (N, C_in, D_in, H_in, W_in) or (C_in, D_in, H_in, W_in).

  • Output: (N, C_out, D_out, H_out, W_out) or (C_out, D_out, H_out, W_out), as for nn.Conv3d.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QAffineFormats, QConv3d, Quant
>>> formats = QAffineFormats(weight_quant=Quant(BinaryK(8, 4)))
>>> conv = QConv3d(3, 8, 3, formats=formats)
>>> conv(torch.randn(1, 3, 8, 16, 16)).shape
torch.Size([1, 8, 6, 14, 14])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(input)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

input (Tensor)

Layer arithmetic factories#

mptorch.quant.binaryK_gemm_formats(mul_K, mul_P, *, mul_bias=None, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_K=None, acc_P=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, acc_saturation_mode=None, acc_subnormals_mode=None, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Build a QAffineFormats whose dot products run in a binaryK GEMM.

The returned formats set fwd_math, bwd_igrad_math and bwd_wgrad_math. A Linear layer’s forward GEMM and both of its gradient GEMMs then run through mptorch.quant.ops.binaryK_matmul(), which takes these same arguments. Every product is rounded to the mul_* format. When accumulate_quant is set, every partial sum is rounded to the acc_* format.

The format is resolved once, here, so each pass costs only the op. Every pass checks the formats against the carrier of the tensors it runs on: binary64 for a float64 layer and binary32 otherwise, unless carrier names one. It warns with mptorch.FormatRangeWarning about a range that the carrier cannot hold.

Parameters:
  • mul_K (int) – total width in bits of the multiply format.

  • mul_P (int) – precision (significand bits, the implicit one included) of the multiply format.

  • mul_bias (int | None) – exponent bias of the multiply format. None takes IEEE P3109’s, 2**(K-P-1) signed and 2**(K-P) unsigned. Default: None

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits drawn per stochastic rounding of a product; only read when rounding_mode is RoundMode.SR. Default: 0

  • accumulate_quant (bool) – whether the running sum is rounded to the acc_* format after every step. False keeps it in the carrier’s precision and ignores the acc_* widths. Default: True

  • acc_K (int | None) – width of the accumulate format. None takes mul_K. Default: None

  • acc_P (int | None) – precision of the accumulate format. None takes mul_P. Default: None

  • acc_bias (int | None) – exponent bias of the accumulate format. None takes P3109’s for acc_K/acc_P. Default: None

  • acc_is_signed (bool | None) – sign bit of the accumulate format. None takes mul_is_signed. Default: None

  • acc_prng_bits (int) – random bits per stochastic rounding of a partial sum. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed, as for mptorch.quant.binaryK_matmul(): NAIVE, KAHAN, BLOCK or TREE (the last not for a fused mac). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – rounding for both formats; one mode for both because the kernels take it as a template parameter. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – overflow behaviour of the multiply format. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – what the multiply format keeps below its smallest normal. Default: SubnormalsMode.SUBNORMALS

  • acc_saturation_mode (SaturationMode | None) – overflow behaviour of the accumulate format. None takes saturation_mode. Default: None

  • acc_subnormals_mode (SubnormalsMode | None) – subnormal handling of the accumulate format. None takes subnormals_mode. Default: None

  • block_size (int | None) – BLOCK’s and TREE’s block size, as for mptorch.quant.binaryK_matmul(). Default: None

  • outer_K (int | None) – width of the outer format BLOCK and TREE round their total to, as for mptorch.quant.binaryK_matmul(), which documents it and the rest of its spelling: outer_P, outer_bias, outer_is_signed, outer_prng_bits, outer_saturation_mode and outer_subnormals_mode. Default: None, an unrounded total.

  • carrier (dtype | None) – the float arithmetic the GEMM rounds in. None takes the layer’s (binary64 for float64, binary32 for the rest); torch.float64 runs a float32 or half-precision layer in binary64 too and narrows each result back to the layer’s dtype; torch.float32 on a float64 layer raises at the call. Default: None

  • carrier_rounding (RoundMode) – RoundMode.RO rounds the carrier’s steps to odd, as for mptorch.quant.binaryK_matmul(), for every pass of the layer; NAIVE only. Default: RoundMode.RNE

  • outer_P (int | None)

  • outer_bias (int | None)

  • outer_is_signed (bool | None)

  • outer_prng_bits (int)

  • outer_saturation_mode (SaturationMode | None)

  • outer_subnormals_mode (SubnormalsMode | None)

Returns:

with the three *_math hooks set and every *_quant slot left None.

Return type:

QAffineFormats

Raises:

ValueError – for a format no carrier can hold (precision above 53 bits, an exponent field past 30 bits, stochastic bits with no significand left) or a carrier that names no carrier.

Example:

>>> import torch
>>> from mptorch import BinaryK
>>> from mptorch.quant import QLinear, Quant, binaryK_gemm_formats
>>> formats = binaryK_gemm_formats(mul_K=8, mul_P=4, acc_K=16, acc_P=11)
>>> formats.input_quant = Quant(BinaryK(8, 4))
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.binaryK_gemm_formats_fma(fma_K, fma_P, *, fma_bias=None, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

Fused-multiply-add analog of binaryK_gemm_formats().

Each dot-product step is one fused multiply-add, round_fma(s + a * b), rounded once to the fma_* format (mptorch.quant.ops.binaryK_matmul_fma()). It replaces a rounded multiply followed by a separately rounded add. The general contract is that of binaryK_gemm_formats(): resolution at construction, the carrier and the warnings.

Parameters:
  • fma_K (int) – total width in bits of the fused format.

  • fma_P (int) – precision of the fused format, the implicit bit included.

  • fma_bias (int | None) – exponent bias; None takes IEEE P3109’s. Default: None

  • fma_is_signed (bool) – whether the format has a sign bit. Default: True

  • fma_quant (bool) – whether each fused step is rounded at all. False runs unrounded fused steps in the carrier. Default: True

  • fma_prng_bits (int) – random bits per stochastic rounding; only read when rounding_mode is RoundMode.SR. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed, as for mptorch.quant.binaryK_matmul(): NAIVE, KAHAN, BLOCK or TREE (the last not for a fused mac). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – rounding of each fused step. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – overflow behaviour. Default: SaturationMode.SAT_NONE

  • subnormals_mode (SubnormalsMode) – subnormal handling. Default: SubnormalsMode.SUBNORMALS

  • block_size (int | None) – BLOCK’s and TREE’s block size, as for mptorch.quant.binaryK_matmul(). Default: None

  • outer_K (int | None) – width of the outer format BLOCK and TREE round their total to, as for mptorch.quant.binaryK_matmul(), which documents it and the rest of its spelling: outer_P, outer_bias, outer_is_signed, outer_prng_bits, outer_saturation_mode and outer_subnormals_mode. Default: None, an unrounded total.

  • carrier (dtype | None) – as for binaryK_gemm_formats(). Default: None

  • carrier_rounding (RoundMode) – RoundMode.RO rounds the carrier’s steps to odd, as for mptorch.quant.binaryK_matmul_fma(), for every pass of the layer; NAIVE only. Default: RoundMode.RNE

  • outer_P (int | None)

  • outer_bias (int | None)

  • outer_is_signed (bool | None)

  • outer_prng_bits (int)

  • outer_saturation_mode (SaturationMode | None)

  • outer_subnormals_mode (SubnormalsMode | None)

Returns:

with the three *_math hooks set.

Return type:

QAffineFormats

Raises:

ValueError – as for binaryK_gemm_formats().

Example:

>>> import torch
>>> from mptorch.quant import QLinear, binaryK_gemm_formats_fma
>>> layer = QLinear(256, 64, formats=binaryK_gemm_formats_fma(8, 4))
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.superfp_gemm_formats(mul_man_bits, mul_exp_bits, mul_normal_binades, mul_bias, *, mul_is_signed=True, mul_prng_bits=0, accumulate_quant=True, acc_man_bits=None, acc_exp_bits=None, acc_normal_binades=None, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, acc_saturation_mode=None, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

superfp analog of binaryK_gemm_formats().

The dot products run through mptorch.quant.ops.superfp_matmul(). Products are rounded to the mul_* superfp format. When accumulate_quant is set, partial sums are rounded to the acc_* one. A superfp format keeps a mantissa in the top normal_binades binades of its range and spends the rest of its codes on supernormal values, which are powers of two with no mantissa. It has no subnormals, so there is no subnormals_mode. superfp_gemm_formats_fma() is the fused-multiply-add analog.

Parameters:
  • mul_man_bits (int) – mantissa bits of the multiply format.

  • mul_exp_bits (int) – exponent bits of the multiply format.

  • mul_normal_binades (int) – binades with a full mantissa in the multiply format.

  • mul_bias (int) – exponent bias of the multiply format (required; superfp has no conventional default).

  • mul_is_signed (bool) – whether the multiply format has a sign bit. Default: True

  • mul_prng_bits (int) – random bits per stochastic rounding of a product. Default: 0

  • accumulate_quant (bool) – whether partial sums are rounded to the acc_* format. Default: True

  • acc_man_bits (int | None) – None takes mul_man_bits. Default: None

  • acc_exp_bits (int | None) – None takes mul_exp_bits. Default: None

  • acc_normal_binades (int | None) – None takes mul_normal_binades. Default: None

  • acc_bias (int | None) – None takes mul_bias. Default: None

  • acc_is_signed (bool | None) – None takes mul_is_signed. Default: None

  • acc_prng_bits (int) – random bits per stochastic rounding of a partial sum. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed, as for mptorch.quant.binaryK_matmul(): NAIVE, KAHAN, BLOCK or TREE (the last not for a fused mac). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – rounding for both formats. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – overflow behaviour of the multiply format. Default: SaturationMode.SAT_NONE

  • acc_saturation_mode (SaturationMode | None) – None takes saturation_mode. Default: None

  • block_size (int | None) – BLOCK’s and TREE’s block size, as for mptorch.quant.binaryK_matmul(). Default: None

  • outer_man_bits (int | None) – mantissa bits of the outer format BLOCK and TREE round their total to, as for mptorch.quant.superfp_matmul(), which documents it and the rest of its spelling: outer_exp_bits, outer_normal_binades, outer_bias, outer_is_signed, outer_prng_bits and outer_saturation_mode. Default: None, an unrounded total.

  • carrier (dtype | None) – as for binaryK_gemm_formats(). Default: None

  • carrier_rounding (RoundMode) – RoundMode.RO rounds the carrier’s steps to odd, as for mptorch.quant.superfp_matmul(), for every pass of the layer; NAIVE only. Default: RoundMode.RNE

  • outer_exp_bits (int | None)

  • outer_normal_binades (int | None)

  • outer_bias (int | None)

  • outer_is_signed (bool | None)

  • outer_prng_bits (int)

  • outer_saturation_mode (SaturationMode | None)

Returns:

with the three *_math hooks set.

Return type:

QAffineFormats

Raises:

ValueError – for a format no carrier can hold, a normal_binades that leaves no supernormal codes, or a carrier that names no carrier.

Example:

>>> import torch
>>> from mptorch.quant import QLinear, superfp_gemm_formats
>>> formats = superfp_gemm_formats(3, 4, 8, 7, accumulate_quant=False)
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.superfp_gemm_formats_fma(fma_man_bits, fma_exp_bits, fma_normal_binades, fma_bias, *, fma_is_signed=True, fma_quant=True, fma_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None, carrier_rounding=RoundMode.RNE)[source]#

superfp analog of binaryK_gemm_formats_fma().

Each dot-product step is one fused multiply-add, rounded once to the fma_* superfp format (mptorch.quant.ops.superfp_matmul_fma()). The arguments are the multiply-format arguments of superfp_gemm_formats() under the fma_ prefix, plus fma_quant, as in binaryK_gemm_formats_fma().

Parameters:
  • fma_man_bits (int) – mantissa bits of the fused format.

  • fma_exp_bits (int) – exponent bits of the fused format.

  • fma_normal_binades (int) – binades with a full mantissa.

  • fma_bias (int) – exponent bias (required).

  • fma_is_signed (bool) – whether the format has a sign bit. Default: True

  • fma_quant (bool) – whether each fused step is rounded at all. Default: True

  • fma_prng_bits (int) – random bits per stochastic rounding. Default: 0

  • accumulate_algorithm (AccumulateAlgorithm) – how the products are summed, as for mptorch.quant.binaryK_matmul(): NAIVE, KAHAN, BLOCK or TREE (the last not for a fused mac). Default: AccumulateAlgorithm.NAIVE

  • rounding_mode (RoundMode) – rounding of each fused step. Default: RoundMode.RNE

  • saturation_mode (SaturationMode) – overflow behaviour. Default: SaturationMode.SAT_NONE

  • block_size (int | None) – BLOCK’s and TREE’s block size, as for mptorch.quant.binaryK_matmul(). Default: None

  • outer_man_bits (int | None) – mantissa bits of the outer format BLOCK and TREE round their total to, as for mptorch.quant.superfp_matmul(), which documents it and the rest of its spelling: outer_exp_bits, outer_normal_binades, outer_bias, outer_is_signed, outer_prng_bits and outer_saturation_mode. Default: None, an unrounded total.

  • carrier (dtype | None) – as for binaryK_gemm_formats(). Default: None

  • carrier_rounding (RoundMode) – RoundMode.RO rounds the carrier’s steps to odd, as for mptorch.quant.superfp_matmul_fma(), for every pass of the layer; NAIVE only. Default: RoundMode.RNE

  • outer_exp_bits (int | None)

  • outer_normal_binades (int | None)

  • outer_bias (int | None)

  • outer_is_signed (bool | None)

  • outer_prng_bits (int)

  • outer_saturation_mode (SaturationMode | None)

Returns:

with the three *_math hooks set.

Return type:

QAffineFormats

Raises:

ValueError – as for superfp_gemm_formats().

Example:

>>> import torch
>>> from mptorch.quant import QLinear, superfp_gemm_formats_fma
>>> formats = superfp_gemm_formats_fma(3, 4, 8, 7)
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.binaryK_superfp_gemm_formats(mul_K, mul_P, acc_man_bits, acc_exp_bits, acc_normal_binades, acc_bias, *, mul_bias=None, mul_is_signed=True, mul_prng_bits=0, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, subnormals_mode=SubnormalsMode.SUBNORMALS, acc_saturation_mode=None, block_size=None, outer_man_bits=None, outer_exp_bits=None, outer_normal_binades=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, carrier=None)[source]#

Cross-family analog of binaryK_gemm_formats(): binaryK products, superfp sums.

The dot products run through mptorch.quant.ops.binaryK_superfp_matmul(), which documents every argument: products are rounded to the binaryK mul_* format and partial sums to the superfp acc_* format, which is required (an unrounded sum is binaryK_gemm_formats() with accumulate_quant=False). With BLOCK or TREE the outer format is a superfp one.

Returns:

with the three *_math hooks set.

Return type:

QAffineFormats

Raises:

ValueError – for a format no carrier can hold, or a carrier that is torch.float64 or names no carrier.

Parameters:

Example:

>>> import torch
>>> from mptorch.quant import QLinear, binaryK_superfp_gemm_formats
>>> formats = binaryK_superfp_gemm_formats(8, 4, 3, 4, 8, 7)
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.superfp_binaryK_gemm_formats(mul_man_bits, mul_exp_bits, mul_normal_binades, mul_bias, acc_K, acc_P, *, mul_is_signed=True, mul_prng_bits=0, acc_bias=None, acc_is_signed=None, acc_prng_bits=0, accumulate_algorithm=AccumulateAlgorithm.NAIVE, rounding_mode=RoundMode.RNE, saturation_mode=SaturationMode.SAT_NONE, acc_saturation_mode=None, acc_subnormals_mode=SubnormalsMode.SUBNORMALS, block_size=None, outer_K=None, outer_P=None, outer_bias=None, outer_is_signed=None, outer_prng_bits=0, outer_saturation_mode=None, outer_subnormals_mode=None, carrier=None)[source]#

Cross-family analog of superfp_gemm_formats(): superfp products, binaryK sums.

The dot products run through mptorch.quant.ops.superfp_binaryK_matmul(), which documents every argument: products are rounded to the superfp mul_* format and partial sums to the binaryK acc_* format, which is required (an unrounded sum is superfp_gemm_formats() with accumulate_quant=False). With BLOCK or TREE the outer format is a binaryK one.

Returns:

with the three *_math hooks set.

Return type:

QAffineFormats

Raises:

ValueError – for a format no carrier can hold, a normal_binades that leaves no supernormal codes, or a carrier that is torch.float64 or names no carrier.

Parameters:

Example:

>>> import torch
>>> from mptorch.quant import QLinear, superfp_binaryK_gemm_formats
>>> formats = superfp_binaryK_gemm_formats(3, 4, 8, 7, 16, 11)
>>> layer = QLinear(256, 64, formats=formats)
>>> layer(torch.randn(32, 256)).shape
torch.Size([32, 64])
mptorch.quant.conv_formats(mac, *, prec_idx=None, igrad_prec_idx=None, wgrad_prec_idx=None)[source]#

Build a QAffineFormats whose three convolution passes run in mac’s arithmetic.

The forward convolution, the input gradient and the weight gradient of a QConv1d, QConv2d or QConv3d each run in mac’s arithmetic. Every product and every addition of every dot product is rounded as a GEMM of that mac rounds it. The operands are gathered from the convolution’s tensors inside the kernel instead of being unfolded, so no pass allocates more than its result.

The forward pass and the weight gradient are each one GEMM, bit-identical to the GEMM of the same mac over F.unfold’s operands.

The input gradient is one GEMM per residue class of the stride, each over the kernel taps that reach its positions. A strided convolution’s gradient therefore costs what its forward pass does. A transposed convolution would cost stride**nd times more, because it sums the zeros it inserts. Under a NAIVE sum and a deterministic rounding the two are bit-identical, because adding a zero changes nothing there. Convolutions has the equations and says what differs in the other cases.

Any stride, padding ("same" and "valid" included), dilation and groups works. Groups share one launch. A depthwise convolution (one channel per group) uses a sixteenth of the kernel’s tile width, which is correct but not fast.

Like matmul_formats(), this sets only the math hooks. The caller adds operand quantization (weight_quant, input_quant and the other *_quant slots) separately.

The carrier is the GEMM’s: a float64 model rounds in binary64, and float32, float16 and bfloat16 ones in binary32, unless the mac names carrier=torch.float64. Then narrower operands are widened, each pass runs the binary64 kernels, and its result is narrowed back to their dtype, bit-identical to the pass on the widened operands. On MPS, which has no float64, binary32 is the only carrier.

Parameters:
  • mac (SplitMac | FusedMac | Number) – the dot-product arithmetic, resolved once through mptorch.quant.mac.spec_for_mac(). A bare Number means SplitMac(fmt, fmt). Every accumulate_algorithm applies, and a SplitMac may round its products and its sums in formats of two families, as for a GEMM. A palette selects the per-output-element ops, which need one map per pass.

  • prec_idx (Tensor | None) – the forward’s palette map, indexed like the output with its spatial dimensions flattened: [Cout, OUT] with OUT the number of output positions, [Cout, 1] (one format per output channel) or [1, OUT], optionally with a leading batch dimension. Required by, and only by, a palette mac. Default: None

  • igrad_prec_idx (Tensor | None) – the input gradient’s map, shaped the same way over [Cin, IN], with IN the number of input positions. The classes of a strided gradient read it at their own positions. Default: None

  • wgrad_prec_idx (Tensor | None) – the weight gradient’s map, over the weight as [Cout, Cin/groups * prod(kernel)], or [Cout, 1]. Default: None

Returns:

with fwd_math, bwd_igrad_math and bwd_wgrad_math set and every *_quant slot left None.

Return type:

QAffineFormats

Raises:

ValueError – for a palette mac without prec_idx, or a map given to a mac without a palette.

Example

Binary8p4 products summed in a 12-bit accumulator, with the operands also rounded to Binary8p4, for a strided layer. The backward pass runs both gradients in the same arithmetic:

>>> import torch
>>> from mptorch import AccumulateAlgorithm, BinaryK, RoundMode
>>> from mptorch.quant import FusedMac, QConv1d, QConv2d, Quant, SplitMac
>>> from mptorch.quant import conv_formats
>>> binary8p4 = BinaryK(8, 4)
>>> formats = conv_formats(SplitMac(binary8p4, BinaryK(12, 7)))
>>> formats.input_quant = formats.weight_quant = Quant(binary8p4)
>>> conv = QConv2d(3, 8, 3, stride=2, padding=1, formats=formats)
>>> x = torch.randn(2, 3, 16, 16, requires_grad=True)
>>> conv(x).sum().backward()
>>> x.grad.shape, conv.weight.grad.shape
(torch.Size([2, 3, 16, 16]), torch.Size([8, 3, 3, 3]))

Any mac: a fused multiply-add with Kahan summation under stochastic rounding, on a grouped, dilated 1D convolution:

>>> fma = FusedMac(BinaryK(12, 7, prng_bits=8), rounding=RoundMode.SR,
...                accumulate_algorithm=AccumulateAlgorithm.KAHAN)
>>> conv1d = QConv1d(4, 8, 3, dilation=2, groups=2, formats=conv_formats(fma))
>>> conv1d(torch.randn(1, 4, 20)).shape
torch.Size([1, 8, 16])

A palette, here one format per output channel of the forward (a [Cout, 1] map), and one per pass for the two gradients:

>>> pal = SplitMac([binary8p4, BinaryK(8, 5)], BinaryK(12, 7))
>>> per_channel = conv_formats(
...     pal,
...     prec_idx=torch.tensor([[0], [1]] * 4),
...     igrad_prec_idx=torch.zeros(3, 1, dtype=torch.int64),
...     wgrad_prec_idx=torch.zeros(8, 1, dtype=torch.int64),
... )
>>> QConv2d(3, 8, 3, padding=1, formats=per_channel)(torch.randn(1, 3, 6, 6)).shape
torch.Size([1, 8, 6, 6])
mptorch.quant.block_gemm_formats(input, weight, grad=None, *, acc=None, fused=False, rounding=RoundMode.RNE, accumulate_algorithm=AccumulateAlgorithm.NAIVE, block_size=None, outer=None, carrier=None, tensor_scale_epilogue=False)[source]#

Build a QAffineFormats whose three Linear GEMMs are block GEMMs.

Each hook packs what it multiplies along the dimension it sums over, in the format of the tensor’s role:

  • The forward product x @ w^T packs the input along its features in input’s format, and the weight along its input features in weight’s.

  • The input gradient g @ w packs the output gradient along its features in grad’s format (input’s by default), and the weight along its output features.

  • The weight gradient g^T @ x packs both along the batch.

The arithmetic (acc, fused, rounding, the accumulate algorithm) is that of mptorch.quant.block_matmul() and is shared by the three passes. Results are in the carrier (float32, or float64 in binary64), stored in the input’s dtype.

A weight that arrives already packed, from weight_quant = BlockQuant(fmt, axis=1).pack, is used as it is. It is then packed once per optimizer step instead of in each hook (the memo sees the step’s in-place write), and in inference only once.

With square tiles (dataclasses.replace(fmt, block_rows=fmt.block_size), NVFP4’s 16 x 16 weights) the input gradient reads that packing transposed, so the forward and backward passes see the same quantized weight. A 1D or non-square weight format quantizes differently along the other axis. A weight packed in such a format therefore raises in the input gradient. To train with one, leave weight_quant unset.

For inference, mptorch.quant.QLinear.freeze_packed_() replaces the layer’s float weight by its codes in weight’s format, and the layer then holds only those (mptorch.quant.QPackedLinear).

Parameters:
  • input (BlockFormat | BlockQuant) – the input’s format (a BlockQuant names its rounding and tensor scale).

  • weight (BlockFormat | BlockQuant) – the weight’s.

  • grad (BlockFormat | BlockQuant | None) – the output gradient’s. Default: None, input’s.

  • acc (BinaryK | None) – the accumulate format. Default: None

  • fused (bool) – a fused multiply-add per step. Default: False

  • rounding (RoundMode) – the sum’s rounding mode. Default: RoundMode.RNE

  • accumulate_algorithm (AccumulateAlgorithm) – as for mptorch.quant.SplitMac. Default: AccumulateAlgorithm.NAIVE

  • block_size (int | None) – BLOCK’s and TREE’s. Default: None

  • outer (BinaryK | None) – BLOCK’s and TREE’s outer format. Default: None

  • carrier (dtype | None) – torch.float64 packs and multiplies in binary64 whatever the layer’s dtype, as for mptorch.quant.BlockMac (a BlockQuant that names its own carrier keeps it). Default: None, the layer’s: binary64 for a float64 layer, binary32 otherwise.

  • tensor_scale_epilogue (bool) – apply the operands’ per-tensor scales to each GEMM’s result rather than in the decode, as NVIDIA’s NVFP4 GEMMs do (mptorch.quant.block_matmul()). Default: False

Returns:

with the three math hooks set and every *_quant slot left None.

Return type:

QAffineFormats

Example:

>>> import dataclasses, torch
>>> from mptorch import BinaryK, NVFP4
>>> from mptorch.quant import BlockQuant, QLinear, block_gemm_formats
>>> w16 = dataclasses.replace(NVFP4, block_rows=16)
>>> formats = block_gemm_formats(NVFP4, w16, acc=BinaryK(16, 11))
>>> formats.weight_quant = BlockQuant(w16, axis=1).pack
>>> layer = QLinear(64, 32, formats=formats)
>>> layer(torch.randn(8, 64)).sum().backward()