"""
pe.py -- a SIMD processing element (PE) in the style of MAGNet, simulated cycle by cycle (the block of Lab 1)
=============================================================================================================

[Why we need it]
    The processing element is the brick of almost every ML accelerator: MAGNet, Simba, NVDLA, and -- with a
    different arrangement -- the TPU's systolic array. Lab 1 of CS 217 designs one in C++ with HLS. This module
    builds the same block as a Python model, so that its behavior can be measured: how many cycles a layer takes,
    where cycles are lost, how many times each buffer is read, and how all of that depends on the PE's shape
    (lanes x vector width) and on its DATAFLOW (which operand stays put while the others stream).

[The PE]
                         input buffer (IB) ----- one input vector (vec elements) per cycle, broadcast to all lanes
                                |
        weight buffer (WB) -> [lane 0: vec multipliers + adder tree] -> accumulation buffer (AB) / accumulator register
                           -> [lane 1: vec multipliers + adder tree] -> ...
                           -> ...                                       (lanes outputs per cycle)
    - lanes  : vector MAC units; each computes one OUTPUT CHANNEL (one column n of the weight matrix)
    - vec    : multipliers per lane; each lane computes a vec-wide dot product per cycle (vec INPUT channels)
    - So the PE performs lanes x vec MACs per cycle. It computes C[M, N] = A[M, K] @ B[K, N] with int8 inputs
      (A = activations, B = weights) and int32 accumulation.

[Dataflows] (the order of the loops, i.e. which operand stays in the PE while the others stream)
    WS  weight-stationary : for each (n-tile, k-chunk): load lanes x vec weights into lane registers once, then
                            stream all M input vectors past them; partial sums go to the accumulation buffer
                            (read-modify-write) and come back K/vec times.
    OS  output-stationary : for each (n-tile, m): keep lanes partial sums in accumulator registers, stream the
                            K/vec input vectors and weight blocks; write each output once.
    IS  input-stationary  : for each (m, k-chunk): hold one input vector, stream the weight blocks of all n-tiles;
                            partial sums are read-modified-written in the accumulation buffer.

[Timing model]
    - One vector-MAC issue per cycle at most (all lanes in lockstep: SIMD).
    - The weight buffer delivers wb_width elements per cycle. WS loads a block of lanes x vec weights in
      ceil(lanes*vec / wb_width) cycles -- hidden behind the previous block's compute if the weight registers are
      double-buffered and the block is long enough. OS and IS need lanes*vec weights EVERY issue, so an issue
      takes ceil(lanes*vec / wb_width) cycles.
    - A read-modify-write of the accumulation buffer takes acc_latency cycles: the same accumulator can be updated
      again only acc_latency cycles later (a recurrence, Lecture 2). WS/IS stall when updates of one accumulator
      come closer than that; OS accumulates in a register with single-cycle feedback.
    - K is padded up to a multiple of vec and N up to a multiple of lanes: the padded MACs are issued (wasted).
    - At the end the pipeline drains: mac_latency + (acc_latency for WS/IS, 1 for OS's final write).

[Usage]
    import numpy as np, pe
    cfg = pe.PEConfig(lanes=8, vec=8)
    A = np.random.randint(-128, 128, (20, 30)); B = np.random.randint(-128, 128, (30, 12))
    r = pe.simulate(cfg, A, B, "WS")          # cycle by cycle, with real arithmetic
    assert (r.C == A @ B).all(); print(r.cycles, r.utilization)
    pe.estimate(cfg, 20, 30, 12, "WS")       # the same counts from a fast block-level model (no arithmetic)

[Edge cases]
    - simulate() executes every vector-MAC issue in Python with numpy arithmetic: fine up to ~10^5 issues
      (a fraction of a second); use estimate() for big layers. The self-test checks that both agree exactly.
    - Buffers are assumed large enough to hold the operands of the GEMM (tiling across a global buffer is
      Lecture 7's topic); their capacities matter only for the energy per access (energy()).
"""

