"""
arith_cost.py -- what a multiply, an add and a dot product cost in each number format (45 nm model)
====================================================================================================

[Why we need it]
    "Fewer bits, more work" is only true if narrow arithmetic is really cheaper. This module prices it, starting
    from Horowitz's 45 nm table (Lecture 1) and two structural facts:
    1. an integer multiplier is an array of partial products: area and energy grow roughly with bits^2
       (Horowitz's 8- and 32-bit multipliers give an exponent of about 1.8); an adder grows ~linearly;
    2. a floating-point multiplier multiplies the SIGNIFICANDS (mantissa + hidden bit) and adds the exponents;
       its cost is dominated by the significand multiplier, so it is modeled as a power law in the significand
       width through Horowitz's FP16 (11-bit significand) and FP32 (24-bit) multipliers.
    On top: the cost of a MAC (multiplier + accumulator adder), the width of an accumulator that sums products
    EXACTLY (why FP4/FP6 dot products can use small integer adder trees), and the cost of applying block scales
    before (prologue) or after (epilogue) a block's dot product -- the question of HW2.

[Usage]
    import arith_cost as ac, numfmt as nf
    ac.mult_energy_pj(nf.FP8_E4M3); ac.mac_energy_pj(nf.FP8_E4M3, acc="fp32")
    ac.exact_accumulator_bits(nf.FP4_E2M1, terms=32)     # bits of a fixed-point accumulator that never rounds

[Edge cases and honesty]
    - These are MODELS calibrated on two or three points of one 45 nm table. They capture the scaling with width,
      not the details of any real design (Booth encoding, shared exponent logic, pipelining).
    - Formats below 8 bits are extrapolations of the fits; treat their absolute values as rough, their RATIOS as
      the point.
"""

import math

import numpy as np

import course_path

course_path.use("lecture01")

import numfmt as nf  # noqa: E402
from energy_model import HOROWITZ_AREA_UM2, HOROWITZ_OP_PJ, op_area_um2, op_energy_pj, power_law  # noqa: E402

# Power laws for floating-point units in terms of the significand width p = mbits + 1 (FP16: 11, FP32: 24).
_P16, _P32 = 11, 24
FP_MULT_E = power_law(_P16, HOROWITZ_OP_PJ[("fp", "mult", 16)], _P32, HOROWITZ_OP_PJ[("fp", "mult", 32)])
FP_MULT_A = power_law(_P16, HOROWITZ_AREA_UM2[("fp", "mult", 16)], _P32, HOROWITZ_AREA_UM2[("fp", "mult", 32)])
FP_ADD_E = power_law(_P16, HOROWITZ_OP_PJ[("fp", "add", 16)], _P32, HOROWITZ_OP_PJ[("fp", "add", 32)])
FP_ADD_A = power_law(_P16, HOROWITZ_AREA_UM2[("fp", "add", 16)], _P32, HOROWITZ_AREA_UM2[("fp", "add", 32)])


def _p(fmt):
    """Significand width of a float format (mantissa bits + the hidden 1)."""
    return fmt.mbits + 1


def mult_energy_pj(fmt):
    """
    Energy of one multiplication in a format (45 nm).
    [Args] fmt: numfmt.IntFormat (integer multiplier of fmt.bits bits) or numfmt.FloatFormat (significand model)
    [Returns] pJ
    """
    if isinstance(fmt, nf.IntFormat):
        return op_energy_pj("int", "mult", fmt.bits)
    a, alpha = FP_MULT_E
    return a * _p(fmt) ** alpha


def mult_area_um2(fmt):
    """Area of one multiplier (45 nm, µm^2); same models as mult_energy_pj."""
    if isinstance(fmt, nf.IntFormat):
        return op_area_um2("int", "mult", fmt.bits)
    a, alpha = FP_MULT_A
    return a * _p(fmt) ** alpha


def add_energy_pj(kind, bits=None, fmt=None):
    """
    Energy of one addition: kind "int" with `bits`, or kind "fp" with a FloatFormat `fmt` (significand model).
    """
    if kind == "int":
        return op_energy_pj("int", "add", bits)
    a, alpha = FP_ADD_E
    return a * _p(fmt) ** alpha


def add_area_um2(kind, bits=None, fmt=None):
    """Area of one adder (45 nm, µm^2)."""
    if kind == "int":
        return op_area_um2("int", "add", bits)
    a, alpha = FP_ADD_A
    return a * _p(fmt) ** alpha


def mac_energy_pj(fmt, acc="auto"):
    """
    Energy of one multiply-accumulate: a multiplier in `fmt` + an accumulator adder.

    [Args] acc: "auto" (int32 adder for integer formats, FP32 adder for float formats -- the usual choices), "fp32",
        "fp16", or an int giving the width of an integer (fixed-point) accumulator
    [Returns] pJ
    [Edge cases] The FP32 accumulate costs 0.9 pJ in this model -- MORE than an FP8 multiply. For low-precision
        float formats the accumulator, not the multiplier, decides the MAC energy unless products are summed in
        fixed point (see exact_accumulator_bits and block_dot_energy_pj).
    """
    m = mult_energy_pj(fmt)
    if acc == "auto":
        acc = 32 if isinstance(fmt, nf.IntFormat) else "fp32"
    if acc == "fp32":
        return m + add_energy_pj("fp", fmt=nf.FP32)
    if acc == "fp16":
        return m + add_energy_pj("fp", fmt=nf.FP16)
    return m + add_energy_pj("int", bits=int(acc))


