"""
numfmt.py -- number formats bit by bit: INT-k, FP32/FP16/BF16, FP8 (E4M3, E5M2), FP6, FP4, MX and NVFP4 blocks
==============================================================================================================

[Why we need it]
    Lecture 4 asks how few bits a model can use and what each bit costs. To answer with numbers we need the
    formats themselves, implemented exactly: which values each format can represent, how a real number is rounded
    into it, what happens at the edges (subnormals, overflow, NaN), and how BLOCK formats share one scale among
    many elements. This module provides
    1. FloatFormat: any small floating-point format (sign, exponent, mantissa, bias, special-value convention),
       with quantize() (round to nearest, ties to even, or stochastic), encode() to bit codes and decode() back;
    2. IntFormat: k-bit integers with a scale (the classic INT8/INT4 quantization);
    3. block formats: the OCP Microscaling (MX) formats -- MXFP8, MXFP6, MXFP4, MXINT8: 32 elements share one
       8-bit power-of-two scale (E8M0) -- NVIDIA's NVFP4 (16 FP4 elements share an FP8 E4M3 scale, plus a per-tensor
       FP32 scale), and the two-level "shared microexponents" scheme of Rouhani et al. (ISCA 2023).

[Usage]
    import numpy as np, numfmt as nf
    nf.FP8_E4M3.max                         # 448.0
    nf.quantize(np.array([0.1, 3.3]), nf.FP4_E2M1)       # -> [0.0, 3.0]
    nf.encode(1.5, nf.FP8_E4M3)             # -> 0x3c  (bits 0 0111 100)
    x_hat = nf.mx_quantize(x, nf.MXFP4)     # block-scaled fake quantization along the last axis

[Rounding and overflow conventions]
    - Round to nearest, ties to EVEN (IEEE default): 2.5 -> 2, 3.5 -> 4 in a format whose grid there has
      spacing 1. Implemented as numpy.rint on the scaled value, which rounds halves to even.
    - Overflow SATURATES to +-max by default (the usual choice when quantizing tensors, and what MX element
      conversion does). With saturate=False, IEEE-like formats (FP32/FP16/BF16/E5M2) overflow to infinity and
      E4M3 to NaN; FP6/FP4 have neither and always saturate.
    - All functions take and return float64 numpy arrays of DEQUANTIZED values ("fake quantization"): the value
      the hardware would see after decoding. encode()/decode() give the actual bit codes.

[Edge cases]
    - Negative zero: quantize() returns -0.0 for small negative inputs (as hardware does); comparisons treat
      -0.0 == 0.0. encode() keeps the sign bit.
    - Inputs must be finite unless saturate=False semantics are wanted; NaN inputs stay NaN.
"""

import math
from dataclasses import dataclass

import numpy as np

# =====================================================================================================================
# Floating-point formats
# =====================================================================================================================


@dataclass(frozen=True)
class FloatFormat:
    """
    A binary floating-point format: value = (-1)^s * 2^(exponent - bias) * 1.mantissa  (or 0.mantissa for subnormals).

    [Fields]
        name    : label
        ebits   : exponent bits
        mbits   : mantissa (fraction) bits; precision = mbits + 1 significant bits for normal numbers
        bias    : exponent bias
        special : how the top exponent code is used --
                  "ieee" : reserved for infinity (mantissa 0) and NaN (FP32, FP16, BF16, FP8 E5M2)
                  "fn"   : normal numbers, except the all-ones code which is NaN (FP8 E4M3, "finite + NaN")
                  "none" : all codes are finite numbers (FP6 E2M3/E3M2, FP4 E2M1 of the MX spec)
    [Properties] bits, emin, emax, max, min_normal, min_subnormal, eps (relative spacing at 1.0)
    """
    name: str
    ebits: int
    mbits: int
    bias: int
    special: str = "ieee"

    @property
    def bits(self):
        return 1 + self.ebits + self.mbits

    @property
    def emin(self):
        """Exponent of the smallest normal number (subnormals share it)."""
        return 1 - self.bias

    @property
    def emax(self):
        """Exponent of the largest finite number."""
        top = 2 ** self.ebits - 1
        return (top - 1 if self.special == "ieee" else top) - self.bias

    @property
    def max(self):
        """Largest finite value. E4M3 loses its all-ones mantissa at the top exponent to NaN: 1.75 * 2^8 = 448."""
        if self.special == "fn":
            return (2 - 2.0 ** (1 - self.mbits)) * 2.0 ** self.emax
        return (2 - 2.0 ** -self.mbits) * 2.0 ** self.emax

    @property
    def min_normal(self):
        return 2.0 ** self.emin

    @property
    def min_subnormal(self):
        return 2.0 ** (self.emin - self.mbits)

    @property
    def eps(self):
        """Gap between 1.0 and the next larger value: 2^-mbits (relative precision of normal numbers)."""
        return 2.0 ** -self.mbits

    @property
    def has_inf(self):
        return self.special == "ieee"