import math
from dataclasses import dataclass, field

import course_path

course_path.use("lecture01")

from energy_model import mac_energy_pj, sram_pj_per_byte  # noqa: E402

DATAFLOWS = ("WS", "OS", "IS")


@dataclass(frozen=True)
class PEConfig:
    """
    The design parameters of the PE (the knobs of Lab 1 and of MAGNet's PE template).

    [Fields]
        lanes, vec      : vector MAC units and multipliers per unit (lanes x vec MACs per cycle)
        wb_width        : weight-buffer read width in elements per cycle; 0 = lanes * vec (enough for OS/IS)
        acc_latency     : cycles of an accumulation-buffer read-modify-write
        mac_latency     : pipeline depth of multiply + adder tree
        double_buffer   : WS weight registers are double-buffered (load the next block while computing)
        wb_bytes, ib_bytes, ab_bytes : buffer capacities (only used for energy per access)
        freq_ghz        : clock, for converting cycles to time
    """
    lanes: int = 8
    vec: int = 8
    wb_width: int = 0
    acc_latency: int = 3
    mac_latency: int = 2
    double_buffer: bool = True
    wb_bytes: int = 32 * 1024
    ib_bytes: int = 16 * 1024
    ab_bytes: int = 8 * 1024
    freq_ghz: float = 1.0

    @property
    def macs(self):
        """MACs per cycle at full utilization."""
        return self.lanes * self.vec

    @property
    def wbw(self):
        """Effective weight-buffer read width (elements per cycle)."""
        return self.wb_width or self.lanes * self.vec


@dataclass
class PEResult:
    """
    The outcome of running one GEMM on the PE.

    [Fields]
        C            : the result (numpy int64 array) -- None for estimate()
        cycles       : total cycles including pipeline drain
        useful_macs  : M * K * N
        issued_macs  : issues x lanes x vec (includes the padding of K and N)
        stalls       : dict cause -> cycles: "weight load" (WS waiting for weights), "accumulator" (RMW
                       hazard), "weight bandwidth" (OS/IS issues slowed by the weight buffer), "drain"
        counts       : dict of element accesses: "ib" input-buffer reads, "wb" weight-buffer reads, "ab_r"/"ab_w"
                       accumulation-buffer reads/writes, "wreg" weight-register reads, "areg" accumulator-register
                       updates, "mac" vector-MAC issues x lanes x vec
        trace        : list of the first issues (cycle, m, k-chunk, n-tile) when requested
    [Properties] utilization = useful MACs / (cycles x MACs per cycle)
    """
    C: object
    cycles: int
    useful_macs: int
    issued_macs: int
    stalls: dict
    counts: dict
    cfg: PEConfig
    trace: list = field(default_factory=list)

    @property
    def utilization(self):
        return self.useful_macs / (self.cycles * self.cfg.macs) if self.cycles else 0.0


def _tiles(cfg, M, K, N):
    """Number of k-chunks and n-tiles (with padding) and the cycles one OS/IS issue takes."""
    kt = math.ceil(K / cfg.vec)
    nt = math.ceil(N / cfg.lanes)
    per_issue = math.ceil(cfg.lanes * cfg.vec / cfg.wbw)
    return kt, nt, per_issue


def _new_counts():
    return {"ib": 0, "wb": 0, "ab_r": 0, "ab_w": 0, "wreg": 0, "areg": 0, "mac": 0}


