"""
quant.py -- quantizing tensors: scales and granularity, error metrics, synthetic LLM-like data, per-block format choice
=====================================================================================================================

[Why we need it]
    numfmt.py says how ONE number is rounded. Quantizing a model means choosing, for whole tensors, a format and
    SCALES: one scale per tensor, per channel (row), or per small group of elements. The finer the granularity, the
    better each scale fits its data -- and the more scale bits must be stored and applied. This module provides
    1. quantize_2d(): symmetric max-scaled quantization of a 2D array with per-tensor, per-row or per-group scales,
       for integer and floating-point element formats, plus the block formats of numfmt (MX, NVFP4);
    2. error metrics: SQNR (signal-to-quantization-noise ratio, dB) and relative error;
    3. synthetic data: Gaussian, Laplace and Student-t tensors, LLM-like weights (per-channel spread) and
       activations with a few OUTLIER channels (the phenomenon reported by Dettmers et al., LLM.int8(), 2022);
    4. a per-block FORMAT SELECTOR in the spirit of BlockDialect (Jang & Tambe, 2025): each block picks, from a
       small book of 4-bit formats, the one that represents it best.

[Usage]
    import quant as q, numfmt as nf
    W = q.llm_weights(4096, 4096, rng)
    Wq = q.quantize_2d(W, nf.INT4, "group", group=128)
    q.sqnr_db(W, Wq)

[Conventions] 2D arrays are (rows, columns) with groups/blocks running along the LAST axis: for weights stored as
    (output channels, input channels) a "row" scale is a per-output-channel scale and a group of 128 runs along the
    input dimension (the usual weight-only LLM quantization, e.g. "INT4 g128"); for activations (tokens, channels)
    a "row" scale is a per-token scale. Scales are kept in float64 here (their own rounding is ignored except
    where a format defines it, e.g. MX's E8M0 and NVFP4's E4M3 block scales).
"""

import numpy as np

import numfmt as nf

# =====================================================================================================================
# Error metrics
# =====================================================================================================================


def sqnr_db(x, xq):
    """
    Signal-to-quantization-noise ratio in dB: 10 log10(sum x^2 / sum (x - xq)^2).

    [Idea] Every extra bit of a uniform quantizer halves the step and cuts the noise power 4x: +6.02 dB per bit.
        SQNR is therefore a "bits of precision" meter: 20 dB ~ 3.3 bits, 40 dB ~ 6.6 bits.
    [Edge cases] An exact quantization returns inf.
    """
    x, xq = np.asarray(x, dtype=np.float64), np.asarray(xq, dtype=np.float64)
    noise = np.sum((x - xq) ** 2)
    return float("inf") if noise == 0 else float(10 * np.log10(np.sum(x ** 2) / noise))


def rel_error(y, yq):
    """Relative Frobenius error ||y - yq|| / ||y||."""
    y, yq = np.asarray(y, dtype=np.float64), np.asarray(yq, dtype=np.float64)
    return float(np.linalg.norm(y - yq) / np.linalg.norm(y))


# =====================================================================================================================
# Tensor quantization with scales
# =====================================================================================================================

def _scale_for(amax, fmt, clip):
    """Scale that maps clip * amax onto the format's largest value (zero where amax is zero)."""
    return np.where(amax > 0, clip * amax / fmt.max, 0.0)


def quantize_2d(x, fmt, mode="tensor", group=128, clip=1.0):
    """
    Symmetric quantization of a 2D array with scales per tensor, per row, or per group of `group` columns.

    [Idea] scale = clip * max|x| / (largest value of the format), computed over the elements that share it; each
        element is then rounded to the format's grid after division by its scale. clip < 1 deliberately saturates
        the few largest values to give everything else a finer grid (useful for heavy tails, Part 5 of script 02).
    [Args]
        x    : 2D array
        fmt  : numfmt.IntFormat (INT8, INT4), numfmt.FloatFormat (e.g. FP8_E4M3 per tensor), numfmt.MXFormat or
               numfmt.NVFP4Format (block formats: `mode` and `clip` are ignored, the format defines its scaling;
               `group` overrides the block size if mode == "group")
        mode : "tensor", "row" or "group"
    [Returns] float64 array of dequantized values
    [Edge cases] The last group of a row may be shorter (it is zero-padded internally). Rows or groups that are
        entirely zero stay zero.
    """
    x = np.asarray(x, dtype=np.float64)
    if isinstance(fmt, nf.MXFormat):
        return nf.mx_quantize(x, fmt, block=group if mode == "group" else None)
    if isinstance(fmt, nf.NVFP4Format):
        return nf.nvfp4_quantize(x, block=group if mode == "group" else fmt.block)
    if mode == "group":
        xb, n = nf._blocks(x, group)
        amax = np.max(np.abs(xb), axis=-1, keepdims=True)
        return nf._unblock(_apply(xb, fmt, _scale_for(amax, fmt, clip)), n)
    if mode == "row":
        amax = np.max(np.abs(x), axis=-1, keepdims=True)
    elif mode == "tensor":
        amax = np.max(np.abs(x))
    else:
        raise ValueError("mode must be 'tensor', 'row' or 'group'")
    return _apply(x, fmt, _scale_for(amax, fmt, clip))


