"""
tpu_model.py -- a TPU-style matrix unit fed by a weight FIFO from DRAM: when is it compute-bound, when memory-bound?
=====================================================================================================================

[Why we need it]
    TPU v1 (Jouppi et al., ISCA 2017) puts a 256 x 256 weight-stationary systolic array (the Matrix Multiply Unit,
    MXU) next to a 24 MiB Unified Buffer for activations and 4 MiB of accumulators. Weights stream from off-chip
    DDR3 memory (34 GB/s) through a Weight FIFO, four 64 KiB tiles deep; the MXU double-buffers them so it can
    compute with one tile while the next shifts in. Whether the MXU is busy therefore depends on a race: does a
    weight tile arrive (64 KiB / 34 GB/s = 1.9 us) faster than the MXU finishes using the previous one (one cycle per
    activation row, i.e. B cycles for a batch of B)? This module simulates that race tile by tile, so that the
    roofline of the TPU paper can be reproduced from first principles.

[Usage]
    from tpu_model import TPU_V1, run_matmul
    r = run_matmul(TPU_V1, batch=200, K=2048, N=2048)
    print(r["seconds"], r["tops"], r["bound"])

[Model]
    - A matrix multiplication Y = X W (X: batch x K activations from the on-chip buffer, W: K x N weights from
      DRAM) is cut into ceil(K / rows) x ceil(N / cols) weight tiles.
    - DRAM delivers tiles one after another at dram_bw into a FIFO of `fifo_tiles` entries; a tile can only be
      fetched when the FIFO has room (back-pressure, Lecture 2).
    - Each MXU takes the next tile when it has arrived and the MXU is free; a tile occupies the MXU for
      max(batch, rows) cycles (weight-stationary pipelining, systolic.estimate()); n_mxu units share the DRAM.
    - Fill and drain (rows + cols - 2 cycles) are paid once. Activations and accumulators are on chip and never
      stall the array (true of TPU v1's 256-byte-wide Unified Buffer path; Lecture 7 relaxes it).
[Edge cases] batch beyond the accumulator capacity (4096 rows on TPU v1) would need several passes; not modeled.
"""

import math
from dataclasses import dataclass, replace

import course_path

course_path.use("lecture01")

from hw_specs import TPU_V1 as TPU_V1_SPEC  # noqa: E402


@dataclass(frozen=True)
class TPUConfig:
    """
    [Fields] name; rows, cols (one MXU); n_mxu; freq (Hz); elem_bytes (bytes per weight: 1 = int8, 2 = bf16);
        dram_bw (bytes/s available for weights); fifo_tiles (weight FIFO depth in tiles)
    [Properties] peak (ops/s, 1 MAC = 2 ops), ridge (ops per weight byte), tile_bytes
    """
    name: str
    rows: int
    cols: int
    n_mxu: int
    freq: float
    elem_bytes: int
    dram_bw: float
    fifo_tiles: int = 4

    @property
    def peak(self):
        return 2 * self.rows * self.cols * self.n_mxu * self.freq

    @property
    def ridge(self):
        return self.peak / self.dram_bw

    @property
    def tile_bytes(self):
        return self.rows * self.cols * self.elem_bytes


# TPU v1 (Jouppi et al. 2017): one 256 x 256 int8 MXU at 700 MHz, 34 GB/s DDR3, a 4-tile weight FIFO.
TPU_V1 = TPUConfig("TPU v1", 256, 256, 1, 700e6, 1, TPU_V1_SPEC.mem_bw, 4)
# One TPU v4 TensorCore (Jouppi et al. 2023): four 128 x 128 bf16 MXUs at 1050 MHz; a chip has two cores sharing
# ~1.2 TB/s of HBM, so ~600 GB/s per core.
TPU_V4_CORE = TPUConfig("TPU v4 TensorCore", 128, 128, 4, 1.05e9, 2, 600e9, 4)


def run_matmul(cfg, batch, K, N):
    """
    Time of Y = X W on the TPU model, tile by tile.

    [Args] cfg: TPUConfig; batch: rows of X; K, N: weight matrix shape
    [Returns] dict: seconds, tops (useful ops/s), utilization (of peak), bound ("memory" if fetching all weight
        tiles takes longer than computing with them), stall_cycles (MXU cycles spent waiting for weights), tiles,
        cycles
    [Edge cases] With several MXUs, tiles are handed out in order to whichever MXU frees first.
    """
    tiles = math.ceil(K / cfg.rows) * math.ceil(N / cfg.cols)
    t_load = cfg.tile_bytes / cfg.dram_bw * cfg.freq           # cycles to fetch one tile from DRAM
    t_use = max(batch, cfg.rows)                                 # cycles one tile occupies an MXU
    arrive = []                                                  # cycle each tile is in the FIFO
    start = []
    mxu_free = [0.0] * cfg.n_mxu
    stall = 0.0
    dram_free = 0.0
    for i in range(tiles):
        # DRAM may fetch tile i once the FIFO has room: tile i - fifo_tiles must have left it (started on an MXU)
        can_fetch = dram_free if i < cfg.fifo_tiles else max(dram_free, start[i - cfg.fifo_tiles])
        dram_free = can_fetch + t_load
        arrive.append(dram_free)
        u = min(range(cfg.n_mxu), key=lambda k: mxu_free[k])
        s = max(mxu_free[u], arrive[i])
        stall += max(0.0, arrive[i] - mxu_free[u])
        start.append(s)
        mxu_free[u] = s + t_use
    cycles = max(mxu_free) + cfg.rows + cfg.cols - 2
    seconds = cycles / cfg.freq
    ops = 2 * batch * K * N
    busy = tiles * t_use / cfg.n_mxu                 # cycles the MXUs need for the work itself
    fetch = tiles * t_load                           # cycles DRAM needs to deliver all the weights
    return {"seconds": seconds, "tops": ops / seconds, "utilization": ops / seconds / cfg.peak,
            "bound": "memory" if fetch > busy else "compute", "stall_cycles": stall, "tiles": tiles,
            "cycles": cycles}


def roofline_tops(cfg, batch):
    """Roofline bound for a weight-streaming matmul: min(peak, bandwidth x intensity), intensity = 2 B / elem_bytes."""
    return min(cfg.peak, cfg.dram_bw * 2 * batch / cfg.elem_bytes)


if __name__ == "__main__":
    # The TPU v1 ridge: 92 TOPS / 34 GB/s = ~2700 ops per weight byte, i.e. ~1350 MACs: batch ~1350 for int8.
    assert abs(TPU_V1.peak - 91.75e12) < 1e11 and 2650 < TPU_V1.ridge < 2750
    small = run_matmul(TPU_V1, 16, 2048, 2048)
    big = run_matmul(TPU_V1, 4096, 2048, 2048)
    assert small["bound"] == "memory" and big["bound"] == "compute"
    assert abs(small["tops"] / roofline_tops(TPU_V1, 16) - 1) < 0.05
    assert big["utilization"] > 0.9
    print("tpu_model.py self-test passed")