FP32 = FloatFormat("FP32", 8, 23, 127)
FP16 = FloatFormat("FP16", 5, 10, 15)
BF16 = FloatFormat("BF16", 8, 7, 127)
FP8_E4M3 = FloatFormat("FP8 E4M3", 4, 3, 7, "fn")
FP8_E5M2 = FloatFormat("FP8 E5M2", 5, 2, 15)
FP6_E2M3 = FloatFormat("FP6 E2M3", 2, 3, 1, "none")
FP6_E3M2 = FloatFormat("FP6 E3M2", 3, 2, 3, "none")
FP4_E2M1 = FloatFormat("FP4 E2M1", 2, 1, 1, "none")
FLOAT_FORMATS = [FP32, FP16, BF16, FP8_E4M3, FP8_E5M2, FP6_E2M3, FP6_E3M2, FP4_E2M1]


def _round(v, rounding, rng):
    """
    Round non-negative values v to integers.

    [Args] rounding: "nearest" (ties to even) or "stochastic" (round up with probability = fractional part,
        so that the EXPECTED result equals v -- unbiased, used in low-precision training)
    """
    if rounding == "nearest":
        return np.rint(v)
    if rounding == "stochastic":
        rng = rng or np.random.default_rng(0)
        return np.floor(v + rng.random(np.shape(v)))
    raise ValueError("rounding must be 'nearest' or 'stochastic'")


def quantize(x, fmt, saturate=True, rounding="nearest", rng=None):
    """
    Round real numbers to the nearest value representable in a FloatFormat.

    [Idea] A float format is a stack of binades [2^e, 2^(e+1)), each holding 2^mbits equally spaced values with
        spacing 2^(e - mbits). So: find each value's binade e (numpy.frexp gives it exactly), clamp e at emin
        (below that, the subnormals continue with the same spacing down to 0), divide by the spacing, round to an
        integer, multiply back. Values that round past the largest finite number saturate (or become inf/NaN).
    [Args]
        x        : array-like of real numbers
        fmt      : FloatFormat
        saturate : clamp overflow to +-max (default) instead of producing inf (IEEE formats) or NaN (E4M3)
        rounding : "nearest" (ties to even) or "stochastic"; rng: numpy Generator for stochastic rounding
    [Returns] float64 numpy array of representable values
    [Edge cases] A value that rounds up across a binade boundary (e.g. 1.99 -> 2.0 in FP4) is handled
        naturally: q * spacing lands exactly on 2^(e+1). Zero stays zero; NaN stays NaN.
    [Python tip] np.frexp(a) returns (m, E) with a = m * 2**E and 0.5 <= m < 1 -- an exact way to read a
        float's exponent without logarithms (log2 can be off by one ulp near powers of two).
    """
    x = np.asarray(x, dtype=np.float64)
    a = np.abs(x)
    with np.errstate(invalid="ignore", over="ignore"):
        _, E = np.frexp(a)
        e = np.maximum(E - 1, fmt.emin)
        spacing = np.ldexp(1.0, e - fmt.mbits)
        q = _round(a / spacing, rounding, rng) * spacing
        over = (q > fmt.max) | np.isinf(a)
        if saturate or fmt.special == "none":
            q = np.where(over, fmt.max, q)
        elif fmt.special == "ieee":
            q = np.where(over, np.inf, q)
        else:
            q = np.where(over, np.nan, q)
        out = np.copysign(q, x)
    return np.where(np.isnan(x), np.nan, out)