def simulate(cfg, A, B, dataflow="WS", trace=0):
    """
    Run C = A @ B on the PE, one vector-MAC issue at a time, with real int arithmetic.

    [Args]
        cfg      : PEConfig
        A, B     : integer matrices (M x K activations, K x N weights), e.g. int8 values
        dataflow : "WS", "OS" or "IS" (see the module docstring)
        trace    : record the first `trace` issues as (cycle, m, k-chunk, n-tile)
    [Returns] PEResult (C is computed by the simulated datapath, block by block -- compare with A @ B)
    [Edge cases] Raises ValueError for an unknown dataflow or mismatched shapes. Empty matrices give 0 cycles.
    [Python tip] np.pad(x, ((0, a), (0, b))) appends a rows and b columns of zeros -- the padding the hardware sees
        when K or N is not a multiple of the vector width or lane count.
    """
    import numpy as np

    if dataflow not in DATAFLOWS:
        raise ValueError(f"dataflow must be one of {DATAFLOWS}")
    M, K = A.shape
    K2, N = B.shape
    if K != K2:
        raise ValueError("inner dimensions of A and B differ")
    kt, nt, per = _tiles(cfg, M, K, N)
    V, Lz = cfg.vec, cfg.lanes
    Ap = np.pad(np.asarray(A, dtype=np.int64), ((0, 0), (0, kt * V - K)))
    Bp = np.pad(np.asarray(B, dtype=np.int64), ((0, kt * V - K), (0, nt * Lz - N)))
    C = np.zeros((M, nt * Lz), dtype=np.int64)
    counts, stalls, tr = _new_counts(), {"weight load": 0, "accumulator": 0, "weight bandwidth": 0, "drain": 0}, []
    t = 0
    acc_ready = {}

    def mac(m, k, n, t):
        """One vector-MAC issue: lanes dot products of width vec; returns the lanes partial results."""
        if len(tr) < trace:
            tr.append((t, m, k, n))
        counts["mac"] += Lz * V
        return Ap[m, k * V:(k + 1) * V] @ Bp[k * V:(k + 1) * V, n * Lz:(n + 1) * Lz]

    if M == 0 or K == 0 or N == 0:
        return PEResult(C[:, :N], 0, 0, 0, stalls, counts, cfg, tr)

    if dataflow == "WS":
        lw = math.ceil(Lz * V / cfg.wbw)                 # cycles to load one block of weights
        w_ready = lw                                     # the first block loads from cycle 0
        for n in range(nt):
            for k in range(kt):
                counts["wb"] += Lz * V                    # weights read ONCE per block into the lane registers
                start = max(t, w_ready)
                stalls["weight load"] += start - t
                t = start
                if k > 0:                                 # each accumulator was last updated one block earlier
                    ready = acc_ready[(0, n)]
                    if ready > t:
                        stalls["accumulator"] += ready - t
                        t = ready
                block_start = t
                for m in range(M):
                    C[m, n * Lz:(n + 1) * Lz] += mac(m, k, n, t)
                    counts["ib"] += V
                    counts["wreg"] += Lz * V
                    counts["ab_r"] += Lz if k > 0 else 0
                    counts["ab_w"] += Lz
                    acc_ready[(m, n)] = t + cfg.acc_latency
                    t += 1
                w_ready = (block_start if cfg.double_buffer else t) + lw
        drain = cfg.mac_latency + cfg.acc_latency
    elif dataflow == "OS":
        for n in range(nt):
            for m in range(M):
                acc = np.zeros(Lz, dtype=np.int64)        # accumulator registers in the lanes
                for k in range(kt):
                    acc += mac(m, k, n, t)
                    counts["ib"] += V
                    counts["wb"] += Lz * V
                    counts["areg"] += Lz
                    stalls["weight bandwidth"] += per - 1
                    t += per
                C[m, n * Lz:(n + 1) * Lz] = acc
                counts["ab_w"] += Lz                      # each output written once
        drain = cfg.mac_latency + 1
    else:  # IS
        for m in range(M):
            for k in range(kt):
                counts["ib"] += V                         # the input vector is read once and held
                if k > 0:
                    ready = acc_ready[(m, 0)]
                    if ready > t:
                        stalls["accumulator"] += ready - t
                        t = ready
                for n in range(nt):
                    C[m, n * Lz:(n + 1) * Lz] += mac(m, k, n, t)
                    counts["wb"] += Lz * V
                    counts["ab_r"] += Lz if k > 0 else 0
                    counts["ab_w"] += Lz
                    acc_ready[(m, n)] = t + cfg.acc_latency
                    stalls["weight bandwidth"] += per - 1
                    t += per
        drain = cfg.mac_latency + cfg.acc_latency
    stalls["drain"] = drain
    return PEResult(C[:, :N], t + drain, M * K * N, counts["mac"], stalls, counts, cfg, tr)


