"""
metrics.py -- efficiency metrics of ML accelerators, Eyeriss-style energy accounting, and a zoo of layer shapes
=============================================================================================================

[Why we need it]
    "Our chip delivers 400 TOPS at 10 TOPS/W" says almost nothing until we know: at which precision? dense or
    "with sparsity"? at what utilization on which network? including DRAM or only the core? in which process
    node? Lecture 3 is about measuring accelerators honestly. This module holds the formulas:
    1. throughput metrics: peak ops/s, effective ops/s, utilization;
    2. efficiency metrics: ops/J (= ops/s per W), energy per op, ops/s per mm^2, energy per inference;
    3. how a quoted number is built from a dense one (precision and sparsity multipliers) -- and taken apart;
    4. technology-node normalization with an explicit, user-chosen scaling exponent (because there is no single
       correct one);
    5. Eyeriss-style ENERGY ACCOUNTING: energy = sum over storage levels of (accesses x cost per access), with
       Eyeriss's normalized costs (RF 1, PE array 2, global buffer 6, DRAM 200, relative to one MAC);
    6. a zoo of real layer shapes written as GEMMs (convolutions through im2col), shared by the scripts.

[Usage]
    from metrics import peak_ops, utilization, LAYERS, conv_as_gemm, eyeriss_energy
    peak_ops(macs=4096, freq_hz=1e9)        # 8.19e12 ops/s (1 MAC = 2 ops)

[Conventions] 1 MAC = 2 ops. "Dense" means without structured-sparsity doubling. Energies in pJ unless stated.
"""

import math
from dataclasses import dataclass

import course_path

course_path.use("lecture01")

from energy_model import EYERISS_RELATIVE  # noqa: E402

# =====================================================================================================================
# Throughput and efficiency
# =====================================================================================================================


def peak_ops(macs, freq_hz, ops_per_mac=2):
    """
    Peak throughput: every MAC busy every cycle.
    [Args] macs: MAC units; freq_hz: clock; ops_per_mac: 2 by convention (a multiply and an add)
    [Returns] ops per second
    """
    return macs * freq_hz * ops_per_mac


def utilization(useful_ops, seconds, peak):
    """
    Fraction of the peak actually delivered: useful ops / (time x peak).
    [Edge cases] Only USEFUL ops count: padded MACs, recomputation and ops on structured-sparse zeros are not
        work the user asked for. Returns 0 for zero time or peak.
    """
    if seconds <= 0 or peak <= 0:
        return 0.0
    return useful_ops / (seconds * peak)


def ops_per_joule(ops_per_s, watts):
    """Energy efficiency: ops/s per W = ops per joule (1 TOPS/W = 1e12 ops/J = 1 op/pJ)."""
    return ops_per_s / watts


def pj_per_op(ops_per_s, watts):
    """Energy per operation in pJ (the inverse view of TOPS/W: 10 TOPS/W = 0.1 pJ/op)."""
    return watts / ops_per_s * 1e12


def quoted_tops(dense_ops, precision_factor=1, sparsity_factor=1):
    """
    How a headline number is built: dense ops x (precision multiplier) x (sparsity multiplier).

    [Idea] Hardware that runs int8 at rate R usually runs int4 at 2R (narrower multipliers, Lecture 4), and
        "2:4 structured sparsity" lets it skip half the multiplications, which vendors count as 2R "effective".
        The same silicon can be quoted at R, 2R or 4R.
    [Returns] the quoted ops/s
    """
    return dense_ops * precision_factor * sparsity_factor


