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
SaturationModeincsrc/common/modes.h, by name and value. Each member combines one of IEEE P3109’s three saturation modes with the format’s domain (seeDomain), 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 onlySatFinite. That leaves four valid combinations, one member each:SAT_FINITEis the finite domain, and the other three are the extended one.On a
BinaryKorSuperFPthe domain can be given withdomain=instead:saturation=SAT_FINITE, domain=Domain.EXTENDEDis stored asSAT_FINITE_EXTENDED. The flat*_quantizeand*_matmulfunctions 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
roundTowardZeronever 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_NONEandSAT_PROPAGATE. Every result beyond it, an infinite input included, clamps to it, as underSAT_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
SatFinitesaturation mode. ABinaryKorSuperFPtakes the domain asdomain=and folds it into itsSaturationModewhen it is built. If it is leftNone, it follows from the saturation mode: finite forSAT_FINITEand 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
eformats (Binary8p4se).- Type:
Has \(\pm\infty\)
- FINITE = 1#
the
fformats.- 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
SubnormalsModeincsrc/common/modes.h, by name and value. OnlySUBNORMALSis 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
xhas two candidates for its magnitude, zero and the smallest valuex_min, and the rounding mode picks between them:RoundMode.RNEandRoundMode.RNAtake the nearer one. On a tie,RNEtakes the zero andRNAtakesx_min.The directed modes take the candidate in their own direction.
RoundMode.ROtakesx_min, the nonzero candidate.RoundMode.SRtakesx_minwith 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
RoundModeincsrc/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
switchinside a GEMM’s accumulate step cost 1.2 to 2.3 times the kernel time.mptorch.quant.Quantandmptorch.quant.SplitMactherefore 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 spelledSR_A),SR_BandSR_C, which differ in how they read theprng_bitsrandom 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
- class mptorch.number.AccumulateAlgorithm(*values)[source]#
How the partial products of a dot product are folded into its sum.
Mirrors
AccumulateAlgorithmincsrc/common/modes.h, by name and value. It selects the reduction inside a custom-arithmetic GEMM (mptorch.quant.SplitMac,mptorch.quant.FusedMac, the flat*_matmulwrappers).Notation:
aandbare the two operands of one step, andsis the running sum.round_mulandround_accare the mac’s two roundings.round_accis the identity when there is no accumulate format. In a fused mac it is the fused format’s rounding, and the step isround_acc(fma(a, b, s))in place ofround_acc(s + round_mul(a * b)).round_outis the rounding of the mac’souterformat (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 iss.KAHAN: a compensationcis 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 iss. With no accumulate format this is Kahan’s summation in the carrier.BLOCK: theNAIVEstep runs on a block’s sums. After everyblock_sizeproducts, and after the last one, the block is added to a total,tot = round_out(tot + s), andsrestarts from zero. This gives two levels of precision: a narrow accumulate format inside a block, and a wider outer format across blocks. The result istot.TREE: the rounded productsp1, p2, ...of a block ofblock_size = 2**Lare 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 inBLOCK. 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.SRevery 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 tilesK, 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,BLOCKandTREEare 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) andBlockFormat(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.
BinaryKandSuperFPare its subclasses. A quantizer or GEMM factory that takes aFloatFormataccepts 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:
Ktotal bits of whichPare 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_signedanddomainare those four.BinaryK(8, 4)isBinary8p4se, andBinaryK(8, 4, domain=Domain.FINITE, saturation=SaturationMode.SAT_FINITE)isBinary8p4sf. The finite domain admits onlySAT_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.Quantandmptorch.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 derivedbiasis 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, soP - 1mantissa bits are stored;1 <= P <= K.bias (
int|None) – exponent bias. Default: P3109’s,2**(K-P-1)signed and2**(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 byRoundMode.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.FINITEadmits onlySAT_FINITE.Domain.EXTENDEDwithSAT_FINITEis stored asSaturationMode.SAT_FINITE_EXTENDED. Default:None, which follows fromsaturation: finite forSAT_FINITE, extended otherwise. The instance stores the resolved domain.subnormals (
SubnormalsMode) – what lies below the smallest normal. Any value other thanSUBNORMALSgives 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_bitsabove 52, an exponent field past 30 bits, a negativeprng_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 (seeFormatRangeWarning).TypeError – if
saturationis not aSaturationModeordomainis not aDomain.
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
- saturation: SaturationMode = 2#
- subnormals: SubnormalsMode = 0#
- 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.himplements it.The top
normal_binadesbinades of the exponent range keep a fullman_bits-bit mantissa. The remaining binades would have spentn = (2**exp_bits - normal_binades) * 2**man_bitscodes on mantissas. Those codes instead encode the zero andn - 1further 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:biasis 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
subnormalsmode, 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 most2**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 byRoundMode.SR. Default: 0.saturation (
SaturationMode) – overflow behaviour. Default:SaturationMode.SAT_NONE.domain (
Domain|None) – whether the top code is an infinity, as forBinaryK. Default:None, which follows fromsaturation.
- Raises:
ValueError – for the finite domain with a saturation mode other than
SAT_FINITE; for a format that neither carrier can simulate, as forBinaryK; and for anormal_binadesthat leaves no supernormal codes. Each call checks the format against its own carrier (seeFormatRangeWarning).
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]
- saturation: SaturationMode = 2#
- 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
SuperFPelements and scales. A tensor is split into blocks ofblock_sizeconsecutive elements along one axis, the packed axis. The functions that take a block format name that axis withaxis. Each block stores onescalecode andblock_sizeelement codes, and an element decodes to itselemvalue times its block’s scale.mptorch.quant.block_quantize()rounds a tensor to the format,mptorch.quant.block_pack()stores it inuint8codes, andmptorch.quant.block_matmul()multiplies two packed operands.The kind of
scaledecides 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 from2**-127to2**127, so the block scale is enough. The format has no tensor scale, andtensor_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**-9to 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 astensor_scale(its default is given below).tensor_scale=1.0leaves the block scales alone.scale=Nonestores the element codes unscaled.
A tensor scale without block scales is not available.
With
block_rows > 1a scale is shared by a tile ofblock_rowsconsecutive rows ofblock_sizeelements. 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
amaxbyscale_rounding(ScaleRounding). The defaults are:A power-of-two scale (
scale.P == 1, E8M0) is2**(floor(log2(amax)) - emax), clamped to its codes, whereemax = floor(log2(elem_max)). This is OCP MX’s rule.A
BinaryKscale with a mantissa (E4M3) isamax / (elem_max * tensor_scale)rounded to nearest even by the scale format’s cast. This is NVFP4’s rule.A
SuperFPscale 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 tensorx.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) underSaturationMode.SAT_FINITE. It is then clamped toelem_max.elem’s ownsaturationis not read; itssubnormalsandprng_bitsare.Special values. An infinite input saturates to
elem_max. A NaN input takesnan_codewhen 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=Noneand nonan_code) the NaN becomeselem_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 unlessnan_codeorinf_codesays 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 within2**-127 .. 2**127in binary32 and2**-1023 .. 2**1023in 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.Nonestores the element codes unscaled.block_size (
int) – elements per block along the packed axis. A power of two in [2, 128], withelem_bits * block_sizea multiple of 8.block_rows (
int) – rows per scale tile. A power of two in [1, 128], withblock_rows * block_size <= 16384; 1 without a scale. Default:1elem_max (
float|None) – the largest magnitude an element takes, a value ofelem. Default:None,elem’s largest finite value underSAT_FINITE.nan_code (
int|None) – the magnitude code (sign bit clear) that the element format spends on NaN, aboveelem_max’s. Default:Noneinf_code (
int|None) – the magnitude code it spends on infinity. It is decoded but never produced. Default:Nonescale_rounding (
ScaleRounding|None) – how a block’s scale is chosen.OCPneeds a power-of-two scale. AFOUR_OVER_SIXrule needs a cast scale. Default:None, the scale’s own rule:OCPfor a power-of-two scale,NEARESTfor a binaryK with a mantissa,SELECTIVEfor a superfp. The default is resolved against the scale each time the format is built, sodataclasses.replace(NVFP4, scale=SuperFP(...))takes the superfp’s rule.
These attributes are derived when the format is built and are read-only:
scale_rule: theScaleRoundingin effect (Nonewithout a scale). Formats compare by it, so leavingscale_roundingat its default and naming that default give equal formats.elem_bits: the bits per element code, sign included (elem.Kfor a binaryK,elem.wlfor 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**127for E8M0, 0 without a scale).top_scale: the scale that the default tensor scale gives the tensor’s largest block. It isscale_max, or under aFOUR_OVER_SIXrule the largest scalevfor whichv * elem_max / 2**emaxis 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_maxthat is not a value ofelem; anan_codeorinf_codeat or belowelem_max’s code; a power-of-two scale that is signed or reaches past2**-1023or2**1023(the pack multiplies by its reciprocal);scale_rounding=OCPon a cast scale; aFOUR_OVER_SIXrule on a power-of-two scale; or anyscale_roundingwithout a scale.TypeError – if
elemorscaleis not aBinaryKor aSuperFP.
- 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#
- class mptorch.number.FixedPoint(wl, fl, *, is_signed=True, symmetric=False, prng_bits=0)[source]#
A fixed-point format:
wlbits, of whichflare 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**-flthat awl-bit integer holds: withn = wl - 1magnitude bits in a signed format andn = wlin 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]withsymmetric, and[0, 2**(n - fl) - 2**-fl]unsigned.flmay be any integer: negative for a step coarser than 1, abovewlfor a format of pure fractions.Every
RoundModeapplies, as forBinaryK. Below the step the two candidates are zero and2**-fl, picked asSubnormalsModedescribes. 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 nosaturationfield. 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 reasonBinaryKis.- Parameters:
wl (
int) – word length, the sign bit included; at least 2 signed and 1 unsigned.fl (
int) – fractional length; the step between values is2**-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 byRoundMode.SRbelow the step, ignored under every other rounding mode. Default: 0.
- Raises:
ValueError – for a
wltoo short, a symmetric unsigned format, a negativeprng_bits, or what binary64 cannot simulate: more than 52 magnitude bits, with or withoutprng_bits, a largest value below its normals, or a range reaching its top binade. Each call checks the format against its own carrier (seeFormatRangeWarning).
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
- 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.quantwarn 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
BinaryKwithSubnormalsMode.SUBNORMALSand for aSuperFP. 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
BinaryKwithSubnormalsMode.NORMALSorSubnormalsMode.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 = 1underNORMALS, andEXTENDED_NORMALSat the carrier’s full precision (P = 24,P = 53).
Formats and rounding (“What the carrier can hold”) derives both.
BinaryKandSuperFPdo 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 andbits - 1magnitude bits, one step of2**-(bits - 2)from zero to the largest value,2 - 2**-(bits - 2), soemaxis 0 and a block’s E8M0 scale is2**floor(log2(amax)), OCP’s rule. Any otherflgives the same block values and only movesemax; build theBlockFormatdirectly for one.bfp(8, 32)is OCP’s MXINT8 but for one code: MXINT8’s elements are two’s complement, and-2has no sign-magnitude code. The block GEMM takes element codes of up to 8 bits;bfp(9)tobfp(16)pack, unpack and quantize only.- Parameters:
- Return type:
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
xto 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 hasKbits in total.Pof them are precision (P - 1stored mantissa bits plus the implicit one), andK - Pare exponent bits (K - P + 1whenis_signedis false, because there is no sign bit). Passbiasexplicitly for a format outside P3109. The layouts of the OCP 8-bit formats areK=8, P=4, bias=7(E4M3) andK=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 ofRoundMode.SRare drawn in the carrier too, soP - 1 + prng_bitsis 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_FINITEandSAT_FINITE_EXTENDED(P3109’sSatFinitein 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.Quantis 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 - 1stored mantissa bits plus the implicit one.bias (
int|None) – the exponent bias. Default:None, which is P3109’s2**(K - P - 1)signed and2**(K - P)unsigned, one more than IEEE 754 gives the same exponent width.prng_bits (
int) – random bitsRoundMode.SRdraws below the target mantissa; ignored by every other mode. Default:0is_signed (
bool) – whether the format has a sign bit. Default:Truerounding_mode (
RoundMode) – how a value between two of the format’s is rounded. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – what a value past the largest finite one becomes. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – how the bottom of the range is filled in. Default:SubnormalsMode.SUBNORMALScarrier (
dtype|None) –torch.float64rounds anyxin binary64. A narrowerxis widened first, and the result is narrowed back to its dtype with one rounding.torch.float32names binary32. A float64xrefuses 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:
- Raises:
ValueError – if the carrier cannot hold the format (precision above the carrier’s,
P - 1 + prng_bitsabove its mantissa bits, an exponent field past 30 bits, no finite normal value), or ifcarrieris a dtype that names no carrier or is narrower thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires 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
xto a superfp (supernormal) format.The format has
man_bitsstored mantissa bits andexp_bitsexponent bits, but only the topnormal_binadesbinades 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 nosubnormals_mode.biasis required, because the format has no default rule for it. Seemptorch.SuperFP.Dtypes, the carrier, the storage check,
prng_bitsand differentiability are as forbinaryK_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 bitsRoundMode.SRdraws below the target mantissa; ignored by every other mode. Default:0is_signed (
bool) – whether the format has a sign bit. Default:Truerounding_mode (
RoundMode) – how a value between two of the format’s is rounded. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – what a value past the largest finite one becomes. Default:SaturationMode.SAT_NONEcarrier (
dtype|None) – as forbinaryK_quantize(). Default:None,x’s own carrier.
- Returns:
a new tensor of
x’s shape and dtype holding the rounded values.- Return type:
- Raises:
ValueError – if the carrier cannot hold the format (precision above the carrier’s,
man_bits + prng_bitsabove its mantissa bits, an over-wide exponent field, anormal_binadesthat leaves no supernormal code, no finite normal value), or ifcarrieris a dtype that names no carrier or is narrower thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires 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=7the 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
xto a fixed-point format.The format holds the multiples of the step
2**-flthat awl-bit integer holds:[-2**(wl - 1 - fl), 2**(wl - 1 - fl) - 2**-fl]in two’s complement, one step narrower at the bottom withsymmetric, and[0, 2**(wl - fl) - 2**-fl]unsigned (seemptorch.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 nosaturation_mode. NaN inputs pass through.Dtypes, the carrier, the storage check,
prng_bitsand differentiability are as forbinaryK_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 is2**-fl.prng_bits (
int) – random bitsRoundMode.SRdraws below the step; ignored by every other mode. Default:0is_signed (
bool) – whether the format has a sign bit. Default:Truesymmetric (
bool) – drop the most negative code, so the range is symmetric about zero; signed formats only. Default:Falserounding_mode (
RoundMode) – how a value between two of the format’s is rounded. Default:RoundMode.RNEcarrier (
dtype|None) – as forbinaryK_quantize(). Default:None,x’s own carrier.
- Returns:
a new tensor of
x’s shape and dtype holding the rounded values.- Return type:
- 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 (wltoo short, a symmetric unsigned format, negativeprng_bits), or ifcarrieris a dtype that names no carrier or is narrower thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires 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=4the 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
xto 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 overx. That includesRoundMode.SRwith 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 ownsx: 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 leavexunchanged: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.float64on 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 andcarrierarebinaryK_quantize()’s.carrier (
dtype|None) –Noneor the carrierxalready has (torch.float32for float32, float16 and bfloat16,torch.float64for float64). Default:NoneK (int)
P (int)
bias (int | None)
prng_bits (int)
is_signed (bool)
rounding_mode (RoundMode)
saturation_mode (SaturationMode)
subnormals_mode (SubnormalsMode)
- Returns:
xitself, holding the rounded values.- Return type:
- Raises:
ValueError – as for
binaryK_quantize(), and ifcarrieris wider thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires 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
xto a superfp format, in place.This is the in-place spelling of
superfp_quantize(): the same arguments, checks and result, written overx, with no output allocation. Its purpose and the inputs it refuses are the same as forbinaryK_quantize_(): a tensor that is not contiguous, a CUDA view off a 16-byte boundary, and acarrierwider thanx.- Parameters:
x (
Tensor) – the tensor to round and overwrite; float32, float64, float16 or bfloat16, contiguous. The format and mode arguments between it andcarrieraresuperfp_quantize()’s.carrier (
dtype|None) –Noneor the carrierxalready has. Default:Noneman_bits (int)
exp_bits (int)
normal_binades (int)
bias (int)
prng_bits (int)
is_signed (bool)
rounding_mode (RoundMode)
saturation_mode (SaturationMode)
- Returns:
xitself, holding the rounded values.- Return type:
- Raises:
ValueError – as for
superfp_quantize(), and ifcarrieris wider thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires 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
xto a fixed-point format, in place.The in-place spelling of
fixedpoint_quantize(): the same arguments, checks and result, written overx, 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, acarrierwider thanx) are as forbinaryK_quantize_().- Parameters:
x (
Tensor) – the tensor to round and overwrite; float32, float64, float16 or bfloat16, contiguous. The format and mode arguments between it andcarrierarefixedpoint_quantize()’s.carrier (
dtype|None) –Noneor the carrierxalready has. Default:Nonewl (int)
fl (int)
prng_bits (int)
is_signed (bool)
symmetric (bool)
rounding_mode (RoundMode)
- Returns:
xitself, holding the rounded values.- Return type:
- Raises:
ValueError – as for
fixedpoint_quantize(), and ifcarrieris wider thanx.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
xrequires grad under grad mode, is not contiguous, or is a CUDA view off a 16-byte boundary.
- 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
*_quantslot of aQAffineFormatsorQMatmulFormatstakes one, and a straight-throughmptorch.quant.Quantizeror a QAT observer wraps one. The call is bound at construction, so each call costs only the op. The class is frozen, so aQuantcan be a dictionary key and a memoization key, like the mac objects.- Parameters:
fmt (
Number) – the format to round to: amptorch.BinaryK, amptorch.SuperFP, amptorch.FixedPoint, or amptorch.BlockFormat. A block format’s blocks run along the last axis; useBlockQuantfor another axis or a tensor scale.rounding (
RoundMode) – the rounding mode. Default:RoundMode.RNEcarrier (
dtype|None) – the float arithmetic the cast rounds in, as the argument of the same name ofmptorch.quant.binaryK_quantize().Nonerounds in the tensor’s own default carrier: binary32 for float16, bfloat16 and float32 tensors, and binary64 for float64 ones.torch.float64rounds in binary64 whatever the tensor.torch.float32rounds in binary32 and refuses a float64 tensor. Default:Noneinplace (
bool) – round the tensor in place and return it, instead of allocating a result. This goes throughmptorch.quant.binaryK_quantize_(),mptorch.quant.superfp_quantize_()ormptorch.quant.fixedpoint_quantize_(). Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a*_quantslot 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 acarrierwider than the tensor. Default:False
- Raises:
TypeError – for a format with no elementwise quantizer, or a
carrierthat is not atorch.dtype.ValueError – for a
carrierdtype 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.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 reachesxisbackward_quant(grad). A direction whose quantizer isNoneis left alone. Because it is annn.Module, it can sit in any*_quantslot of aQAffineFormatsorQMatmulFormatsand 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 amptorch.quant.Quantwith round-to-nearest-even. AnyTensor -> Tensorcallable is used as it is.Noneleaves the forward pass alone. Default:Nonebackward_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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
Block quantizers#
- mptorch.quant.block_quantize(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#
Round
xto a block format alongaxisand return the decoded values.This is
block_pack()andblock_unpack()fused, with no packed intermediate. It is the fake quantizer that a*_quantslot of a layer’s formats takes, andmptorch.quant.BlockQuantis its value spelling. The arguments are those ofblock_pack(), and the result hasx’s shape, dtype and layout. The function is not differentiable: wrap it inmptorch.quant.Quantizerfor 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])
- mptorch.quant.block_quantize_(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#
block_quantize(), written overxin place; returnsx.Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a
*_quantslot, because a layer’s input belongs to the graph of whatever produced it.xmust have no overlapping elements. A tensor of rank 4 or more must be able to fold its leading dimensions as a view withaxismoved last. The out-of-place op has neither restriction. The result equals that ofblock_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
- mptorch.quant.block_pack(x, fmt, axis=-1, *, rounding=RoundMode.RNE, tensor_scale=None, carrier=None)[source]#
Round
xto a block format alongaxisand store it packed.Each run of
fmt.block_sizeconsecutive elements alongaxisshares one scale. For a 2D format the run also spansfmt.block_rowsrows along the axis before it. The scale is chosen from the block’s values asmptorch.BlockFormatdescribes. Each element is then divided by the scale and rounded to the element format inrounding. The result stores the codes, which take a quarter to an eighth of float32’s bytes;BlockPackeddescribes the layout. A transposed view is packed without a copy, and so is anyaxis, because the kernel readsxthrough its strides.Under
RoundMode.SRan element’s random bits are keyed on its index in the packed orientation (the tensor withaxismoved 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:-1rounding (
RoundMode) – the elements’ rounding mode. The scale is always chosen by the format’s rule. Default:RoundMode.RNEtensor_scale (
float|None) – the per-tensor scale of a format whose block scale has a mantissa (NVFP4).Nonetakesmax(|x|) / (elem_max * top_scale), which readsxonce more and, on a GPU, synchronizes with it. Default:Nonecarrier (
dtype|None) – the arithmetic the rounding runs in:torch.float64packs anyxin binary64, widening a narrower one first (the default tensor scale is then a float64 quotient), andtorch.float32names binary32, which a float64xrefuses. Default:None,x’s own: binary64 for float64, binary32 otherwise.
- Returns:
the codes, the scales and what describes them.
- Return type:
- Raises:
ValueError – for a format the carrier does not hold (
mptorch.number.check_block_carrier()),carrier=torch.float32on a float64x, or atensor_scalegiven 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
BlockPackedinto 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 onepwas packed in, or binary64 whendtypeis float64 orcarrier=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 throughnarrow_float64), andmptorch.FormatRangeWarningreports it.block_unpack(block_pack(x, fmt, axis))equalsblock_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 dtypepwas packed from.carrier (
dtype|None) –torch.float64decodes in binary64;torch.float32refuses appacked in binary64 and a float64dtype. Default:None,p’s carrier, or binary64 for a float64dtype.
- Returns:
the decoded values, of shape
p.shape(a view with the packed axis moved back into place).- Return type:
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:uint8codes 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,axisanddtype: the logical tensor’s shape, the axis it was packed along, and the dtype it was packed from, whichunpack()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) ortorch.float64(binary64).unpack()andblock_matmul()decode it in that carrier or a wider one. It defaults todtype’s: binary64 for float64, binary32 otherwise.
mTis the logical transpose of the last two dimensions. It reads the same codes the other way: nothing is copied, and onlyshapeandaxischange. This letsblock_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 mT: BlockPacked#
The logical transpose of the last two dimensions, without a copy.
- unpack(dtype=None)[source]#
block_unpack()of this tensor.
- 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()alongaxis. It returns the decoded values, with the tensor’s shape and dtype. That is what a*_quantslot of a layer’s formats or amptorch.quant.Quantizertakes.pack()ismptorch.quant.block_pack()instead. It returns the codes themselves, whichmptorch.quant.block_gemm_formats()andmptorch.quant.block_matmul_formats()multiply without decoding them first. UseBlockQuant(fmt, axis=1).packas aQLinear’sweight_quantto 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.RNEaxis (
int) – the axis the blocks run along. Default:-1tensor_scale (
float|None) – a static per-tensor scale, for a format that has one (NVFP4).Nonederives it per call. Default:Nonecarrier (
dtype|None) – as formptorch.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#
- pack(x, axis=None)[source]#
mptorch.quant.block_pack()ofxalongaxis, memoized onx, its version, its device and its dtype.axisdefaults to this quantizer’s.- Return type:
- Parameters:
- pack_fresh(x, axis)[source]#
mptorch.quant.block_pack()ofxalongaxis, not memoized. Use it for an activation or a gradient, which is a new tensor on every call.- Return type:
- 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:
SplitMacandFusedMac, 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_quantandfma_quantstop 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
Numberor a sequence of them, and a sequence anywhere selects the_mixedop and requires aprec_idx; op choice is a table keyed on(family, mac kind, is palette)rather than eight function names. ASplitMacwhose 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
*_quantslot of aQAffineFormatsorQMatmulFormatstakes one, and a straight-throughmptorch.quant.Quantizeror a QAT observer wraps one. The call is bound at construction, so each call costs only the op. The class is frozen, so aQuantcan be a dictionary key and a memoization key, like the mac objects.- Parameters:
fmt (
Number) – the format to round to: amptorch.BinaryK, amptorch.SuperFP, amptorch.FixedPoint, or amptorch.BlockFormat. A block format’s blocks run along the last axis; useBlockQuantfor another axis or a tensor scale.rounding (
RoundMode) – the rounding mode. Default:RoundMode.RNEcarrier (
dtype|None) – the float arithmetic the cast rounds in, as the argument of the same name ofmptorch.quant.binaryK_quantize().Nonerounds in the tensor’s own default carrier: binary32 for float16, bfloat16 and float32 tensors, and binary64 for float64 ones.torch.float64rounds in binary64 whatever the tensor.torch.float32rounds in binary32 and refuses a float64 tensor. Default:Noneinplace (
bool) – round the tensor in place and return it, instead of allocating a result. This goes throughmptorch.quant.binaryK_quantize_(),mptorch.quant.superfp_quantize_()ormptorch.quant.fixedpoint_quantize_(). Use it for a tensor the caller owns, such as a weight quantized once at load. Never use it in a*_quantslot 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 acarrierwider than the tensor. Default:False
- Raises:
TypeError – for a format with no elementwise quantizer, or a
carrierthat is not atorch.dtype.ValueError – for a
carrierdtype 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
_mixedops take the palette’s widths as a table, and aprec_idxmap picks one entry per output element. A plain sequence of formats works anywhere aPalettedoes 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 toMAX_PALETTEformats, 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 themulformat and the new partial sum to theaccformat.mulandaccare each a format or a sequence of formats. A sequence is a palette; it selects the_mixedop and requires aprec_idxat the call.accalone may also beNone, which leaves the running sum in the carrier’s full precision. The two may be of different families, aBinaryKmultiply with aSuperFPaccumulate 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.roundingis 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;Noneleaves the running sum unrounded. Default:Nonerounding (
RoundMode) – rounding mode of both halves. Default:RoundMode.RNEaccumulate_algorithm (
AccumulateAlgorithm) – how the products are summed.NAIVEis the step above, in order.KAHANcarries a compensation term next to the sum, in theaccformat.BLOCKruns the step above over blocks ofblock_sizeproducts and adds each block’s sum to a total with a third rounding,outer.TREEsums each block’s products pairwise, rounding every pair’s sum toacc, and adds the block’s root to the total in the same way.mptorch.AccumulateAlgorithmstates each precisely.KAHAN,BLOCKandTREErun in both carriers; a palette in any slot raises. Default:AccumulateAlgorithm.NAIVEcarrier (
dtype|None) – the float arithmetic that both halves and everything between them are computed in, as the argument of the same name ofmptorch.quant.binaryK_matmul().Nonetakes the operands’ carrier (binary64 for float64, binary32 for the rest).torch.float64widens narrower operands to binary64 and narrows the result back to their dtype.torch.float32refuses float64 operands. Every call checks the formats against that carrier. Default:Noneblock_size (
int|None) – products per block.BLOCKrequires one, which must divide 16 or be a multiple of 16.TREEtakes a power of two in [2, 256] and defaults to 16.NAIVEandKAHANtake none. Default:Noneouter (
Number|None) – the format, of the accumulate format’s family (the multiply’s whenaccisNone), thatBLOCKandTREEround the total to after each block is added.Noneleaves the total in the carrier’s precision, asacc=Nonedoes for the sum. When given, the result holds this format’s values. Default:Nonecarrier_rounding (
RoundMode) – how the carrier rounds the product and the sum before the formats do.RoundMode.RNEis the carrier’s nearest multiply and add.RoundMode.ROrounds 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:Pat most 22 underRNEandRNA, 23 under the directed modes andRO, andP + prng_bitsat most 23 underSR, in binary32 (51, 52 and 52 in binary64); a call outside those raises.ROis implemented forNAIVE, one format per slot and one family, on CPU and CUDA tensors. Withacc=Noneonly the product is rounded to odd, since no format rounds the sum after it. Default:RoundMode.RNE
- Raises:
ValueError – if
mulisNone, if both slots are palettes of different lengths, ifmulandaccare of different families and either is a palette, ifcarriernames no carrier, ifblock_sizeorouterdoes not fit the algorithm, or ifcarrier_roundingis neitherRNEnorROor isROwith something it does not implement.TypeError – if
outeris of another family than the accumulate format or not a single format, orcarrieris not atorch.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 whereSplitMachas two. The carrier’s FMA roundss + a * bto nearest before the format does, unlesscarrier_rounding=RoundMode.RO.fmais a format, a palette, orNone.Nonegives an unrounded fused step: the carrier’s own FMA, in order. It has no format forprec_idxto select, so it never selects a_mixedop.- Parameters:
fma (
Number|Sequence[Number] |Palette|None) – the format each fused step is rounded to, a palette of them, orNone.rounding (
RoundMode) – rounding mode of the fused step. Default:RoundMode.RNEaccumulate_algorithm (
AccumulateAlgorithm) – as forSplitMac, with the fused step in place of the split one.TREEraises, because a fused multiply-add has no product term to sum pairwise. Default:AccumulateAlgorithm.NAIVEouter (
Number|None) – as forSplitMac. Withfma=Noneit may be of either family. Default:Nonecarrier_rounding (
RoundMode) – as forSplitMac, for the fused step’s one carrier rounding.RoundMode.ROneeds a format (fma=Noneraises). Default:RoundMode.RNE
- Raises:
ValueError – if
carriernames no carrier, a palette is invalid,block_sizeorouterdoes not fit the algorithm, orcarrier_roundingdoes not fit the mac.TypeError – if
carrieris not atorch.dtype, orouteris 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()alongaxis. It returns the decoded values, with the tensor’s shape and dtype. That is what a*_quantslot of a layer’s formats or amptorch.quant.Quantizertakes.pack()ismptorch.quant.block_pack()instead. It returns the codes themselves, whichmptorch.quant.block_gemm_formats()andmptorch.quant.block_matmul_formats()multiply without decoding them first. UseBlockQuant(fmt, axis=1).packas aQLinear’sweight_quantto 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.RNEaxis (
int) – the axis the blocks run along. Default:-1tensor_scale (
float|None) – a static per-tensor scale, for a format that has one (NVFP4).Nonederives it per call. Default:Nonecarrier (
dtype|None) – as formptorch.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()ofxalongaxis, memoized onx, its version, its device and its dtype.axisdefaults to this quantizer’s.- Return type:
- Parameters:
- pack_fresh(x, axis)[source]#
mptorch.quant.block_pack()ofxalongaxis, not memoized. Use it for an activation or a gradient, which is a new tensor on every call.- Return type:
- 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.
aandbare the formats that the left and right operands are packed in. Each is amptorch.BlockFormat(packed to nearest even) or aBlockQuant(which specifies the rounding and a tensor scale).bdefaults toa.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 toacc. Withfused=True, each fused multiply-add is rounded toacc.acc=Noneleaves the sum in the carrier. The accumulate algorithms are those ofSplitMac.mptorch.quant.qmatmul()andmptorch.quant.QMatmulaccept aBlockMac(mptorch.quant.block_matmul_formats()builds their formats). They also accept a bareBlockFormat, which meansBlockMac(fmt).- Parameters:
a (
BlockFormat|BlockQuant) – the left operand’s format.b (
BlockFormat|BlockQuant|None) – the right operand’s. Default:None,a’s.fused (
bool) – a fused multiply-add per step. Default:Falserounding (
RoundMode) – the sum’s rounding mode. Default:RoundMode.RNEaccumulate_algorithm (
AccumulateAlgorithm) – as forSplitMac(TREEneedsfused=False). Default:AccumulateAlgorithm.NAIVEcarrier (
dtype|None) –torch.float64packs the operands and multiplies them in binary64, whatever their dtype (an operandBlockQuantthat names a carrier of its own keeps it). Default:None, the operands’: binary64 for float64 tensors, binary32 otherwise.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: plaintorch.matmul, which is what an A/B against unquantized arithmetic wants;a
Number(BinaryK(8, 4)): shorthand forSplitMac(mul=fmt, acc=fmt), the common case where one format is used for both halves of the dot product, and for aBlockFormat,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 requiringprec_idx, and acarrierchoosing the float arithmetic it is computed in (binary64 for any operands withtorch.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, astorch.mmis.- Parameters:
- Returns:
the
[M, N]product.- Return type:
- 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, astorch.bmmis.There is no broadcasting: both batch dimensions must be equal.
torch.bmmmakes this check andqmatmuldoes not.- Parameters:
- Returns:
the
[B, M, N]batch of products.- Return type:
- 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 arithmeticformatsnames.It accepts everything
torch.matmulaccepts: 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’scarrierasks 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 intoM, 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(plaintorch.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 theagrad_prec_idxandbgrad_prec_idxarguments ofmptorch.quant.matmul_formats()for those. Default:None
- Returns:
a @ bin the operands’ dtype, withtorch.matmul’s output shape.- Return type:
- Raises:
ValueError – for a palette without
prec_idx, aprec_idxwith no palette, or acarriernarrower than the operands.TypeError – for a
formatsvalue 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
formatsto aQMatmulFormats.The four spellings listed in the module docstring are told apart here and nowhere else, so
qmatmul()andmptorch.quant.QMatmulaccept exactly the same values.- Parameters:
- Returns:
formatsitself if it already was one, an emptyQMatmulFormats()forNone, or the memoized one for a mac.- Return type:
- Raises:
ValueError – for a
prec_idxgiven withNone(nothing to select from) or with aQMatmulFormats(whose maps were bound bymptorch.quant.matmul_formats()).TypeError – for any other
formatsvalue.
- 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.
QMatmulandmptorch.quant.qmatmul()read this container. Its slots mirror those ofQAffineFormats, renamed for an op whose two operands play the same role:a/binstead of input/weight, and one gradient quantizer per operand, because the two gradient GEMMs may need different formats. Every slot is optional, andNonemeans plain PyTorch. AQMatmulFormats()with nothing set computestorch.matmuland 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’sstate_dict.The
recompute_*flags areQAffineFormats’ for the two operands: keepa(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 toain the forward. Default:Noneb_quant (
Callable|None) – applied tobin the forward. Default:Noneagrad_quant (
Callable|None) – applied to the output gradient beforea’s gradient GEMM. Default:Nonebgrad_quant (
Callable|None) – applied to the output gradient beforeb’s gradient GEMM. Default:Nonefwd_math (
Callable|None) –fwd_math(q_a, q_b) -> a @ b. Default:Nonebwd_agrad_math (
Callable|None) –bwd_agrad_math(q_grad, q_b) -> grad @ b^T. Default:Nonebwd_bgrad_math (
Callable|None) –bwd_bgrad_math(q_grad, q_a) -> a^T @ grad. Default:Nonerecompute_a (
bool|None) – keeparaw for backward and runa_quanton it again there.Nonekeeps the copy. Set it where something else keepsaalive, as attention’s softmax keeps the probabilities that multiplyV.Trueruns any callable again, as forQAffineFormats. Default:Nonerecompute_b (
bool|None) – the same forbandb_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.matmulwith the arithmetic of oneQMatmulFormats.This is the module form of
mptorch.quant.qmatmul(). LikeQLinear, it is a module because its formats are one: aQMatmulFormatsis annn.Module, so a quantizer that carries state (a QAT observer) is registered in the parent model’sstate_dictwhen 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_bsay 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 bymptorch.quant.matmul.as_matmul_formats(). Default:None(plaintorch.matmul)
- Shape:
Input:
aandbin any shapestorch.matmulaccepts.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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- mptorch.quant.matmul_formats(mac, *, prec_idx=None, agrad_prec_idx=None, bgrad_prec_idx=None)[source]#
Build a
QMatmulFormatswhose three passes run inmac’s arithmetic.The forward product
a @ b,a’s gradientgrad @ b^Tandb’s gradienta^T @ gradeach run through the GEMM op thatmacresolves to.A palette in any of
mac’s slots selects the per-output-element op, which needs oneprec_idxmap 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_formatsfactories, 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 throughmptorch.quant.mac.spec_for_mac().prec_idx (
Tensor|None) – integer map selecting a palette entry per element of the forward’s output, shaped likea @ b([M, N],[M, 1]or[1, N], optionally batched). Required by, and only by, a palettemac. Default:Noneagrad_prec_idx (
Tensor|None) – the map fora’s gradient, shaped likegrad @ b^T. Default:Nonebgrad_prec_idx (
Tensor|None) – the map forb’s gradient, shaped likea^T @ grad. Default:None
- Returns:
with
fwd_math,bwd_agrad_mathandbwd_bgrad_mathset and every*_quantslot leftNone.- Return type:
- Raises:
ValueError – if
macholds a palette andprec_idxisNone, or if a map is given for amacwith 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 @ bof their logical values.ais logically[..., M, K]andbis[..., K, N]. The kernel decodes each element as it loads it (its value times its block’s scale, asblock_unpack()would) and multiplies in the carrier: binary64 whencarrier=torch.float64or 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 toacc. A fused mac rounds each fused multiply-add toacc.acc=Noneleaves the sum in the carrier.Each operand is read along K. It may be packed along its K (
aalong its last axis,balong its second-to-last) or along its other dimension, which the kernel reads transposed. One packed weight therefore serves bothx @ w.Tandg @ w;BlockPacked.mTis 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: seemptorch.quant.qmatmul()with amptorch.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=Truedoes 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.fused (
bool) – one rounding per step (a fused multiply-add) instead of two. Default:Falserounding (
RoundMode) – the rounding mode of the sum. Default:RoundMode.RNEaccumulate_algorithm (
AccumulateAlgorithm) – as formptorch.quant.SplitMac. Default:AccumulateAlgorithm.NAIVEblock_size (
int|None) – BLOCK’s and TREE’s block size. Default:Noneouter (
BinaryK|None) – BLOCK’s and TREE’s outer format. Default:Nonecarrier (
dtype|None) –torch.float64multiplies in binary64;torch.float32refuses 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:
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
QMatmulFormatswhose three passes are block GEMMs.Each pass packs its operands along the dimension it sums over:
The forward product
a @ bpacksaalong its last dimension andbalong its second-to-last (their K), inmac’s two formats.a’s gradientgrad @ b^Tpacksgradalong its last dimension andbalong its last.b’s gradienta^T @ gradpacksaalong its second-to-last dimension andgradalong its second-to-last.
A gradient pass takes the formats of the slots it fills from
agrad_mac/bgrad_mac, which default tomac. An operand whose format has square tiles is packed once, by thea_quant/b_quantslot that this function sets for it. The gradient passes read that packing throughmptorch.quant.BlockPacked.mT. Each pass’s result is in the carrier (float32, or float64 in binary64), stored in the operands’ dtype.- Parameters:
- Returns:
the three math hooks, and
a_quant/b_quantfor square-tiled operands.- Return type:
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), whereop(x) = x.Twhen the correspondingtrans_*flag is set, andop(x) = xotherwise. This is not the same as quantizingaandband then callingtorch.matmul. It quantizes the arithmetic of each dot product. Every partial product is rounded to the binaryK format given bymul_K/mul_P. Whenaccumulate_quantis true, the running sum is rounded to the format given byacc_K/acc_Pafter every accumulation step. Withaccumulate_quant=Falsethe 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().aandbfollowtorch.matmul’s operand rules: 1D operands are promoted (and their dimension is dropped from the result), leading dimensions broadcast against each other, andtrans_a/trans_bapply 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 intoMas a view.
The two shapes that a quantized attention block uses are covered by these. Under
RoundMode.SReach 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, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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’s2**(K - P - 1)signed and2**(K - P)unsigned.mul_is_signed (
bool) – whether the multiply format has a sign bit. Default:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding, asbinaryK_quantize()’sprng_bits. Default:0accumulate_quant (
bool) – whether the running sum is rounded to the accumulate format after every step. Default:Trueacc_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 foracc_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 bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed.NAIVEis the step above, in order.KAHANcarries a compensation term next to the sum, rounded to the accumulate format.BLOCKruns the step above over blocks ofblock_sizeproducts and adds each block’s sum to a total, which the outer format rounds.TREEsums 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.AccumulateAlgorithmstates each precisely. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of both formats. There is one mode per op, because the kernel is instantiated on it. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply format’s overflow behavior. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – the multiply format’s bottom of range. Default:SubnormalsMode.SUBNORMALSacc_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.BLOCKrequires one, which must divide 16 or be a multiple of 16 (the kernels count in slabs of 16 steps).TREEtakes a power of two in [2, 256] and defaults to 16.NAIVEandKAHANtake none. Default:Noneouter_K (
int|None) – width of the outer format. This is the rounding thatBLOCKandTREEapply to the total after each block is added.None(withouter_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:Noneouter_P (
int|None) – precision of the outer format; given together withouter_K. Default:Noneouter_bias (
int|None) – exponent bias of the outer format. Default:None, P3109’s forouter_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 bitsRoundMode.SRdraws for the outer rounding. Default:0outer_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 forbinaryK_quantize().torch.float64widens narrower operands to binary64 and narrows the result back to their dtype with one rounding.torch.float32refuses float64 operands. Default:None, the operands’ own carrier.carrier_rounding (
RoundMode) – how the carrier rounds each product and sum before the formats do.RoundMode.RNEis the carrier’s nearest multiply and add, which the directed modes can then round to the wrong neighbour.RoundMode.ROrounds them to odd, so each format rounds the exact product and the exact sum, for formats withPat most 22 underRNE/RNA, 23 under the directed modes andRO, andP + prng_bitsat most 23 underSRin binary32 (51, 52 and 52 in binary64); a call outside those raises.ROruns thecustom_matmul_*_oddops: NAIVE only, on CPU and CUDA tensors. Withaccumulate_quant=Falseonly 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.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold a format (as for
binaryK_quantize()), ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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 bymul_man_bits,mul_exp_bits,mul_normal_binadesandmul_bias. Whenaccumulate_quantis true, the running sum is rounded to theacc_*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, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding. Default:0accumulate_quant (
bool) – whether the running sum is rounded to the accumulate format after every step. Default:Trueacc_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 bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – as forbinaryK_matmul(). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of both formats. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply format’s overflow behavior. Default:SaturationMode.SAT_NONEacc_saturation_mode (
SaturationMode|None) – the accumulate format’s overflow behavior. Default:None,saturation_mode.block_size (
int|None) – as forbinaryK_matmul(). Default:Noneouter_man_bits (
int|None) – mantissa bits of the outer format, the roundingBLOCKandTREEapply to the total after each block is folded in (binaryK_matmul()’souter_K). The four widths are given together, or none of them, which leaves the total in the carrier’s precision. Default:Noneouter_exp_bits (
int|None) – exponent bits of the outer format. Default:Noneouter_normal_binades (
int|None) – normal binades of the outer format. Default:Noneouter_bias (
int|None) – exponent bias of the outer format. Default:Noneouter_is_signed (
bool|None) – whether the outer format has a sign bit. Default:None, the accumulate format’s.outer_prng_bits (
int) – random bitsRoundMode.SRdraws for the outer rounding. Default:0outer_saturation_mode (
SaturationMode|None) – the outer format’s overflow behavior. Default:None, the accumulate format’s.carrier (
dtype|None) – as forbinaryK_matmul(). Default:None, the operands’ own carrier.carrier_rounding (
RoundMode) – as forbinaryK_matmul(). Default:RoundMode.RNE
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold a format (as for
superfp_quantize()), ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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, withsthe 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 singlefma_K/fma_Pformat instead of amul_*/acc_*pair. Withfma_quant=Falsethe fused step runs at the carrier’s own precision, likeaccumulate_quant=FalseinbinaryK_matmul().aandbfollowtorch.matmul’s operand rules. The carrier, the storage check and the per-call resolution are as forbinaryK_matmul().- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsefma_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’s2**(K - P - 1)signed and2**(K - P)unsigned.fma_is_signed (
bool) – whether the format has a sign bit. Default:Truefma_quant (
bool) – whether the fused step is rounded to the format at all. Default:Truefma_prng_bits (
int) – random bitsRoundMode.SRdraws for the fused rounding, asbinaryK_quantize()’sprng_bits. Default:0accumulate_algorithm (
AccumulateAlgorithm) – as forbinaryK_matmul(), with the fused step in place of the split one, exceptTREE, which raises: a fused multiply-add has no product term to sum pairwise. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the fused step’s rounding. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the format’s overflow behavior. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – the format’s bottom of range. Default:SubnormalsMode.SUBNORMALSblock_size (
int|None) – as forbinaryK_matmul(). Default:Noneouter_K (
int|None) – as forbinaryK_matmul(). Default:Noneouter_P (
int|None) – as forbinaryK_matmul(). Default:Noneouter_bias (
int|None) – as forbinaryK_matmul(). Default:Noneouter_is_signed (
bool|None) – whether the outer format has a sign bit. Default:None,fma_is_signed.outer_prng_bits (
int) – as forbinaryK_matmul(). Default:0outer_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 forbinaryK_matmul(). Default:None, the operands’ own carrier.carrier_rounding (
RoundMode) – as forbinaryK_matmul(). The fused step needsfma_quant=True. Default:RoundMode.RNE
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold the format, if
carriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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 byfma_man_bits,fma_exp_bits,fma_normal_binadesandfma_bias(seesuperfp_quantize()). Withfma_quant=Falseit is left at the carrier’s precision.aandbfollowtorch.matmul’s operand rules. The carrier, the storage check and the per-call resolution are as forbinaryK_matmul().- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsefma_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:Truefma_quant (
bool) – whether the fused step is rounded to the format at all. Default:Truefma_prng_bits (
int) – random bitsRoundMode.SRdraws for the fused rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – as forbinaryK_matmul(), with the fused step in place of the split one, exceptTREE, which raises: a fused multiply-add has no product term to sum pairwise. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the fused step’s rounding. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the format’s overflow behavior. Default:SaturationMode.SAT_NONEblock_size (
int|None) – as forbinaryK_matmul(). Default:Noneouter_man_bits (
int|None) – mantissa bits of the outer format, the roundingBLOCKandTREEapply to the total after each block is folded in (binaryK_matmul()’souter_K). The four widths are given together, or none of them, which leaves the total in the carrier’s precision. Default:Noneouter_exp_bits (
int|None) – exponent bits of the outer format. Default:Noneouter_normal_binades (
int|None) – normal binades of the outer format. Default:Noneouter_bias (
int|None) – exponent bias of the outer format. Default:Noneouter_is_signed (
bool|None) – whether the outer format has a sign bit. Default:None,fma_is_signed.outer_prng_bits (
int) – random bitsRoundMode.SRdraws for the outer rounding. Default:0outer_saturation_mode (
SaturationMode|None) – the outer format’s overflow behavior. Default:None,saturation_mode.carrier (
dtype|None) – as forbinaryK_matmul(). Default:None, the operands’ own carrier.carrier_rounding (
RoundMode) – as forbinaryK_matmul(). The fused step needsfma_quant=True. Default:RoundMode.RNE
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold the format, if
carriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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 byprec_idxfrom a palette of up to 8 formats.mul_Kandmul_Pare per-entry sequences, and their common length is the palette sizen. Each of the other palette arguments may be a scalar (used for every entry), ann-length sequence, orNone.Nonedefaults per entry as inbinaryK_matmul():acc_*fall back to themul_*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_idxselects 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 ofB(one map per batch element) or 1. The batch is never folded intoMhere, because the map is indexed by output element.Any integer dtype and layout is accepted. A map that is already
int32, contiguous and ona’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, ofa’s dtype and device.prec_idx (
Tensor) – the palette index of each output element, in[0, n).trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding; shared by the palette. Default:0accumulate_quant (
bool) – whether the running sum is rounded to the accumulate format after every step. Default:Trueacc_K (
int|Sequence[int] |None) – width of each entry’s accumulate format. Default:None, themul_Kentry.acc_P (
int|Sequence[int] |None) – precision of each entry’s accumulate format. Default:None, themul_Pentry.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 bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed; the palette ops implementNAIVEonly. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of every format. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply formats’ overflow behavior. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – the multiply formats’ bottom of range. Default:SubnormalsMode.SUBNORMALSacc_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 forbinaryK_matmul(). Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if the palette is empty or a palette argument’s length is not
n, if a carrier cannot hold an entry, ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
nis above 8,prec_idxhas 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=4entry and are exact. The last uses theP=3entry, 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_idxand the carrier contract.mul_man_bitsandmul_exp_bitsare per-entry sequences, and their common length is the palette sizen.mul_normal_binades,mul_biasand everyacc_*may be a scalar or ann-length sequence. Anacc_*may also beNone, which falls back to the correspondingmul_*entry.- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.prec_idx (
Tensor) – the palette index of each output element, in[0, n).trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding; shared by the palette. Default:0accumulate_quant (
bool) – whether the running sum is rounded to the accumulate format after every step. Default:Trueacc_man_bits (
int|Sequence[int] |None) – the accumulate formats’ mantissa bits. Default:None, themul_man_bitsentry.acc_exp_bits (
int|Sequence[int] |None) – the accumulate formats’ exponent bits. Default:None, themul_exp_bitsentry.acc_normal_binades (
int|Sequence[int] |None) – the accumulate formats’ normal binades. Default:None, themul_normal_binadesentry.acc_bias (
int|Sequence[int] |None) – the accumulate formats’ exponent bias. Default:None, themul_biasentry.acc_is_signed (
bool|None) – whether the accumulate formats have a sign bit. Default:None,mul_is_signed.acc_prng_bits (
int) – random bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed; the palette ops implementNAIVEonly. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of every format. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply formats’ overflow behavior. Default:SaturationMode.SAT_NONEacc_saturation_mode (
SaturationMode|None) – the accumulate formats’ overflow behavior. Default:None,saturation_mode.carrier (
dtype|None) – as forbinaryK_matmul(). Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if the palette is empty or a palette argument’s length is not
n, if a carrier cannot hold an entry, ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
nis above 8,prec_idxhas 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 byprec_idx, from a palette of up to 8 formats.prec_idxfollows the contract ofbinaryK_matmul_mixed().fma_Kandfma_Pare per-entry sequences, and their common length is the palette sizen.fma_biasmay be a scalar, ann-length sequence, orNonefor P3109’s bias per entry.fma_quant=Falseis rejected. An unrounded fused step has no format, so a palette would leaveprec_idxnothing to choose. UsebinaryK_matmul_fma()for the unquantized fused step.- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.prec_idx (
Tensor) – the palette index of each output element, in[0, n).trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsefma_K (
Sequence[int]) – width in bits 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:Truefma_quant (
bool) – must beTrue. Default:Truefma_prng_bits (
int) – random bitsRoundMode.SRdraws for the fused rounding; shared by the palette. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the fused steps are summed; the palette ops implementNAIVEonly. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of every entry. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the formats’ overflow behavior. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – the formats’ bottom of range. Default:SubnormalsMode.SUBNORMALScarrier (
dtype|None) – as forbinaryK_matmul(). Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if the palette is empty or a palette argument’s length is not
n, if a carrier cannot hold an entry, ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
fma_quantis false,nis above 8,prec_idxhas 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_idxand the carrier contract.fma_quant=Falseis rejected here too, because an unrounded fused step has no format forprec_idxto choose.fma_man_bitsandfma_exp_bitsare per-entry sequences, and their common length is the palette sizen.fma_normal_binadesandfma_biasmay each be a scalar or ann-length sequence.- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.prec_idx (
Tensor) – the palette index of each output element, in[0, n).trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsefma_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:Truefma_quant (
bool) – must beTrue. Default:Truefma_prng_bits (
int) – random bitsRoundMode.SRdraws for the fused rounding; shared by the palette. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the fused steps are summed; the palette ops implementNAIVEonly. Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of every entry. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the formats’ overflow behavior. Default:SaturationMode.SAT_NONEcarrier (
dtype|None) – as forbinaryK_matmul(). Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if the palette is empty or a palette argument’s length is not
n, if a carrier cannot hold an entry, ifcarriernames no carrier or is narrower than the operands, or if the operands’ leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.RuntimeError – if
fma_quantis false,nis above 8,prec_idxhas 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, asbinaryK_matmul()does, with the product rounded to the binaryK formatmul_K/mul_Pand the partial sum to the superfp format given by the fouracc_*widths. The accumulate format is required: a sum left in the carrier isbinaryK_matmul()withaccumulate_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) andsuperfp_quantize()the accumulate format. The result holds the accumulate format’s values, or withBLOCKorTREEand an outer format, the outer format’s, which is of the accumulate’s family.mptorch.quant.SplitMacwith amptorch.BinaryKmultiply and amptorch.SuperFPaccumulate resolves to this op.- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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’s2**(K - P - 1)signed and2**(K - P)unsigned.mul_is_signed (
bool) – whether the multiply format has a sign bit. Default:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding. Default:0acc_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 bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – as forbinaryK_matmul(). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of both formats. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply format’s overflow behavior. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – the multiply format’s bottom of range. Default:SubnormalsMode.SUBNORMALSacc_saturation_mode (
SaturationMode|None) – the accumulate format’s overflow behavior. Default:None,saturation_mode.block_size (
int|None) – as forbinaryK_matmul(). Default:Noneouter_man_bits (
int|None) – mantissa bits of the superfp outer format, assuperfp_matmul()’s. The four widths are given together, or none of them. Default:Noneouter_exp_bits (
int|None) – exponent bits of the outer format. Default:Noneouter_normal_binades (
int|None) – normal binades of the outer format. Default:Noneouter_bias (
int|None) – exponent bias of the outer format. Default:Noneouter_is_signed (
bool|None) – whether the outer format has a sign bit. Default:None, the accumulate format’s.outer_prng_bits (
int) – random bitsRoundMode.SRdraws for the outer rounding. Default:0outer_saturation_mode (
SaturationMode|None) – the outer format’s overflow behavior. Default:None, the accumulate format’s.carrier (
dtype|None) – as forbinaryK_quantize().torch.float64widens narrower operands to binary64 and narrows the result back to their dtype with one rounding.torch.float32refuses float64 operands. Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold a format, if
carrieristorch.float64or names no carrier, if the operands are float64, or if their leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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 fourmul_*widths and each partial sum to the binaryK formatacc_K/acc_P, which is required (a sum left in the carrier issuperfp_matmul()withaccumulate_quant=False). WithBLOCKorTREEthe outer format is a binaryK one, asbinaryK_matmul()’s.mptorch.quant.SplitMacwith amptorch.SuperFPmultiply and amptorch.BinaryKaccumulate resolves to this op.- Parameters:
a (
Tensor) – the left operand; float32, float64, float16 or bfloat16.b (
Tensor) – the right operand, ofa’s dtype and device.trans_a (
bool) – readatransposed in its last two dimensions. Default:Falsetrans_b (
bool) – readbtransposed in its last two dimensions. Default:Falsemul_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:Truemul_prng_bits (
int) – random bitsRoundMode.SRdraws for the multiply rounding. Default:0acc_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 foracc_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 bitsRoundMode.SRdraws for the accumulate rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – as forbinaryK_matmul(). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – the rounding of both formats. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – the multiply format’s overflow behavior. Default:SaturationMode.SAT_NONEacc_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.SUBNORMALSblock_size (
int|None) – as forbinaryK_matmul(). Default:Noneouter_K (
int|None) – width of the binaryK outer format, asbinaryK_matmul()’s. Default:Noneouter_P (
int|None) – precision of the outer format; given together withouter_K. Default:Noneouter_bias (
int|None) – exponent bias of the outer format. Default:None, P3109’s forouter_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 bitsRoundMode.SRdraws for the outer rounding. Default:0outer_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 forbinaryK_quantize().torch.float64widens narrower operands to binary64 and narrows the result back to their dtype with one rounding.torch.float32refuses float64 operands. Default:None, the operands’ own carrier.
- Returns:
the product, in the operands’ dtype, with the shape
torch.matmulwould give.- Return type:
- Raises:
ValueError – if a carrier cannot hold a format, if
carrieristorch.float64or names no carrier, if the operands are float64, or if their leading dimensions do not broadcast.TypeError – if
carrieris neither atorch.dtypenorNone.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
Nonemeans plain PyTorch behaviour for that step. Quantization is therefore opt-in per tensor and per pass: with aQAffineFormats()that has nothing set,QLinearbehaves exactly asnn.Linear.The forward pass quantizes the input, the weight and the bias through their
*_quantslots, then runsfwd_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 runsbwd_igrad_mathandbwd_wgrad_math(or PyTorch’s defaults).The class inherits from
nn.Module. A quantizer that is itself annn.Module(a QAT observer with running statistics) is therefore registered with the parent model and appears in itsstate_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;Noneis the layer’s default (both forQConv1d/2d/3d, the weight only forQLinear). 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:Noneinput_quant (
Callable|None) – applied to the input in the forward. Default:Nonebias_quant (
Callable|None) – applied to the bias in the forward. Default:Nonewgrad_quant (
Callable|None) – applied to the output gradient before the weight-gradient GEMM. Default:Noneigrad_quant (
Callable|None) – applied to the output gradient before the input-gradient GEMM. Default:Nonebgrad_quant (
Callable|None) – applied to the output gradient before the bias-gradient sum. Default:Nonefwd_math (
Callable|None) – the forward’s arithmetic. For Linear,fwd_math(q_input, q_weight, q_bias); for Conv, the same plusstride,padding,dilation,groupsandndas keywords. Default:Nonebwd_igrad_math (
Callable|None) – the input gradient’s arithmetic,bwd_igrad_math(q_grad_output, q_weight)for Linear (Conv addsinput_sizeand the convolution keywords). Default:Nonebwd_wgrad_math (
Callable|None) – the weight gradient’s arithmetic,bwd_wgrad_math(q_grad_output, q_input)for Linear (Conv addsweight_sizeand the convolution keywords). Default:Nonerecompute_input (
bool|None) – keep the raw input for backward and runinput_quanton it again there, instead of keeping its result.Noneis the layer’s default:Truefor a convolution,FalseforQLinear. UnderNoneonly a quantizer known to be stateless is run twice – amptorch.quant.Quant(not in place), amptorch.quant.BlockQuantcalled as a fake quantizer, or amptorch.quant.Quantizerover one – and any other callable keeps its result saved, since one with state (a QAT observer) would update it twice.Trueruns 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:Nonerecompute_weight (
bool|None) – the same for the weight andweight_quant.NoneisTruefor 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.Linearwith per-tensor quantization and custom arithmetic.It holds the same parameters as
nn.Linearand computes the sameinput @ weight.T + bias, but throughCustomArithLinear. The input, the weight, the bias and each gradient can therefore be rounded by the quantizers informats, and each GEMM can run in custom arithmetic (seemptorch.quant.binaryK_gemm_formats()). WithformatsleftNone, or with aQAffineFormatswhose slots are allNone, the layer is numerically identical tonn.Linear.formatsis a submodule, so a stateful quantizer in it appears in the layer’sstate_dict. For backward the layer keeps a quantized copy of its input and its raw weight, which it quantizes again there, unlessformats’recompute_input/recompute_weightsay otherwise. A layer overmptorch.quant.block_gemm_formats()can drop its float weight for its block codes withfreeze_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:Truedevice – as for
nn.Linear. Default:Nonedtype – as for
nn.Linear. Default:Noneformats (
QAffineFormats|None) – the quantizers and math hooks.Nonebuilds an emptyQAffineFormats(). 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.
- freeze_packed_(*, pack=True)[source]#
Replace the float weight by its block codes, in place.
The layer becomes a
QPackedLinear: itsweightisNone, and twouint8buffers,weight_codesandweight_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_quantunset, the weight packed in the weight format ofmptorch.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.Falseallocates zeroed buffers of the right shapes instead, on the weight’s device, forload_state_dict()of a frozen checkpoint to fill; on the meta device it allocates nothing. Default:True- Returns:
this layer.
- Return type:
- Raises:
ValueError – for formats that do not come from
mptorch.quant.block_gemm_formats(), forpack=Trueon a weight on the meta device, which has no values, and for aweight_quantresult 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
QLinearwhose weight is stored only as its block codes.QLinear.freeze_packed_()andmptorch.quant.freeze_packed_()make one, in place, from aQLinearovermptorch.quant.block_gemm_formats(); the class is not constructed directly. It is still aQLinear(isinstanceholds) and returns what the layer returned before the freeze, from a fraction of the memory: the weight’s codes and scales areuint8buffers,weight_codesandweight_scales, which follow.to()and stayuint8under.half(), andweightisNone. The packing’s format, shape, tensor scale, dtype and carrier are in thestate_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 thestate_dict. A model built on the meta device and frozen that way allocates its codes only when the state is loaded withassign=True, so the float model never exists. A checkpoint frozen in another format or shape raises, naming both.packed_weightis the codes as amptorch.quant.BlockPacked, andunfreeze_packed_()turns the layer back into aQLinear.Initialize internal Module state, shared by both nn.Module and ScriptModule.
- property packed_weight: BlockPacked#
The weight as a
mptorch.quant.BlockPackedover the two buffers, built per call, so that it follows the buffers through.to().
- reset_parameters()[source]#
Resets parameters based on their initialization used in
__init__.- Return type:
- 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.
- 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 correspondingget_extra_state()for your module if you need to store extra state within its state_dict.
- 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 plainnn.Linear.- Return type:
- mptorch.quant.freeze_packed_(model, *, pack=True)[source]#
QLinear.freeze_packed_()on everyQLinearofmodelwhose formats come frommptorch.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 forQLinear.freeze_packed_():Falseallocates zeroed codes for a frozen checkpoint to fill. Default:True
- Returns:
how many layers were frozen.
- Return type:
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.Conv1dwith per-tensor quantization and custom arithmetic.It holds the same parameters as
nn.Conv1dand computes the same convolution, but throughCustomArithConvNd. The input, the weight, the bias and each gradient can therefore be rounded by the quantizers informats, and each convolution can run in custom arithmetic. WithformatsleftNone, or with aQAffineFormatswhose slots are allNone, the layer is numerically identical tonn.Conv1d. Apadding_modeother than"zeros"is applied withF.padbefore the Function, asnn.Conv1ddoes, so the Function only ever sees zero padding. For backward the layer keeps its raw input and weight, which it quantizes again there, unlessformats’recompute_input/recompute_weightsay 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:1padding (
int|tuple[int] |str) – padding added to both sides of the input. Default:0dilation (
int|tuple[int]) – spacing between kernel elements. Default:1groups (
int) – blocked connections from input to output channels. Default:1bias (
bool) – whether the layer learns an additive bias. Default:Truepadding_mode (
Literal['zeros','reflect','replicate','circular']) –"zeros","reflect","replicate"or"circular". Default:"zeros"device – as for
nn.Conv1d. Default:Nonedtype – as for
nn.Conv1d. Default:Noneformats (
QAffineFormats|None) – the quantizers and math hooks;mptorch.quant.conv_formats()builds hooks that run the three convolutions in a custom arithmetic.Nonebuilds an emptyQAffineFormats(). 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 fornn.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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- 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.Conv2dwith per-tensor quantization and custom arithmetic.The 2D twin of
QConv1d. It has the same parameters asnn.Conv2dand computes the same convolution, throughCustomArithConvNd, so the quantizers and math hooks informatsapply. With empty formats it is numerically identical tonn.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:1padding (
int|tuple[int,int] |str) – padding added to all four sides of the input. Default:0dilation (
int|tuple[int,int]) – spacing between kernel elements. Default:1groups (
int) – blocked connections from input to output channels. Default:1bias (
bool) – whether the layer learns an additive bias. Default:Truepadding_mode (
Literal['zeros','reflect','replicate','circular']) –"zeros","reflect","replicate"or"circular". Default:"zeros"device – as for
nn.Conv2d. Default:Nonedtype – as for
nn.Conv2d. Default:Noneformats (
QAffineFormats|None) – the quantizers and math hooks.Nonebuilds an emptyQAffineFormats(). 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 fornn.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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- 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.Conv3dwith per-tensor quantization and custom arithmetic.The 3D twin of
QConv1d. It has the same parameters asnn.Conv3dand computes the same convolution, throughCustomArithConvNd, so the quantizers and math hooks informatsapply. With empty formats it is numerically identical tonn.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:1padding (
int|tuple[int,int,int] |str) – padding added to all six sides of the input. Default:0dilation (
int|tuple[int,int,int]) – spacing between kernel elements. Default:1groups (
int) – blocked connections from input to output channels. Default:1bias (
bool) – whether the layer learns an additive bias. Default:Truepadding_mode (
Literal['zeros','reflect','replicate','circular']) –"zeros","reflect","replicate"or"circular". Default:"zeros"device – as for
nn.Conv3d. Default:Nonedtype – as for
nn.Conv3d. Default:Noneformats (
QAffineFormats|None) – the quantizers and math hooks.Nonebuilds an emptyQAffineFormats(). 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 fornn.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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
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
QAffineFormatswhose dot products run in a binaryK GEMM.The returned formats set
fwd_math,bwd_igrad_mathandbwd_wgrad_math. A Linear layer’s forward GEMM and both of its gradient GEMMs then run throughmptorch.quant.ops.binaryK_matmul(), which takes these same arguments. Every product is rounded to themul_*format. Whenaccumulate_quantis set, every partial sum is rounded to theacc_*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
carriernames one. It warns withmptorch.FormatRangeWarningabout 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.Nonetakes IEEE P3109’s,2**(K-P-1)signed and2**(K-P)unsigned. Default:Nonemul_is_signed (
bool) – whether the multiply format has a sign bit. Default:Truemul_prng_bits (
int) – random bits drawn per stochastic rounding of a product; only read whenrounding_modeisRoundMode.SR. Default:0accumulate_quant (
bool) – whether the running sum is rounded to theacc_*format after every step.Falsekeeps it in the carrier’s precision and ignores theacc_*widths. Default:Trueacc_K (
int|None) – width of the accumulate format.Nonetakesmul_K. Default:Noneacc_P (
int|None) – precision of the accumulate format.Nonetakesmul_P. Default:Noneacc_bias (
int|None) – exponent bias of the accumulate format.Nonetakes P3109’s foracc_K/acc_P. Default:Noneacc_is_signed (
bool|None) – sign bit of the accumulate format.Nonetakesmul_is_signed. Default:Noneacc_prng_bits (
int) – random bits per stochastic rounding of a partial sum. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed, as formptorch.quant.binaryK_matmul():NAIVE,KAHAN,BLOCKorTREE(the last not for a fused mac). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – rounding for both formats; one mode for both because the kernels take it as a template parameter. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – overflow behaviour of the multiply format. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – what the multiply format keeps below its smallest normal. Default:SubnormalsMode.SUBNORMALSacc_saturation_mode (
SaturationMode|None) – overflow behaviour of the accumulate format.Nonetakessaturation_mode. Default:Noneacc_subnormals_mode (
SubnormalsMode|None) – subnormal handling of the accumulate format.Nonetakessubnormals_mode. Default:Noneblock_size (
int|None) –BLOCK’s andTREE’s block size, as formptorch.quant.binaryK_matmul(). Default:Noneouter_K (
int|None) – width of the outer formatBLOCKandTREEround their total to, as formptorch.quant.binaryK_matmul(), which documents it and the rest of its spelling:outer_P,outer_bias,outer_is_signed,outer_prng_bits,outer_saturation_modeandouter_subnormals_mode. Default:None, an unrounded total.carrier (
dtype|None) – the float arithmetic the GEMM rounds in.Nonetakes the layer’s (binary64 for float64, binary32 for the rest);torch.float64runs a float32 or half-precision layer in binary64 too and narrows each result back to the layer’s dtype;torch.float32on a float64 layer raises at the call. Default:Nonecarrier_rounding (
RoundMode) –RoundMode.ROrounds the carrier’s steps to odd, as formptorch.quant.binaryK_matmul(), for every pass of the layer;NAIVEonly. Default:RoundMode.RNEouter_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
*_mathhooks set and every*_quantslot leftNone.- Return type:
- 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
carrierthat 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 thefma_*format (mptorch.quant.ops.binaryK_matmul_fma()). It replaces a rounded multiply followed by a separately rounded add. The general contract is that ofbinaryK_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;Nonetakes IEEE P3109’s. Default:Nonefma_is_signed (
bool) – whether the format has a sign bit. Default:Truefma_quant (
bool) – whether each fused step is rounded at all.Falseruns unrounded fused steps in the carrier. Default:Truefma_prng_bits (
int) – random bits per stochastic rounding; only read whenrounding_modeisRoundMode.SR. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed, as formptorch.quant.binaryK_matmul():NAIVE,KAHAN,BLOCKorTREE(the last not for a fused mac). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – rounding of each fused step. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – overflow behaviour. Default:SaturationMode.SAT_NONEsubnormals_mode (
SubnormalsMode) – subnormal handling. Default:SubnormalsMode.SUBNORMALSblock_size (
int|None) –BLOCK’s andTREE’s block size, as formptorch.quant.binaryK_matmul(). Default:Noneouter_K (
int|None) – width of the outer formatBLOCKandTREEround their total to, as formptorch.quant.binaryK_matmul(), which documents it and the rest of its spelling:outer_P,outer_bias,outer_is_signed,outer_prng_bits,outer_saturation_modeandouter_subnormals_mode. Default:None, an unrounded total.carrier (
dtype|None) – as forbinaryK_gemm_formats(). Default:Nonecarrier_rounding (
RoundMode) –RoundMode.ROrounds the carrier’s steps to odd, as formptorch.quant.binaryK_matmul_fma(), for every pass of the layer;NAIVEonly. Default:RoundMode.RNEouter_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
*_mathhooks set.- Return type:
- 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 themul_*superfp format. Whenaccumulate_quantis set, partial sums are rounded to theacc_*one. A superfp format keeps a mantissa in the topnormal_binadesbinades 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 nosubnormals_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:Truemul_prng_bits (
int) – random bits per stochastic rounding of a product. Default:0accumulate_quant (
bool) – whether partial sums are rounded to theacc_*format. Default:Trueacc_man_bits (
int|None) –Nonetakesmul_man_bits. Default:Noneacc_exp_bits (
int|None) –Nonetakesmul_exp_bits. Default:Noneacc_normal_binades (
int|None) –Nonetakesmul_normal_binades. Default:Noneacc_is_signed (
bool|None) –Nonetakesmul_is_signed. Default:Noneacc_prng_bits (
int) – random bits per stochastic rounding of a partial sum. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed, as formptorch.quant.binaryK_matmul():NAIVE,KAHAN,BLOCKorTREE(the last not for a fused mac). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – rounding for both formats. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – overflow behaviour of the multiply format. Default:SaturationMode.SAT_NONEacc_saturation_mode (
SaturationMode|None) –Nonetakessaturation_mode. Default:Noneblock_size (
int|None) –BLOCK’s andTREE’s block size, as formptorch.quant.binaryK_matmul(). Default:Noneouter_man_bits (
int|None) – mantissa bits of the outer formatBLOCKandTREEround their total to, as formptorch.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_bitsandouter_saturation_mode. Default:None, an unrounded total.carrier (
dtype|None) – as forbinaryK_gemm_formats(). Default:Nonecarrier_rounding (
RoundMode) –RoundMode.ROrounds the carrier’s steps to odd, as formptorch.quant.superfp_matmul(), for every pass of the layer;NAIVEonly. Default:RoundMode.RNEouter_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
*_mathhooks set.- Return type:
- Raises:
ValueError – for a format no carrier can hold, a
normal_binadesthat leaves no supernormal codes, or acarrierthat 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 ofsuperfp_gemm_formats()under thefma_prefix, plusfma_quant, as inbinaryK_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:Truefma_quant (
bool) – whether each fused step is rounded at all. Default:Truefma_prng_bits (
int) – random bits per stochastic rounding. Default:0accumulate_algorithm (
AccumulateAlgorithm) – how the products are summed, as formptorch.quant.binaryK_matmul():NAIVE,KAHAN,BLOCKorTREE(the last not for a fused mac). Default:AccumulateAlgorithm.NAIVErounding_mode (
RoundMode) – rounding of each fused step. Default:RoundMode.RNEsaturation_mode (
SaturationMode) – overflow behaviour. Default:SaturationMode.SAT_NONEblock_size (
int|None) –BLOCK’s andTREE’s block size, as formptorch.quant.binaryK_matmul(). Default:Noneouter_man_bits (
int|None) – mantissa bits of the outer formatBLOCKandTREEround their total to, as formptorch.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_bitsandouter_saturation_mode. Default:None, an unrounded total.carrier (
dtype|None) – as forbinaryK_gemm_formats(). Default:Nonecarrier_rounding (
RoundMode) –RoundMode.ROrounds the carrier’s steps to odd, as formptorch.quant.superfp_matmul_fma(), for every pass of the layer;NAIVEonly. Default:RoundMode.RNEouter_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
*_mathhooks set.- Return type:
- 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 binaryKmul_*format and partial sums to the superfpacc_*format, which is required (an unrounded sum isbinaryK_gemm_formats()withaccumulate_quant=False). WithBLOCKorTREEthe outer format is a superfp one.- Returns:
with the three
*_mathhooks set.- Return type:
- Raises:
ValueError – for a format no carrier can hold, or a
carrierthat istorch.float64or names no carrier.- Parameters:
mul_K (int)
mul_P (int)
acc_man_bits (int)
acc_exp_bits (int)
acc_normal_binades (int)
acc_bias (int)
mul_bias (int | None)
mul_is_signed (bool)
mul_prng_bits (int)
acc_is_signed (bool | None)
acc_prng_bits (int)
accumulate_algorithm (AccumulateAlgorithm)
rounding_mode (RoundMode)
saturation_mode (SaturationMode)
subnormals_mode (SubnormalsMode)
acc_saturation_mode (SaturationMode | None)
block_size (int | None)
outer_man_bits (int | None)
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)
carrier (dtype | None)
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 superfpmul_*format and partial sums to the binaryKacc_*format, which is required (an unrounded sum issuperfp_gemm_formats()withaccumulate_quant=False). WithBLOCKorTREEthe outer format is a binaryK one.- Returns:
with the three
*_mathhooks set.- Return type:
- Raises:
ValueError – for a format no carrier can hold, a
normal_binadesthat leaves no supernormal codes, or acarrierthat istorch.float64or names no carrier.- Parameters:
mul_man_bits (int)
mul_exp_bits (int)
mul_normal_binades (int)
mul_bias (int)
acc_K (int)
acc_P (int)
mul_is_signed (bool)
mul_prng_bits (int)
acc_bias (int | None)
acc_is_signed (bool | None)
acc_prng_bits (int)
accumulate_algorithm (AccumulateAlgorithm)
rounding_mode (RoundMode)
saturation_mode (SaturationMode)
acc_saturation_mode (SaturationMode | None)
acc_subnormals_mode (SubnormalsMode)
block_size (int | None)
outer_K (int | None)
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)
carrier (dtype | None)
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
QAffineFormatswhose three convolution passes run inmac’s arithmetic.The forward convolution, the input gradient and the weight gradient of a
QConv1d,QConv2dorQConv3deach run inmac’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**ndtimes more, because it sums the zeros it inserts. Under aNAIVEsum 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 andgroupsworks. 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_quantand the other*_quantslots) 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 throughmptorch.quant.mac.spec_for_mac(). A bareNumbermeansSplitMac(fmt, fmt). Everyaccumulate_algorithmapplies, and aSplitMacmay 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]withOUTthe 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 palettemac. Default:Noneigrad_prec_idx (
Tensor|None) – the input gradient’s map, shaped the same way over[Cin, IN], withINthe number of input positions. The classes of a strided gradient read it at their own positions. Default:Nonewgrad_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_mathandbwd_wgrad_mathset and every*_quantslot leftNone.- Return type:
- Raises:
ValueError – for a palette
macwithoutprec_idx, or a map given to amacwithout 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
QAffineFormatswhose 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^Tpacks the input along its features ininput’s format, and the weight along its input features inweight’s.The input gradient
g @ wpacks the output gradient along its features ingrad’s format (input’s by default), and the weight along its output features.The weight gradient
g^T @ xpacks both along the batch.
The arithmetic (
acc,fused,rounding, the accumulate algorithm) is that ofmptorch.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, leaveweight_quantunset.For inference,
mptorch.quant.QLinear.freeze_packed_()replaces the layer’s float weight by its codes inweight’s format, and the layer then holds only those (mptorch.quant.QPackedLinear).- Parameters:
input (
BlockFormat|BlockQuant) – the input’s format (aBlockQuantnames its rounding and tensor scale).weight (
BlockFormat|BlockQuant) – the weight’s.grad (
BlockFormat|BlockQuant|None) – the output gradient’s. Default:None,input’s.fused (
bool) – a fused multiply-add per step. Default:Falserounding (
RoundMode) – the sum’s rounding mode. Default:RoundMode.RNEaccumulate_algorithm (
AccumulateAlgorithm) – as formptorch.quant.SplitMac. Default:AccumulateAlgorithm.NAIVEouter (
BinaryK|None) – BLOCK’s and TREE’s outer format. Default:Nonecarrier (
dtype|None) –torch.float64packs and multiplies in binary64 whatever the layer’s dtype, as formptorch.quant.BlockMac(aBlockQuantthat 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
*_quantslot leftNone.- Return type:
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()