def estimate(cfg, M, K, N, dataflow="WS"):
    """
    The same cycle and access counts as simulate(), from closed-form expressions (no arithmetic, no loops).

    [Idea] Inside a WS block (or an IS group) every issue follows the previous one by exactly one cycle (or `per`
        cycles), so stalls can only happen at block boundaries, and every block boundary of the same kind behaves
        the same way. For WS with double-buffered weight registers, consecutive block starts are
            max(M, Lw, acc_latency)   apart if the block continues an accumulation (k > 0),
            max(M, Lw)                apart if it starts a new n-tile (k = 0),
        where Lw = cycles to load a weight block. Without double buffering the load cannot overlap: M + Lw
        (or acc_latency, if that is longer, for a continuing block).
        IS: consecutive groups of the same input row m start max(group, acc_latency) apart.
        The self-test checks that these formulas reproduce simulate() exactly.
    [Returns] PEResult with C = None
    """
    if dataflow not in DATAFLOWS:
        raise ValueError(f"dataflow must be one of {DATAFLOWS}")
    kt, nt, per = _tiles(cfg, M, K, N)
    V, Lz, acc = cfg.vec, cfg.lanes, cfg.acc_latency
    counts, stalls = _new_counts(), {"weight load": 0, "accumulator": 0, "weight bandwidth": 0, "drain": 0}
    if M == 0 or K == 0 or N == 0:
        return PEResult(None, 0, 0, 0, stalls, counts, cfg)
    issues = M * kt * nt
    counts["mac"] = issues * Lz * V
    cont, new_tile = nt * (kt - 1), nt - 1                 # block boundaries that continue / restart accumulation
    if dataflow == "WS":
        lw = math.ceil(Lz * V / cfg.wbw)
        if cfg.double_buffer:
            step_new = max(M, lw)
            step_cont = max(M, lw, acc)
            w_stall = max(0, lw - M)
            a_stall = max(0, acc - max(M, lw))
        else:
            step_new = M + lw
            step_cont = max(M + lw, acc)
            w_stall = lw
            a_stall = max(0, acc - (M + lw))
        t = lw + cont * step_cont + new_tile * step_new + M
        stalls["weight load"] = lw + (cont + new_tile) * w_stall
        stalls["accumulator"] = cont * a_stall
        counts.update(ib=issues * V, wb=kt * nt * Lz * V, wreg=issues * Lz * V,
                      ab_r=M * (kt - 1) * nt * Lz, ab_w=issues * Lz)
        drain = cfg.mac_latency + acc
    elif dataflow == "OS":
        t = issues * per
        stalls["weight bandwidth"] = issues * (per - 1)
        counts.update(ib=issues * V, wb=issues * Lz * V, areg=issues * Lz, ab_w=M * nt * Lz)
        drain = cfg.mac_latency + 1
    else:
        group = nt * per                                   # cycles of one (m, k) group
        t = M * ((kt - 1) * max(group, acc) + group)
        stalls["accumulator"] = M * (kt - 1) * max(0, acc - group)
        stalls["weight bandwidth"] = issues * (per - 1)
        counts.update(ib=M * kt * V, wb=issues * Lz * V, ab_r=M * (kt - 1) * nt * Lz, ab_w=issues * Lz)
        drain = cfg.mac_latency + acc
    stalls["drain"] = drain
    return PEResult(None, t + drain, M * K * N, counts["mac"], stalls, counts, cfg)


# =====================================================================================================================
# Energy of a run: access counts x energy per access
# =====================================================================================================================

