"""
systolic.py -- a cycle-accurate systolic array: weight-, output- and input-stationary GEMM, tiling, traffic, utilization
======================================================================================================================

[Why we need it]
    H. T. Kung's systolic array (1978-1982) is the compute fabric of Google's TPUs and of many other accelerators: a
    grid of R x C multiply-accumulate PEs in which data "pulses" from neighbour to neighbour once per clock, like
    blood through the heart (hence "systolic"). Every value read from memory is used by a whole row or column of
    PEs, and all communication is between adjacent PEs -- short wires, no shared bus, no register-file traffic.
    This module simulates such an array clock by clock, with real numbers, so that one can SEE the wavefront, check
    the result against numpy, and count cycles, fill/drain overhead, utilization and memory traffic.

[The three dataflows] (what stays inside each PE)
    WS  weight-stationary : PE (i, j) holds weight B[k0 + i, n0 + j]. Input rows of A enter at the left edge, one
        element per array row, skewed by one cycle per row; they move right one PE per cycle. Partial sums move
        DOWN one PE per cycle, each PE adding a * w; finished outputs leave at the bottom. (TPU v1-v4.)
    OS  output-stationary : PE (i, j) accumulates C[m0 + i, n0 + j]. A enters at the left (skewed by row), B enters
        at the top (skewed by column); both move one PE per cycle; each PE multiplies what passes through.
    IS  input-stationary  : PE (i, j) holds an input element; the mirror image of WS. C^T = B^T A^T, so IS is WS
        applied to the transposed problem (the hardware is the same array with the operands' roles swapped).

[Timing] Registered PE-to-PE links: a value produced in cycle t is seen by the neighbour in cycle t + 1. Inputs are
    SKEWED -- row i of the array receives its stream i cycles late -- so that the operands of every MAC meet in the
    right PE in the right cycle (the "wavefront"). Consequences:
        WS, one weight tile, M input rows : M + R + C - 2 cycles (+ R cycles to load the weights)
        OS, one output tile, reduction K  : K + R + C - 2 cycles (+ 1 cycle to drain the accumulators)
    Tiles of a large GEMM are PIPELINED back to back: the next tile's data follows right behind the previous
    one's, and double-buffered weights (WS) / accumulators (OS) let each PE switch tiles when the new data reaches
    it. Only the first fill and the last drain are paid once.

[Usage]
    import numpy as np, systolic as sa
    A = np.random.randint(-8, 8, (10, 12)); B = np.random.randint(-8, 8, (12, 6))
    r = sa.simulate(A, B, R=4, C=4, dataflow="WS")
    assert (r.C == A @ B).all(); print(r.cycles, r.utilization)
    sa.estimate(10, 12, 6, R=4, C=4, dataflow="WS")      # the same cycle count from a formula

[Edge cases]
    - Dimensions that are not multiples of the array size are zero-padded: the padded PEs compute zeros (they burn
      cycles and energy but produce nothing useful -- utilization accounts for it).
    - The simulator steps every cycle with numpy operations on R x C arrays: fine for arrays up to ~64 x 64 and a
      few thousand cycles. Use estimate() (exact for the same assumptions) for TPU-sized arrays and real layers.
"""

import math
from dataclasses import dataclass, field

import numpy as np

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


@dataclass
class SysResult:
    """
    Outcome of a GEMM on the array.

    [Fields]
        C        : the result (None for estimate())
        cycles   : total cycles from the first weight load / operand injection to the last output
        macs     : useful MACs (M * K * N)
        R, Cc    : array rows and columns
        tiles    : number of tiles processed
        traffic  : dict of element transfers between the array and its SRAM buffers -- "A" (inputs read),
                   "B" (weights read), "C_read"/"C_write" (partial sums / outputs), "hops" (PE-to-PE moves).
                   Only real elements count (padding zeros are generated, not read). WS reads A once per
                   output-column tile and every weight once, and writes partial sums once per k-tile (read back
                   for all but the first); OS reads A once per output-column tile and B once per output-row tile,
                   and writes each output once.
        trace    : per-cycle snapshots (for small demos), when requested
    [Properties] utilization = macs / (cycles * R * Cc)
    """
    C: object
    cycles: int
    macs: int
    R: int
    Cc: int
    tiles: int
    traffic: dict
    trace: list = field(default_factory=list)

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