def _apply(x, fmt, scale):
    """Quantize x with the given scale(s) to an IntFormat or FloatFormat; dequantized result."""
    if isinstance(fmt, nf.IntFormat):
        return nf.quantize_int(x, fmt, scale)
    safe = np.where(scale > 0, scale, 1.0)
    return np.where(scale > 0, nf.quantize(x / safe, fmt) * safe, 0.0)


def mse_optimal_clip(x, fmt, mode="tensor", group=128, grid=np.linspace(0.3, 1.0, 36)):
    """
    The clip ratio (fraction of max|x| mapped to the format's max) that minimizes the quantization MSE.
    [Returns] (best clip, best SQNR in dB)
    [Edge cases] A brute-force search over `grid`; good enough to show the effect, slow for huge tensors.
    """
    best = max(grid, key=lambda c: sqnr_db(x, quantize_2d(x, fmt, mode, group, clip=c)))
    return float(best), sqnr_db(x, quantize_2d(x, fmt, mode, group, clip=best))


# =====================================================================================================================
# Synthetic data
# =====================================================================================================================

def gaussian(shape, rng):
    return rng.standard_normal(shape)


def laplace(shape, rng):
    return rng.laplace(size=shape) / np.sqrt(2)          # unit variance


def student_t(shape, rng, df=3):
    """Heavy-tailed: occasional values 10-20 sigma out (df = 3), like many trained weight and activation tensors."""
    return rng.standard_t(df, size=shape) / np.sqrt(df / (df - 2))


def llm_weights(n_out, n_in, rng, channel_spread=0.3):
    """
    A weight matrix (output channels x input channels) with per-output-channel scales spread log-normally.
    [Idea] Trained layers have rows of quite different magnitudes; that spread is what per-channel scales absorb.
    """
    scales = np.exp(channel_spread * rng.standard_normal((n_out, 1)))
    return rng.standard_normal((n_out, n_in)) * scales / np.sqrt(n_in)


def llm_activations(tokens, d, rng, n_outliers=6, outlier_scale=40.0, channel_spread=0.3):
    """
    Activations (tokens x channels) with a few OUTLIER channels.

    [Idea] Dettmers et al. (LLM.int8(), 2022) report that beyond a few billion parameters, transformer activations
        develop a handful of feature dimensions whose magnitudes are up to ~20-100x the rest, in almost every
        token. Here: Gaussian activations with mild per-channel spread, and `n_outliers` channels scaled by
        `outlier_scale`. This is a synthetic stand-in for the phenomenon, not data from a real model.
    [Returns] (array, indices of the outlier channels)
    """
    x = rng.standard_normal((tokens, d)) * np.exp(channel_spread * rng.standard_normal(d))
    idx = rng.choice(d, n_outliers, replace=False)
    x[:, idx] *= outlier_scale
    return x, np.sort(idx)


# =====================================================================================================================
# Per-block format selection (BlockDialect-style)
# =====================================================================================================================

# A small "format book" of 4-bit sign-magnitude formats: each lists its 8 non-negative magnitudes. The element sign
# is the 4th bit. They differ in how the magnitudes are spread: uniformly (INT-like), as FP4 E2M1, or
# logarithmically (powers of two, good for blocks with a wide spread).
DIALECTS = {
    "FP4 E2M1": np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6]),
    "uniform (INT4-like)": np.array([0, 1, 2, 3, 4, 5, 6, 7]),
    "log (E3M0-like)": np.array([0, 0.0625, 0.125, 0.25, 0.5, 1, 2, 4]),
}