def scale_to_node(value, from_nm, to_nm, exponent):
    """
    Scale an energy (or area) from one process node to another: value x (to_nm / from_nm) ** exponent.

    [Idea] Comparing a 65 nm chip with a 5 nm chip requires a scaling rule, and the "right" exponent is uncertain:
        classical (Dennard) scaling made energy per op fall roughly like (feature size)^2 or faster, but since
        ~2005 supply voltage has barely dropped, so energy falls much more slowly. Area scales closer to
        (feature size)^2, but SRAM and analog scale worse than logic. Rather than hide a constant, the caller
        chooses the exponent -- and should report results for a range of exponents.
    [Edge cases] Node names below ~20 nm are marketing labels, not physical sizes; treat any result as an
        order-of-magnitude statement.
    """
    return value * (to_nm / from_nm) ** exponent


# =====================================================================================================================
# Eyeriss-style energy accounting
# =====================================================================================================================

# Eyeriss's normalized energy of fetching one operand from each level, relative to one MAC (ISCA 2016 / JSSC 2017),
# re-keyed from Lecture 1's table for use as a cost model.
EYERISS_COSTS = {
    "MAC": EYERISS_RELATIVE[0][1],
    "RF": EYERISS_RELATIVE[1][1],
    "array": EYERISS_RELATIVE[2][1],
    "buffer": EYERISS_RELATIVE[3][1],
    "DRAM": EYERISS_RELATIVE[4][1],
}


def eyeriss_energy(accesses, costs=None):
    """
    Energy in units of one MAC: sum over levels of accesses x normalized cost.

    [Args] accesses: dict level -> number of accesses (levels: "MAC", "RF", "array", "buffer", "DRAM");
        costs: dict level -> cost per access (default EYERISS_COSTS)
    [Returns] dict level -> energy (same keys), in MAC units
    [Edge cases] Unknown levels raise KeyError (a typo would otherwise silently cost nothing).
    """
    costs = costs or EYERISS_COSTS
    return {lvl: n * costs[lvl] for lvl, n in accesses.items()}


def energy_per_mac(accesses_per_mac, costs=None):
    """
    Energy of one MAC, in MAC units, given how many accesses each level serves per MAC.

    [Idea] If an operand fetched from DRAM is used by 100 MACs, DRAM serves 1/100 access per MAC and contributes
        200 / 100 = 2 MAC-units of energy to every MAC. The REUSE at each level (MACs per access = 1 / accesses
        per MAC) is what dataflows and buffer sizes decide; this function turns it into energy.
    [Args] accesses_per_mac: dict level -> accesses per MAC (summed over all operands; e.g. a MAC with all three
        operands -- two inputs and a partial sum -- in registers needs 3 RF accesses); costs: as in eyeriss_energy
    [Returns] dict level -> MAC units per MAC, including "MAC": 1
    """
    costs = costs or EYERISS_COSTS
    out = {"MAC": costs["MAC"]}
    for lvl, a in accesses_per_mac.items():
        out[lvl] = costs[lvl] * a
    return out


# =====================================================================================================================
# Layer shapes: convolutions and transformer operators as GEMMs
# =====================================================================================================================

@dataclass(frozen=True)
class Layer:
    """
    One layer as a GEMM C[M, N] = A[M, K] @ B[K, N], possibly repeated over `groups` independent groups.

    [Fields] name; M (output rows: pixels x batch, or tokens); K (reduction: input channels x filter size);
        N (output columns: output channels); groups (depthwise convolutions: one tiny GEMM per channel; attention:
        one GEMM per head); note (where the shape comes from); in_elems (distinct input elements, see below)
    [Properties] macs = groups * M * K * N; inputs = distinct input elements; weights; outputs
    [Edge cases] For a convolution the GEMM's A matrix (im2col) repeats every input pixel R x S times, so its size
        M x K overstates the real input tensor ~9x for a 3x3 filter. conv_as_gemm() records the true input size
        (batch x C x H x W) in in_elems; memory traffic should use `inputs`, not M x K.
    """
    name: str
    M: int
    K: int
    N: int
    groups: int = 1
    note: str = ""
    in_elems: int = 0

    @property
    def macs(self):
        return self.groups * self.M * self.K * self.N

    @property
    def inputs(self):
        """Distinct input elements (the activation tensor), not the im2col matrix."""
        return self.in_elems or self.groups * self.M * self.K

    @property
    def weights(self):
        return self.groups * self.K * self.N

    @property
    def outputs(self):
        return self.groups * self.M * self.N