def encode(x, fmt, saturate=True):
    """
    Bit codes of the values (after rounding): sign | exponent code | mantissa code, as Python ints / int64 array.

    [Idea] For a normal number v = 1.f * 2^e: exponent code = e + bias, mantissa code = f * 2^mbits.
        For a subnormal v = 0.f * 2^emin: exponent code 0, mantissa code = v / min_subnormal.
    [Returns] numpy int64 array (or a Python int for a scalar input)
    [Edge cases] inf -> exponent all ones, mantissa 0 (IEEE formats); NaN -> all-ones exponent and mantissa
        (E4M3: S.1111.111; IEEE: a quiet NaN with the top mantissa bit set).
    """
    scalar = np.ndim(x) == 0
    q = quantize(x, fmt, saturate)
    sign = np.signbit(q).astype(np.int64)
    a = np.abs(q)
    with np.errstate(invalid="ignore", divide="ignore"):
        _, E = np.frexp(a)
        e = E - 1
        normal = a >= fmt.min_normal
        ecode = np.where(normal, e + fmt.bias, 0)
        mant = np.where(normal, (a / np.ldexp(1.0, e) - 1) * 2 ** fmt.mbits, a / fmt.min_subnormal)
    mant = np.nan_to_num(np.rint(mant)).astype(np.int64)
    ecode = np.nan_to_num(ecode).astype(np.int64)
    top = 2 ** fmt.ebits - 1
    is_inf, is_nan = np.isinf(q), np.isnan(q)
    ecode = np.where(is_inf | is_nan, top, ecode)
    mant = np.where(is_inf, 0, mant)
    mant = np.where(is_nan, 2 ** fmt.mbits - 1 if fmt.special == "fn" else 2 ** (fmt.mbits - 1), mant)
    code = (sign << (fmt.ebits + fmt.mbits)) | (ecode << fmt.mbits) | mant
    return int(code) if scalar else code


def decode(code, fmt):
    """
    Values of bit codes (the inverse of encode()).

    [Args] code: int or integer array of codes in [0, 2^bits)
    [Returns] float64 numpy array (or float for a scalar)
    """
    scalar = np.ndim(code) == 0
    c = np.asarray(code, dtype=np.int64)
    sign = (c >> (fmt.ebits + fmt.mbits)) & 1
    ecode = (c >> fmt.mbits) & (2 ** fmt.ebits - 1)
    mant = c & (2 ** fmt.mbits - 1)
    frac = mant / 2.0 ** fmt.mbits
    val = np.where(ecode == 0, frac * 2.0 ** fmt.emin, (1 + frac) * np.ldexp(1.0, ecode - fmt.bias))
    top = 2 ** fmt.ebits - 1
    if fmt.special == "ieee":
        val = np.where(ecode == top, np.where(mant == 0, np.inf, np.nan), val)
    elif fmt.special == "fn":
        val = np.where((ecode == top) & (mant == 2 ** fmt.mbits - 1), np.nan, val)
    val = np.where(sign == 1, -val, val)
    return float(val) if scalar else val


def all_values(fmt, finite=True):
    """Every value of a format with <= 16 bits, sorted (finite only by default). FP4 E2M1: 15 values (+-0 merged)."""
    if fmt.bits > 16:
        raise ValueError("enumerating all codes is only sensible for formats of <= 16 bits")
    v = decode(np.arange(2 ** fmt.bits), fmt)
    if finite:
        v = v[np.isfinite(v)]
    return np.unique(v)


# =====================================================================================================================
# Integer formats
# =====================================================================================================================

@dataclass(frozen=True)
class IntFormat:
    """
    A k-bit integer grid used with a real-valued scale: value = q * scale, q integer in [qmin, qmax].

    [Fields] name; bits; symmetric: True -> qmin = -qmax (e.g. int8 in [-127, 127], so that zero is exactly in the
        middle and +-scale behave the same); False -> two's complement range [-2^(k-1), 2^(k-1) - 1]
    """
    name: str
    bits: int
    symmetric: bool = True

    @property
    def qmax(self):
        return 2 ** (self.bits - 1) - 1

    @property
    def qmin(self):
        return -self.qmax if self.symmetric else -(2 ** (self.bits - 1))

    @property
    def max(self):
        """Largest code (in units of the scale) -- used by scale = amax / max."""
        return float(self.qmax)


INT8 = IntFormat("INT8", 8)
INT4 = IntFormat("INT4", 4)


def quantize_int(x, fmt, scale, rounding="nearest", rng=None):
    """
    Uniform quantization: q = clip(round(x / scale), qmin, qmax); returns q * scale.

    [Args] scale: positive number or array broadcastable to x (per-channel / per-group scales)
    [Returns] float64 array of dequantized values
    [Edge cases] A zero scale (an all-zero channel) returns zeros instead of dividing by zero.
    """
    x = np.asarray(x, dtype=np.float64)
    scale = np.asarray(scale, dtype=np.float64)
    safe = np.where(scale > 0, scale, 1.0)
    a = x / safe
    q = np.sign(a) * _round(np.abs(a), rounding, rng)
    q = np.clip(q, fmt.qmin, fmt.qmax)
    return np.where(scale > 0, q * safe, 0.0)