IN_BYTES, ACC_BYTES = 1, 4          # int8 operands, int32 partial sums


def access_costs_pj(cfg):
    """
    Energy per ELEMENT access of every storage in the PE (45 nm, pJ), from Lecture 1's SRAM model.

    [Idea] Energy per access grows roughly with the square root of the storage's capacity (longer word and bit
        lines), so we price every level by its size: a 64-byte register file is ~10x cheaper per byte than a 32 KB
        buffer. Registers are priced with the same fit extrapolated to their small size -- an approximation
        (real register files with many ports cost more per bit).
    [Returns] dict name -> pJ per element access: "ib", "wb" (int8 reads), "ab" (int32 read or write), "wreg" (lane
        weight registers, int8), "areg" (accumulator registers, int32 read + write), "mac" (one int8 MAC)
    """
    wreg_bytes = 2 * cfg.lanes * cfg.vec * IN_BYTES                 # double-buffered weight registers
    areg_bytes = cfg.lanes * ACC_BYTES
    return {
        "ib": sram_pj_per_byte(cfg.ib_bytes) * IN_BYTES,
        "wb": sram_pj_per_byte(cfg.wb_bytes) * IN_BYTES,
        "ab": sram_pj_per_byte(cfg.ab_bytes) * ACC_BYTES,
        "wreg": sram_pj_per_byte(wreg_bytes) * IN_BYTES,
        "areg": 2 * sram_pj_per_byte(areg_bytes) * ACC_BYTES,
        "mac": mac_energy_pj("int8"),
    }


def energy(result):
    """
    Energy of a PE run by component (pJ): counts x per-access costs.

    [Returns] dict component -> pJ with keys "MAC", "weight registers", "accumulator registers", "input buffer",
        "weight buffer", "accumulation buffer"
    [Edge cases] Padded MACs are charged (the hardware computes them); real designs may gate zero operands
        (Eyeriss does) to save part of that energy.
    """
    c, k = result.counts, access_costs_pj(result.cfg)
    return {
        "MAC": c["mac"] * k["mac"],
        "weight registers": c["wreg"] * k["wreg"],
        "accumulator registers": c["areg"] * k["areg"],
        "input buffer": c["ib"] * k["ib"],
        "weight buffer": c["wb"] * k["wb"],
        "accumulation buffer": (c["ab_r"] + c["ab_w"]) * k["ab"],
    }


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

if __name__ == "__main__":
    import numpy as np

    rng = np.random.default_rng(0)
    shapes = [(20, 30, 12), (1, 64, 64), (3, 17, 9), (64, 64, 64), (2, 40, 3)]
    shapes += [tuple(int(x) for x in rng.integers(1, 40, 3)) for _ in range(15)]       # random small shapes
    configs = [PEConfig(), PEConfig(lanes=4, vec=16, wb_width=16), PEConfig(lanes=16, vec=4, double_buffer=False),
               PEConfig(lanes=8, vec=8, acc_latency=6, wb_width=32),
               PEConfig(lanes=2, vec=4, acc_latency=5, wb_width=3, double_buffer=False)]
    for cfg in configs:
        for (M, K, N) in shapes:
            A = rng.integers(-128, 128, (M, K))
            B = rng.integers(-128, 128, (K, N))
            for df in DATAFLOWS:
                r = simulate(cfg, A, B, df)
                e = estimate(cfg, M, K, N, df)
                assert np.array_equal(r.C, A @ B), (cfg, M, K, N, df)
                assert r.cycles == e.cycles and r.counts == e.counts and r.stalls == e.stalls, \
                    (cfg, (M, K, N), df, r.cycles, e.cycles, r.stalls, e.stalls)
                assert 0 < r.utilization <= 1
    # A perfectly shaped GEMM on the default PE: WS utilization close to 1.
    r = estimate(PEConfig(), 256, 256, 64, "WS")
    assert r.utilization > 0.99, r.utilization
    print("pe.py self-test passed")