def grid_quantize(v, grid):
    """
    Round magnitudes v (>= 0) to the nearest value of a sorted grid (ties to the lower value).
    [Edge cases] Values beyond the top saturate to it.
    """
    idx = np.clip(np.searchsorted(grid, v), 1, len(grid) - 1)
    lo, hi = grid[idx - 1], grid[idx]
    return np.where(v - lo > hi - v, hi, lo)


def dialect_quantize(x, block=16, book=DIALECTS):
    """
    Quantize along the last axis in blocks; every block picks the 4-bit format from `book` with the lowest error.

    [Idea] BlockDialect (Jang & Tambe, 2025) observes that blocks of LLM tensors have different shapes (some
        nearly uniform, some with one large value), so no single 4-bit format suits them all; it assigns each block
        a format ("dialect") from a format book and stores the choice in a few extra bits. The paper's book
        consists of FP4 variants; ours is a simpler illustration with three differently spread grids. Scales follow
        NVFP4: per-tensor FP32 scale g, per-block E4M3 scale of amax / (grid top), so each format's top value
        maps onto the block's largest element.
    [Returns] (dequantized array, dict format name -> fraction of blocks that chose it)
    [Edge cases] Selector cost: ceil(log2(len(book))) bits per block on top of the 8-bit scale.
    """
    xb, n = nf._blocks(x, block)
    amax_t = float(np.max(np.abs(xb)))
    g = amax_t / (nf.FP8_E4M3.max * 6.0) if amax_t > 0 else 1.0
    amax = np.max(np.abs(xb), axis=-1, keepdims=True)
    best = None
    names = list(book)
    for i, name in enumerate(names):
        grid = book[name]
        s = nf.quantize(amax / grid[-1] / g, nf.FP8_E4M3) * g
        safe = np.where(s > 0, s, 1.0)
        q = np.sign(xb) * grid_quantize(np.abs(xb) / safe, grid) * safe
        q = np.where(s > 0, q, 0.0)
        err = np.sum((q - xb) ** 2, axis=-1, keepdims=True)
        if best is None:
            best, best_err, choice = q, err, np.zeros_like(err, dtype=int)
        else:
            better = err < best_err
            best = np.where(better, q, best)
            best_err = np.where(better, err, best_err)
            choice = np.where(better, i, choice)
    frac = {name: float(np.mean(choice == i)) for i, name in enumerate(names)}
    return nf._unblock(best, n), frac


def dialect_bits_per_element(block=16, book=DIALECTS, scale_bits=8):
    """4 bits per element + (block scale + selector bits) / block."""
    return 4 + (scale_bits + int(np.ceil(np.log2(len(book))))) / block


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    x = gaussian((256, 1024), rng)
    # ~6 dB per bit: INT8 vs INT4 per-row SQNR differs by roughly 4 bits x 6 dB.
    s8, s4 = sqnr_db(x, quantize_2d(x, nf.INT8, "row")), sqnr_db(x, quantize_2d(x, nf.INT4, "row"))
    assert 20 < s8 - s4 < 26, (s8, s4)
    # Finer granularity helps on data with per-row spread.
    w = llm_weights(256, 1024, rng)
    t, r, g = (sqnr_db(w, quantize_2d(w, nf.INT4, m, 128)) for m in ("tensor", "row", "group"))
    assert t < r < g, (t, r, g)
    # Outlier channels ruin per-tensor INT8 activations; per-token scales do not fix it (outliers are in every token).
    a, idx = llm_activations(128, 1024, rng)
    normal = np.setdiff1d(np.arange(1024), idx)
    qa = quantize_2d(a, nf.INT8, "tensor")
    assert sqnr_db(a[:, normal], qa[:, normal]) < sqnr_db(x, quantize_2d(x, nf.INT8, "tensor")) - 10
    # Clipping helps heavy tails at 4 bits.
    h = student_t((128, 1024), rng)
    c, best = mse_optimal_clip(h, nf.INT4)
    assert c < 1 and best > sqnr_db(h, quantize_2d(h, nf.INT4)), (c, best)
    # The dialect selector is at least as good as its FP4 member alone.
    dq, frac = dialect_quantize(h)
    fp4_only, _ = dialect_quantize(h, book={"FP4 E2M1": DIALECTS["FP4 E2M1"]})
    assert sqnr_db(h, dq) >= sqnr_db(h, fp4_only) and abs(sum(frac.values()) - 1) < 1e-9
    print("quant.py self-test passed")