# =====================================================================================================================
# Block formats
# =====================================================================================================================

def _blocks(x, block):
    """
    Reshape the last axis of x into (..., n_blocks, block), padding with zeros if needed.
    [Returns] (blocked array, original last-axis length)
    """
    x = np.asarray(x, dtype=np.float64)
    n = x.shape[-1]
    pad = (-n) % block
    if pad:
        x = np.concatenate([x, np.zeros(x.shape[:-1] + (pad,))], axis=-1)
    return x.reshape(x.shape[:-1] + (-1, block)), n


def _unblock(xb, n):
    return xb.reshape(xb.shape[:-2] + (-1,))[..., :n]


@dataclass(frozen=True)
class MXFormat:
    """
    An OCP Microscaling (MX v1.0) format: blocks of `block` elements share one E8M0 scale (a power of two).

    [Fields] name; elem: a FloatFormat or IntFormat "MXINT8"; block: 32 in the spec; scale_bits: 8 (E8M0)
    [Properties] bits_per_element = element bits + scale_bits / block (e.g. MXFP4: 4 + 8/32 = 4.25)
    """
    name: str
    elem: object
    block: int = 32
    scale_bits: int = 8

    @property
    def bits_per_element(self):
        return self.elem.bits + self.scale_bits / self.block

    @property
    def elem_emax(self):
        """Exponent of the element format's largest normal number (the spec's emax_elem); 0 for MXINT8."""
        return 0 if isinstance(self.elem, IntFormat) else self.elem.emax


MXFP8_E4M3 = MXFormat("MXFP8 (E4M3)", FP8_E4M3)
MXFP8_E5M2 = MXFormat("MXFP8 (E5M2)", FP8_E5M2)
MXFP6_E2M3 = MXFormat("MXFP6 (E2M3)", FP6_E2M3)
MXFP6_E3M2 = MXFormat("MXFP6 (E3M2)", FP6_E3M2)
MXFP4 = MXFormat("MXFP4 (E2M1)", FP4_E2M1)
MXINT8 = MXFormat("MXINT8", IntFormat("INT8 (MX, 1.6 fixed point)", 8, symmetric=False))


def mx_quantize(x, fmt, block=None):
    """
    Fake-quantize x to an MX format along its last axis.

    [Idea] (OCP MX v1.0, section on conversion) For each block: shared exponent X = floor(log2(max |x|)) - emax_elem,
        clamped to the E8M0 range [-127, 127]; scale = 2^X; every element is converted to the element format as
        x / scale (with saturation). Because the scale is a power of two, the largest element lands in the element
        format's top binade -- but it can still be up to ~2x below the format's max, which wastes up to one bit.
        MXINT8 elements are 8-bit two's complement with an implicit 2^-6 (values k / 64, k in [-128, 127]).
    [Args] x: array; fmt: MXFormat; block: override the block size (for block-size sweeps)
    [Returns] float64 array, same shape as x
    [Edge cases] An all-zero block gets scale 2^-127 and stays zero. The last block is zero-padded if the axis
        length is not a multiple of the block size.
    """
    block = block or fmt.block
    xb, n = _blocks(x, block)
    amax = np.max(np.abs(xb), axis=-1, keepdims=True)
    with np.errstate(divide="ignore"):
        _, E = np.frexp(amax)
    X = np.where(amax > 0, (E - 1) - fmt.elem_emax, -127)
    X = np.clip(X, -127, 127)
    scale = np.ldexp(1.0, X)
    v = xb / scale
    if isinstance(fmt.elem, IntFormat):
        q = np.clip(np.rint(v * 64), -128, 127) / 64
    else:
        q = quantize(v, fmt.elem, saturate=True)
    return _unblock(q * scale, n)


@dataclass(frozen=True)
class NVFP4Format:
    """NVIDIA NVFP4: FP4 E2M1 elements, blocks of 16 sharing an FP8 E4M3 scale, plus one FP32 scale per tensor."""
    name: str = "NVFP4"
    block: int = 16

    @property
    def bits_per_element(self):
        return 4 + 8 / self.block            # + 32 bits per TENSOR, negligible