def conv_as_gemm(name, batch, C, H, W, K_out, R, S, stride=1, pad=None, groups=1, note=""):
    """
    A convolution as a GEMM (im2col): M = batch x P x Q output pixels, K = (C/groups) x R x S, N = K_out/groups.

    [Idea] Every output pixel is a dot product between an R x S x C patch of the input and a filter; lining the
        patches up as rows of a matrix turns the convolution into one matrix multiplication. Accelerators do not
        necessarily build that matrix in memory, but its SHAPE is what decides how well a PE is used.
    [Args] pad: default "same" padding (R // 2); groups = C for a depthwise convolution
    [Returns] Layer
    """
    pad = R // 2 if pad is None else pad
    P = (H + 2 * pad - R) // stride + 1
    Q = (W + 2 * pad - S) // stride + 1
    return Layer(name, batch * P * Q, (C // groups) * R * S, K_out // groups, groups, note, batch * C * H * W)


# A zoo of layer shapes used by the scripts (batch 1 unless stated). CNN shapes from ResNet-50 and MobileNetV2;
# transformer shapes from Llama 3 8B (d_model 4096, 32 query heads of 128, MLP 14336) at a 512-token prompt.
LAYERS = [
    conv_as_gemm("ResNet-50 conv1 7x7/2", 1, 3, 224, 224, 64, 7, 7, stride=2, note="first layer: only 3 input channels"),
    conv_as_gemm("ResNet-50 3x3 (stage 2)", 1, 64, 56, 56, 64, 3, 3, note="the bulk of a CNN"),
    conv_as_gemm("ResNet-50 1x1 (stage 2)", 1, 256, 56, 56, 64, 1, 1, note="pointwise"),
    conv_as_gemm("MobileNetV2 depthwise 3x3", 1, 144, 56, 56, 144, 3, 3, groups=144, note="one 3x3 filter per channel"),
    Layer("FC 2048->1000, batch 1", 1, 2048, 1000, note="classifier: a matrix-vector product"),
    Layer("Llama-8B q_proj, 512 tokens", 512, 4096, 4096, note="prefill GEMM"),
    Layer("Llama-8B attention QK^T, 512 tok", 512, 128, 512, groups=32, note="per head: 512 x 128 x 512"),
    Layer("Llama-8B MLP up, decode (1 token)", 1, 4096, 14336, note="decode: matrix-vector"),
]


def padded_utilization(dim, width):
    """
    Fraction of `width` parallel slots that do useful work when a dimension of size `dim` is cut into chunks of
    `width`: dim / (ceil(dim / width) * width). 64 channels on 8 lanes: 1.0; 3 channels on 8 lanes: 0.375.
    """
    if dim <= 0:
        return 0.0
    return dim / (math.ceil(dim / width) * width)


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

if __name__ == "__main__":
    assert peak_ops(4096, 1e9) == 8.192e12
    assert abs(pj_per_op(10e12, 1.0) - 0.1) < 1e-12              # 10 TOPS/W = 0.1 pJ/op
    assert quoted_tops(100e12, 2, 2) == 400e12
    l = conv_as_gemm("x", 1, 64, 56, 56, 64, 3, 3)
    assert (l.M, l.K, l.N) == (3136, 576, 64) and l.macs == 3136 * 576 * 64 and l.inputs == 64 * 56 * 56
    dw = LAYERS[3]
    assert (dw.M, dw.K, dw.N, dw.groups) == (3136, 9, 1, 144)
    assert padded_utilization(3, 8) == 0.375 and padded_utilization(64, 8) == 1.0
    e = eyeriss_energy({"MAC": 10, "DRAM": 1})
    assert e == {"MAC": 10, "DRAM": 200}
    print("metrics.py self-test passed")