def exact_accumulator_bits(fmt, terms):
    """
    Width of a fixed-point (integer) accumulator that adds `terms` products of two `fmt` values without rounding.

    [Idea] Every product of two values of a float format is a multiple of min_subnormal^2 and at most max^2, so it
        is an integer in units of min_subnormal^2 with log2(max^2 / min_subnormal^2) bits of magnitude; adding
        `terms` of them needs log2(terms) more bits, plus a sign bit. For FP4 E2M1 (min 0.5, max 6) a 32-term dot
        product fits in 14 bits; for FP8 E4M3 (min 2^-9, max 448) it needs 42 bits; for integers (k bits) the
        familiar 2k - 1 + log2(terms).
    [Returns] int bits
    """
    if isinstance(fmt, nf.IntFormat):
        mag = 2 * (fmt.bits - 1)
    else:
        mag = math.ceil(math.log2(fmt.max ** 2 / fmt.min_subnormal ** 2))
    return mag + math.ceil(math.log2(terms)) + 1


def block_dot_energy_pj(fmt, block=32, scaling="epilogue", accumulate="fixed"):
    """
    Energy PER MAC of a block-scaled dot product (MX-style: one shared scale per `block` elements of each operand).

    [Idea] sum_i (s_a a_i)(s_b b_i) = s_a s_b sum_i a_i b_i. Two ways to apply the scales:
        prologue : dequantize every element first -- with a power-of-two scale this is an 8-bit addition to each
                   element's exponent, turning it into a BF16 number -- then run the dot product in BF16 with FP32
                   accumulation (a BF16 multiply + an FP32 add per MAC);
        epilogue : multiply the narrow elements, sum the products in an exact fixed-point adder tree
                   (accumulate="fixed") or in FP32 (accumulate="fp32"), then apply s_a * s_b ONCE per block
                   (for power-of-two E8M0 scales this is an exponent addition) and add the block result into an
                   FP32 accumulator.
    [Args] fmt: element format; block: elements per scale; scaling: "prologue" or "epilogue"
    [Returns] pJ per MAC (per element pair)
    [Edge cases] The epilogue with power-of-two scales costs one 8-bit integer add (combine exponents) plus one FP32
        add per block; with E4M3 scales (NVFP4) it would be a small float multiply instead -- still per block.
    """
    fp32_add = add_energy_pj("fp", fmt=nf.FP32)
    if scaling == "prologue":                             # rescale a_i and b_i, then a BF16 x BF16 -> FP32 MAC
        return 2 * add_energy_pj("int", bits=8) + mult_energy_pj(nf.BF16) + fp32_add
    mul = mult_energy_pj(fmt)
    if accumulate == "fixed":
        acc = add_energy_pj("int", bits=exact_accumulator_bits(fmt, block))
    else:
        acc = fp32_add
    per_block = add_energy_pj("int", bits=8) + fp32_add    # combine the two E8M0 exponents, add into FP32
    return mul + acc + per_block / block


FORMATS = [nf.INT8, nf.INT4, nf.FP32, nf.FP16, nf.BF16, nf.FP8_E4M3, nf.FP8_E5M2, nf.FP6_E2M3, nf.FP6_E3M2,
           nf.FP4_E2M1]


if __name__ == "__main__":
    # Calibration points are reproduced exactly.
    assert abs(mult_energy_pj(nf.FP16) - 1.1) < 1e-12 and abs(mult_energy_pj(nf.FP32) - 3.7) < 1e-12
    assert abs(mult_energy_pj(nf.INT8) - 0.2) < 1e-12 and abs(add_energy_pj("fp", fmt=nf.FP32) - 0.9) < 1e-12
    # Narrower is cheaper, monotonically in significand width.
    e = [mult_energy_pj(f) for f in (nf.FP32, nf.BF16, nf.FP8_E4M3, nf.FP4_E2M1)]
    assert all(a > b for a, b in zip(e, e[1:])), e
    assert exact_accumulator_bits(nf.FP4_E2M1, 32) == 14 and exact_accumulator_bits(nf.FP8_E4M3, 32) == 42
    assert exact_accumulator_bits(nf.INT8, 32) == 20
    # The epilogue is far cheaper than the prologue.
    assert block_dot_energy_pj(nf.FP4_E2M1) < 0.2 * block_dot_energy_pj(nf.FP4_E2M1, scaling="prologue")
    print("arith_cost.py self-test passed")
    for f in FORMATS:
        print(f"  {f.name:10s} mult {mult_energy_pj(f):6.3f} pJ {mult_area_um2(f):8.0f} um2   MAC {mac_energy_pj(f):6.3f} pJ")