NVFP4 = NVFP4Format()


def nvfp4_quantize(x, block=16, tensor_amax=None):
    """
    Fake-quantize x to NVFP4 along its last axis.

    [Idea] Two-level scaling. A per-tensor FP32 scale g = amax(tensor) / (448 * 6) maps the tensor's range into
        what an E4M3 block scale times an E2M1 element can represent (448 = E4M3 max, 6 = E2M1 max). Each block of
        16 gets scale s = amax(block) / 6, stored as E4M3(s / g); elements are E2M1(x / (E4M3(s / g) * g)).
        Unlike MX's power-of-two scale, the E4M3 scale has 3 mantissa bits, so a block's largest element maps
        close to 6 -- the full FP4 range is used.
    [Args] tensor_amax: override the per-tensor amax (e.g. a calibrated value)
    [Returns] float64 array, same shape as x
    [Edge cases] Rounding the block scale to E4M3 can round it DOWN, pushing x / scale slightly above 6: those
        elements saturate to 6 (a small clipping error). All-zero blocks stay zero.
    """
    x = np.asarray(x, dtype=np.float64)
    amax_t = float(np.max(np.abs(x))) if tensor_amax is None else float(tensor_amax)
    g = amax_t / (FP8_E4M3.max * FP4_E2M1.max) if amax_t > 0 else 1.0
    xb, n = _blocks(x, block)
    amax = np.max(np.abs(xb), axis=-1, keepdims=True)
    s = quantize(amax / FP4_E2M1.max / g, FP8_E4M3, saturate=True) * g
    safe = np.where(s > 0, s, 1.0)
    q = quantize(xb / safe, FP4_E2M1, saturate=True)
    return _unblock(np.where(s > 0, q * safe, 0.0), n)