def _pad(X, rows, cols):
    """Zero-pad a matrix up to (rows, cols)."""
    out = np.zeros((rows, cols), dtype=np.int64)
    out[:X.shape[0], :X.shape[1]] = X
    return out


# =====================================================================================================================
# Weight-stationary
# =====================================================================================================================

def _simulate_ws(A, B, R, C, double_buffer=True, skew=True, trace_cycles=0):
    """
    Weight-stationary array, tiles pipelined. Tiles are ordered n-tile outer, k-tile inner; every tile streams all
    M rows of A. Partial sums of different k-tiles are added in an accumulator buffer below the array (as in the
    TPU), so the array itself never stores outputs.

    [Idea of the implementation] Instead of moving Python objects around, we keep two R x C register arrays: `a`
        (the input element each PE holds this cycle) and `p` (the partial sum each PE produced last cycle). Each
        cycle: a shifts right by one column (column 0 receives the skewed input), p shifts down by one row (row 0
        receives 0), and p_new = p_shifted + a * W_selected. Each PE uses the weight tile that matches the input it
        currently holds (double-buffered weights switch tile by tile as the wavefront passes).
    """
    M, K = A.shape
    N = B.shape[1]
    kt, nt = math.ceil(K / R), math.ceil(N / C)
    Ap = _pad(A, M, kt * R)
    Bp = _pad(B, kt * R, nt * C)
    tiles = [(n, k) for n in range(nt) for k in range(kt)]
    W = np.stack([Bp[k * R:(k + 1) * R, n * C:(n + 1) * C] for n, k in tiles])      # (tiles, R, C)
    slot = max(M, R) if double_buffer else M + R          # input slots per tile (weights must load in R cycles)
    start = R                                             # the first tile's weights load in cycles 0 .. R-1
    out = np.zeros((M, nt * C), dtype=np.int64)
    a = np.zeros((R, C), dtype=np.int64)
    p = np.zeros((R, C), dtype=np.int64)
    I, J = np.indices((R, C))
    total = start + len(tiles) * slot + R + C - 2
    trace = []
    hops = 0
    for t in range(total):
        # 1. inputs entering at the left edge: array row i receives A[m, k*R + i] of global slot g = t - start - i
        left = np.zeros(R, dtype=np.int64)
        g = t - start - np.arange(R) * int(skew)
        tile, m = np.divmod(g, slot)
        ok = (g >= 0) & (tile < len(tiles)) & (m < M)
        for i in np.nonzero(ok)[0]:
            _, k = tiles[tile[i]]
            left[i] = Ap[m[i], k * R + i]
        # 2. shift registers: a moves right, p moves down
        a = np.concatenate([left[:, None], a[:, :-1]], axis=1)
        p_in = np.concatenate([np.zeros((1, C), dtype=np.int64), p[:-1, :]], axis=0)
        hops += int(np.count_nonzero(a[:, 1:])) + int(np.count_nonzero(p_in[1:, :]))
        # 3. which weight tile is each PE using? the tile of the input it holds: slot index t - start - i - j
        gp = t - start - I - J
        tp = np.clip(gp // slot, 0, len(tiles) - 1)
        p = p_in + a * W[tp, I, J]
        # 4. outputs leave the bottom row: column j carries the result of slot g = t - start - (R-1) - j
        gb = t - start - (R - 1) - np.arange(C)
        tb, mb = np.divmod(gb, slot)
        okb = (gb >= 0) & (tb < len(tiles)) & (mb < M)
        for j in np.nonzero(okb)[0]:
            n, _ = tiles[tb[j]]
            out[mb[j], n * C + j] += p[R - 1, j]
        if t < trace_cycles:
            trace.append((t, a.copy(), p.copy()))
    traffic = {"A": M * K * nt, "B": K * N, "C_read": M * N * (kt - 1), "C_write": M * N * kt, "hops": hops}
    return out[:, :N], total, len(tiles), traffic, trace


# =====================================================================================================================
# Output-stationary
# =====================================================================================================================

def _simulate_os(A, B, R, C, skew=True, trace_cycles=0):
    """
    Output-stationary array, tiles pipelined (m-tile outer, n-tile inner); each tile streams K reduction steps.
    A element A[m0 + i, k] enters row i at slot-time k (+ i of skew) and moves right; B element B[k, n0 + j]
    enters column j at slot-time k (+ j of skew) and moves down; PE (i, j) meets A[., k] and B[k, .] in the same
    cycle and accumulates. Double-buffered accumulators let each PE start its next tile while the finished one is
    drained (1 cycle at the end of the last tile).
    """
    M, K = A.shape
    N = B.shape[1]
    mt, nt = math.ceil(M / R), math.ceil(N / C)
    Ap = _pad(A, mt * R, K)
    Bp = _pad(B, K, nt * C)
    tiles = [(m, n) for m in range(mt) for n in range(nt)]
    out = np.zeros((mt * R, nt * C), dtype=np.int64)
    a = np.zeros((R, C), dtype=np.int64)
    b = np.zeros((R, C), dtype=np.int64)
    acc = np.zeros((R, C), dtype=np.int64)
    cur = np.full((R, C), -1)                         # which tile each PE is accumulating
    I, J = np.indices((R, C))
    total = len(tiles) * K + R + C - 2 + 1
    trace, hops = [], 0
    for t in range(total):
        left = np.zeros(R, dtype=np.int64)
        g = t - np.arange(R) * int(skew)
        tile, k = np.divmod(g, K)
        ok = (g >= 0) & (tile < len(tiles))
        for i in np.nonzero(ok)[0]:
            mi, _ = tiles[tile[i]]
            left[i] = Ap[mi * R + i, k[i]]
        top = np.zeros(C, dtype=np.int64)
        g = t - np.arange(C) * int(skew)
        tile, k = np.divmod(g, K)
        ok = (g >= 0) & (tile < len(tiles))
        for j in np.nonzero(ok)[0]:
            _, nj = tiles[tile[j]]
            top[j] = Bp[k[j], nj * C + j]
        a = np.concatenate([left[:, None], a[:, :-1]], axis=1)
        b = np.concatenate([top[None, :], b[:-1, :]], axis=0)
        hops += int(np.count_nonzero(a[:, 1:])) + int(np.count_nonzero(b[1:, :]))
        # PE (i, j) works on global step g = t - i - j: tile g // K
        gp = t - I - J
        tp = np.where(gp >= 0, gp // K, -1)
        switch = (tp != cur) & (cur >= 0) & (tp < len(tiles))  # a NEW tile reaches the PE
        for i, j in zip(*np.nonzero(switch)):                 # finished tile: drain the accumulator
            mi, nj = tiles[cur[i, j]]
            out[mi * R + i, nj * C + j] = acc[i, j]
            acc[i, j] = 0
        cur = np.where((tp >= 0) & (tp < len(tiles)), tp, cur)
        acc += a * b
        if t < trace_cycles:
            trace.append((t, a.copy(), b.copy(), acc.copy()))
    for i, j in zip(*np.nonzero(cur >= 0)):                    # final drain
        mi, nj = tiles[cur[i, j]]
        out[mi * R + i, nj * C + j] = acc[i, j]
    traffic = {"A": M * K * nt, "B": K * N * mt, "C_read": 0, "C_write": M * N, "hops": hops}
    return out[:M, :N], total, len(tiles), traffic, trace


# =====================================================================================================================
# Public interface
# =====================================================================================================================

def simulate(A, B, R, C, dataflow="WS", double_buffer=True, skew=True, trace_cycles=0):
    """
    Run C = A @ B on an R x C systolic array, cycle by cycle, with integer arithmetic.

    [Args]
        A, B          : integer matrices (M x K, K x N)
        R, C          : array rows and columns
        dataflow      : "WS", "OS" or "IS"
        double_buffer : WS only -- weights for the next tile load while the current one computes
        skew          : False removes the input skew (to show why it is needed: the result becomes wrong)
        trace_cycles  : record register snapshots of the first cycles
    [Returns] SysResult
    """
    A, B = np.asarray(A, dtype=np.int64), np.asarray(B, dtype=np.int64)
    if dataflow == "WS":
        out, cyc, nt, tr, trace = _simulate_ws(A, B, R, C, double_buffer, skew, trace_cycles)
    elif dataflow == "OS":
        out, cyc, nt, tr, trace = _simulate_os(A, B, R, C, skew, trace_cycles)
    elif dataflow == "IS":                       # C^T = B^T A^T on the same array: inputs are now stationary
        outT, cyc, nt, tr, trace = _simulate_ws(B.T, A.T, R, C, double_buffer, skew, trace_cycles)
        out = outT.T
        tr = {"A": tr["B"], "B": tr["A"], "C_read": tr["C_read"], "C_write": tr["C_write"], "hops": tr["hops"]}
    else:
        raise ValueError(f"dataflow must be one of {DATAFLOWS}")
    M, K = A.shape
    return SysResult(out, cyc, M * K * B.shape[1], R, C, nt, tr, trace)


def estimate(M, K, N, R, C, dataflow="WS", double_buffer=True):
    """
    Cycles and SRAM traffic of the same pipelined schedule as simulate(), from formulas.

    [Idea]
        WS: tiles = ceil(K/R) * ceil(N/C), each occupying max(M, R) input slots (M rows; the next tile's weights
            need R cycles to load), after an initial R-cycle weight load and before an R + C - 2 cycle drain.
            Without double buffering each tile takes M + R slots.
        OS: tiles = ceil(M/R) * ceil(N/C), each K slots, + R + C - 2 fill/drain + 1 final accumulator drain.
        IS: WS on (N, K, M) -- the roles of A and B swapped.
    [Returns] SysResult with C = None (hops = 0: not counted analytically)
    """
    if dataflow == "IS":
        r = estimate(N, K, M, R, C, "WS", double_buffer)
        tr = {"A": r.traffic["B"], "B": r.traffic["A"], "C_read": r.traffic["C_read"],
              "C_write": r.traffic["C_write"], "hops": 0}
        return SysResult(None, r.cycles, M * K * N, R, C, r.tiles, tr)
    if dataflow == "WS":
        kt, nt = math.ceil(K / R), math.ceil(N / C)
        tiles = kt * nt
        slot = max(M, R) if double_buffer else M + R
        cycles = R + tiles * slot + R + C - 2
        tr = {"A": M * K * nt, "B": K * N, "C_read": M * N * (kt - 1), "C_write": M * N * kt, "hops": 0}
        return SysResult(None, cycles, M * K * N, R, C, tiles, tr)
    if dataflow == "OS":
        mt, nt = math.ceil(M / R), math.ceil(N / C)
        tiles = mt * nt
        cycles = tiles * K + R + C - 2 + 1
        tr = {"A": M * K * nt, "B": K * N * mt, "C_read": 0, "C_write": M * N, "hops": 0}
        return SysResult(None, cycles, M * K * N, R, C, tiles, tr)
    raise ValueError(f"dataflow must be one of {DATAFLOWS}")


def estimate_multi(M, K, N, R, C, n_arrays, dataflow="WS"):
    """
    Several identical arrays working on the tiles of one GEMM in parallel (e.g. TPU v4's four 128 x 128 MXUs per core).

    [Idea] The tiles of the GEMM (see estimate()) are dealt out to the arrays; each array processes its share
        back to back with its own fill and drain, so the GEMM takes as long as the busiest array:
        WS: R + ceil(tiles / n) * max(M, R) + R + C - 2;  OS: ceil(tiles / n) * K + R + C - 1;  IS: WS on (N, K, M).
    [Returns] SysResult whose utilization is relative to ALL arrays' MACs (R * C * n_arrays per cycle)
    [Edge cases] With fewer tiles than arrays, some arrays idle for the whole GEMM -- the small-layer problem of
        many small arrays, the mirror image of one big array's padding problem.
    """
    one = estimate(M, K, N, R, C, dataflow)
    share = math.ceil(one.tiles / n_arrays)
    if dataflow == "OS":
        cycles = share * K + R + C - 1
    else:
        streamed = M if dataflow == "WS" else N
        cycles = R + share * max(streamed, R) + R + C - 2
    return SysResult(None, cycles, M * K * N, R, C * n_arrays, one.tiles, one.traffic)


def flexible_utilization(K, n_mult):
    """
    Utilization of a FLEXIBLE reduction fabric (MAERI-style) of n_mult multipliers on dot products of length K.

    [Idea] MAERI (Kwon, Samajdar, Krishna 2018) connects its multipliers through a reconfigurable reduction tree, so
        that any group of K adjacent multipliers can form one dot product ("virtual neuron"), for any K. With
        n_mult multipliers it runs floor(n_mult / K) dot products at once (or one K-long dot product in
        ceil(K / n_mult) passes). Compare with a rigid R x C array, which pads K to a multiple of R.
    [Returns] fraction of multipliers doing useful work in steady state
    """
    if K >= n_mult:
        return K / (math.ceil(K / n_mult) * n_mult)
    return (n_mult // K) * K / n_mult


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    for (M, K, N, R, C) in [(4, 4, 4, 4, 4), (7, 10, 9, 4, 3), (1, 8, 8, 4, 4), (12, 5, 6, 3, 5), (3, 9, 2, 4, 4)]:
        A = rng.integers(-8, 8, (M, K))
        B = rng.integers(-8, 8, (K, N))
        for df in DATAFLOWS:
            for db in (True, False):
                if df == "OS" and not db:
                    continue
                r = simulate(A, B, R, C, df, double_buffer=db)
                e = estimate(M, K, N, R, C, df, double_buffer=db)
                assert np.array_equal(r.C, A @ B), (M, K, N, R, C, df, db)
                assert r.cycles == e.cycles, (M, K, N, R, C, df, db, r.cycles, e.cycles)
                assert {k: v for k, v in r.traffic.items() if k != "hops"} == \
                       {k: v for k, v in e.traffic.items() if k != "hops"}
    for _ in range(25):                                   # random shapes, including M < R (weight-load stalls)
        M, K, N, R, C = (int(v) for v in rng.integers(1, 12, 5))
        A, B = rng.integers(-8, 8, (M, K)), rng.integers(-8, 8, (K, N))
        for df in DATAFLOWS:
            r = simulate(A, B, R, C, df)
            assert np.array_equal(r.C, A @ B) and r.cycles == estimate(M, K, N, R, C, df).cycles, (M, K, N, R, C, df)
    # Without the skew, the wavefront is broken and the answer is wrong.
    A = rng.integers(-8, 8, (6, 4))
    B = rng.integers(-8, 8, (4, 4))
    assert not np.array_equal(simulate(A, B, 4, 4, "WS", skew=False).C, A @ B)
    # One perfectly sized tile: WS takes M + R + C - 2 cycles after the R-cycle weight load.
    assert estimate(100, 4, 4, 4, 4, "WS").cycles == 4 + 100 + 4 + 4 - 2
    assert flexible_utilization(9, 64) == 63 / 64 and flexible_utilization(128, 64) == 1.0
    one = estimate(512, 4096, 4096, 256, 256)
    four = estimate_multi(512, 4096, 4096, 128, 128, 4)
    assert four.cycles < one.cycles and estimate_multi(512, 4096, 4096, 128, 128, 1).cycles == \
        estimate(512, 4096, 4096, 128, 128).cycles
    print("systolic.py self-test passed")