def smx_quantize(x, mbits, block=16, sub=2):
    """
    Two-level "shared microexponent" quantization in the style of Rouhani et al. (ISCA 2023).

    [Idea] A block of 16 shares an 8-bit exponent E = floor(log2(max |x|)); each pair of elements additionally
        shares a 1-bit MICRO-exponent that lowers its scale by 2x when both elements are small (max |pair| < 2^E).
        Elements are sign + `mbits`-bit magnitudes in fixed point relative to their pair's scale. The small extra
        bit buys back most of the precision a single shared exponent loses on blocks with a wide spread.
        Average bits per element: 1 + mbits + 8/16 + 1/2 (e.g. mbits = 4 -> 6 bits: "MX6"; mbits = 2 -> "MX4").
    [Args] mbits: magnitude bits per element; block, sub: first- and second-level block sizes
    [Returns] float64 array, same shape as x
    [Edge cases] This is an illustrative implementation of the idea, not a bit-exact copy of the paper's hardware.
    """
    xb, n = _blocks(x, block)
    amax = np.max(np.abs(xb), axis=-1, keepdims=True)
    with np.errstate(divide="ignore"):
        _, E = np.frexp(amax)
    E = np.where(amax > 0, E - 1, -127)                       # amax in [2^E, 2^(E+1))
    pairs = xb.reshape(xb.shape[:-1] + (block // sub, sub))
    pmax = np.max(np.abs(pairs), axis=-1, keepdims=True)
    mu = (pmax < np.ldexp(1.0, E)[..., None]).astype(int)      # 1 -> this pair uses scale 2^(E-1)
    step = np.ldexp(1.0, (E[..., None] - mu) - (mbits - 1))   # magnitudes in [0, 2) * 2^(E - mu)
    q = np.clip(np.rint(np.abs(pairs) / step), 0, 2 ** mbits - 1) * step
    return _unblock((np.sign(pairs) * q).reshape(xb.shape), n)


def bits_per_element(fmt, group=None, scale_bits=16):
    """
    Storage bits per element including amortized scales.
    [Args] fmt: FloatFormat / IntFormat (per-tensor: scale negligible), MXFormat, NVFP4Format; group: group size
        for IntFormat/FloatFormat with per-group scales of `scale_bits` bits
    """
    if isinstance(fmt, (MXFormat, NVFP4Format)):
        return fmt.bits_per_element
    return fmt.bits + (scale_bits / group if group else 0)


# =====================================================================================================================
# Self-test
# =====================================================================================================================

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # 1. Known constants.
    assert FP8_E4M3.max == 448 and FP8_E5M2.max == 57344 and FP16.max == 65504
    assert FP6_E2M3.max == 7.5 and FP6_E3M2.max == 28 and FP4_E2M1.max == 6
    assert list(all_values(FP4_E2M1)[7:]) == [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
    assert FP8_E4M3.min_subnormal == 2 ** -9 and FP16.min_subnormal == 2 ** -24
    # 2. FP16 is bit-exact against numpy's float64 -> float16 cast (round to nearest even), including subnormals.
    x = np.concatenate([rng.standard_normal(20000) * 10.0 ** rng.integers(-8, 5, 20000),
                        np.array([65504.0, 65519.0, 1e-8, 2.0 ** -24, 3 * 2.0 ** -26])])
    assert np.array_equal(quantize(x, FP16, saturate=False), x.astype(np.float16).astype(np.float64))
    # 3. BF16 against the classic float32 bit trick (round to nearest even on the upper 16 bits).
    x32 = (rng.standard_normal(20000) * 10.0 ** rng.integers(-30, 30, 20000)).astype(np.float32)
    b = x32.view(np.uint32).astype(np.uint64)
    ref = (((b + 0x7FFF + ((b >> 16) & 1)) >> 16) << 16).astype(np.uint32).view(np.float32).astype(np.float64)
    assert np.array_equal(quantize(x32.astype(np.float64), BF16), ref)
    # 4. Every code of every <= 8-bit format survives decode -> encode, and quantize() agrees with a brute-force
    #    nearest-value search (ties to the even code) on random and midpoint inputs.
    for fmt in (FP8_E4M3, FP8_E5M2, FP6_E2M3, FP6_E3M2, FP4_E2M1):
        codes = np.arange(2 ** fmt.bits)
        vals = decode(codes, fmt)
        fin = np.isfinite(vals)
        assert np.array_equal(encode(vals[fin], fmt), codes[fin]), fmt.name
        grid = np.unique(vals[fin])
        mids = (grid[1:] + grid[:-1]) / 2
        xs = np.concatenate([rng.uniform(-fmt.max, fmt.max, 5000), mids])
        idx = np.clip(np.searchsorted(grid, xs), 1, len(grid) - 1)
        lo, hi = grid[idx - 1], grid[idx]
        pick_hi = (xs - lo > hi - xs) | ((xs - lo == hi - xs) & (encode(hi, fmt) % 2 == 0))
        brute = np.where(pick_hi, hi, lo)
        assert np.array_equal(np.abs(quantize(xs, fmt)), np.abs(brute)), fmt.name
    # 5. Overflow conventions.
    assert quantize(500.0, FP8_E4M3) == 448 and np.isnan(quantize(500.0, FP8_E4M3, saturate=False))
    assert np.isinf(quantize(70000.0, FP16, saturate=False)) and quantize(7.0, FP4_E2M1) == 6
    assert encode(1.5, FP8_E4M3) == 0x3C and decode(0x7F, FP8_E4M3) != decode(0x7F, FP8_E4M3)   # NaN
    # 6. Block formats: within a scaled block the MANTISSA bits decide the error -- MXINT8 (7 magnitude bits) beats
    #    E4M3 and E2M3 (3 mantissa bits each, about equal), which beat E5M2 (2 bits), which beats E2M1 (1 bit).
    x = rng.standard_normal((64, 256))
    errs = {f.name: np.mean((mx_quantize(x, f) - x) ** 2)
            for f in (MXFP8_E4M3, MXFP8_E5M2, MXFP6_E2M3, MXFP4, MXINT8)}
    e3 = (errs["MXFP8 (E4M3)"], errs["MXFP6 (E2M3)"])
    assert errs["MXINT8"] < min(e3) and max(e3) < errs["MXFP8 (E5M2)"] < errs["MXFP4 (E2M1)"], errs
    assert abs(e3[0] / e3[1] - 1) < 0.25, e3
    assert np.mean((nvfp4_quantize(x) - x) ** 2) < errs["MXFP4 (E2M1)"]
    assert np.mean((smx_quantize(x, 4) - x) ** 2) < np.mean((smx_quantize(x, 2) - x) ** 2)
    # 7. Stochastic rounding is unbiased: the mean of many SR roundings of 0.3 in FP4 (grid 0, 0.5) is ~0.3.
    sr = quantize(np.full(100000, 0.3), FP4_E2M1, rounding="stochastic", rng=rng)
    assert abs(sr.mean() - 0.3) < 0.005 and set(np.unique(sr)) == {0.0, 0.5}
    print("numfmt.py self-test passed")
