"""
global_buffer.py -- a banked global buffer shared by several clients, with a near-memory processing unit (the block of
Lab 3), simulated cycle by cycle with real values
====================================================================================================================

[Why we need it]
    The global buffer (GB) is the accelerator's main on-chip memory: a few MB of SRAM between DRAM and the compute
    units. Many CLIENTS use it at once -- the DMA engine filling the next tiles from DRAM, the matrix unit reading
    operand tiles and writing results, the vector unit -- and every cycle each BANK can serve only one of them. Two
    design questions follow:
    1. Placement: which data lives in which banks, so that clients that run at the same time do not collide?
    2. Near-memory processing (NMP): some operations need little arithmetic but touch a lot of data -- summing the
       partial results of a split reduction, residual additions, scaling. Doing them NEXT to the banks (a small
       adder per bank, "read-modify-write") avoids shipping the data to a compute unit and back.
    This module simulates the GB at the granularity of one bank access per cycle, with values, so both questions
    can be answered with numbers -- and the NMP results checked against numpy.

[The model]
    - banks x bank_words words; one word = word_elems fp32 values (word_bytes = 4 x word_elems).
    - mapping: "interleaved" (word w in bank w mod banks) or "blocked" (bank = w // bank_words: contiguous ranges
      live in one bank, so the software decides placement by choosing addresses).
    - Clients present requests in order: ("r", word), ("w", word, value) or ("rmw", word, value) -- read-modify-
      write, which ADDS value into the word in the bank's near-memory adder. A client presents at most one request
      per cycle and at most `rate` requests per cycle on average.
    - Each cycle each bank grants one request (round-robin among the clients that want it). A read or write keeps
      the bank busy 1 cycle; an rmw keeps it busy rmw_cycles (2 = read then write through one port; 1 = a pipelined
      adder with separate read and write ports).
    - Losing clients retry next cycle (a stall).

[Edge cases]
    - Reads return the value at the moment they are granted (a client that reads what another writes in the same
      run must order itself; the experiments here never race).
    - Simulation steps cycle by cycle in Python: fine for ~10^5 requests.
"""

import math
from dataclasses import dataclass, field

import numpy as np

import course_path

course_path.use("lecture01", "lecture03")

from metrics import EYERISS_COSTS  # noqa: E402


@dataclass(frozen=True)
class GBConfig:
    """
    Global-buffer parameters.

    [Fields] banks; bank_words: words per bank; word_elems: fp32 values per word; mapping: "interleaved" or
        "blocked"; rmw_cycles: bank cycles per read-modify-write
    [Properties] words, bytes, word_bytes
    """
    banks: int = 16
    bank_words: int = 4096
    word_elems: int = 8
    mapping: str = "interleaved"
    rmw_cycles: int = 2

    @property
    def words(self):
        return self.banks * self.bank_words

    @property
    def word_bytes(self):
        return 4 * self.word_elems

    @property
    def bytes(self):
        return self.words * self.word_bytes

    def bank(self, word):
        """Bank of a word address."""
        if self.mapping == "interleaved":
            return word % self.banks
        if self.mapping == "blocked":
            return word // self.bank_words
        raise ValueError(f"unknown mapping {self.mapping!r}")


@dataclass
class Client:
    """
    One user of the buffer: a name, a list of requests and a rate.

    [Fields] name; requests: list of tuples ("r", word) | ("w", word, value) | ("rmw", word, value);
        rate: average requests per cycle (<= 1); start: first cycle it may issue
    [Filled by simulate] done (cycle of the last grant + 1), stalls (cycles it wanted a bank and lost),
        reads (values returned by its reads, in order)
    """
    name: str
    requests: list
    rate: float = 1.0
    start: int = 0
    done: int = 0
    stalls: int = 0
    reads: list = field(default_factory=list)


@dataclass
class GBResult:
    """Outcome: total cycles, per-client (done, stalls), bank busy cycles, and the final memory contents."""
    cycles: int
    clients: dict
    bank_busy: list
    memory: np.ndarray


def simulate(cfg, clients, memory=None, max_cycles=10_000_000):
    """
    Run the clients against the buffer cycle by cycle.

    [Idea] Each client has a pointer to its next request and a credit counter (rate per cycle; it may issue when the
        credit reaches 1). Each cycle: every ready client asks for the bank of its head request; each free bank
        grants one asker in round-robin order (the pointer moves past the winner), executes the access on the
        memory array, and becomes busy for 1 cycle (rmw_cycles for rmw); losers stall and retry.
    [Args] cfg: GBConfig; clients: list of Client; memory: optional initial contents, shape (words, word_elems)
    [Returns] GBResult
    [Edge cases] A request to a word outside the buffer raises IndexError. A run that exceeds max_cycles raises
        RuntimeError (it would mean a client can never be served -- impossible with round-robin).
    """
    mem = np.zeros((cfg.words, cfg.word_elems)) if memory is None else np.array(memory, dtype=np.float64)
    ptr = [0] * len(clients)
    credit = [0.0] * len(clients)
    busy_until = [0] * cfg.banks
    busy = [0] * cfg.banks
    rr = [0] * cfg.banks
    cycle = 0
    remaining = sum(len(c.requests) for c in clients)
    while remaining:
        if cycle > max_cycles:
            raise RuntimeError("global buffer simulation did not finish")
        want = {}
        for i, c in enumerate(clients):
            if ptr[i] >= len(c.requests) or cycle < c.start:
                continue
            credit[i] = min(credit[i] + c.rate, 1.0)
            if credit[i] < 1.0 - 1e-12:
                continue
            word = c.requests[ptr[i]][1]
            want.setdefault(cfg.bank(word), []).append(i)
        for b, askers in want.items():
            if busy_until[b] > cycle:
                for i in askers:
                    clients[i].stalls += 1
                continue
            n = len(clients)
            winner = min(askers, key=lambda i: (i - rr[b]) % n)
            rr[b] = (winner + 1) % n
            for i in askers:
                if i != winner:
                    clients[i].stalls += 1
            c = clients[winner]
            req = c.requests[ptr[winner]]
            kind, word = req[0], req[1]
            if kind == "r":
                c.reads.append(mem[word].copy())
                occ = 1
            elif kind == "w":
                mem[word] = req[2]
                occ = 1
            elif kind == "rmw":
                mem[word] += req[2]
                occ = cfg.rmw_cycles
            else:
                raise ValueError(f"unknown request kind {kind!r}")
            busy_until[b] = cycle + occ
            busy[b] += occ
            ptr[winner] += 1
            credit[winner] -= 1.0
            remaining -= 1
            if ptr[winner] == len(c.requests):
                c.done = cycle + 1
        cycle += 1
    end = max([c.done for c in clients] + [max(busy_until)])
    return GBResult(end, {c.name: (c.done, c.stalls) for c in clients}, busy, mem)


# =====================================================================================================================
# Request generators and an energy model
# =====================================================================================================================

def stream(kind, start_word, n_words, values=None, stride=1):
    """Requests for n_words consecutive (or strided) words; values: (n_words, word_elems) array for writes/rmw."""
    words = start_word + stride * np.arange(n_words)
    if kind == "r":
        return [("r", int(w)) for w in words]
    return [(kind, int(w), values[i]) for i, w in enumerate(words)]


# Energy per fp32 element moved, in units of one 16-bit MAC (Eyeriss's normalized costs from Lecture 3; we apply
# the 16-bit numbers per 32-bit element as an order-of-magnitude model): a buffer access, a hop over the on-chip
# network to a compute unit, a register-file access and an add.
COST = {"buffer": EYERISS_COSTS["buffer"], "noc": EYERISS_COSTS["array"], "rf": EYERISS_COSTS["RF"],
        "alu": EYERISS_COSTS["MAC"]}


def reduction_energy(P, elems, path):
    """
    Energy (MAC units) to produce the sum of P partial tensors of `elems` elements, computed by P producers
    (e.g. the cores of a split-K GEMM), with the result left in the buffer.

    [Idea] Both paths start with each producer sending its partial over the on-chip network (one hop per element).
        "compute": the partials are written to the buffer (P writes, P copies of the tensor stored at once); one
            compute unit reads them all back (P reads + P hops + P register writes), adds (P - 1 adds per
            element) and writes the result (1 hop + 1 write).
        "nmp": the partials arrive as accumulate-writes; each bank's adder reads the old value, adds and writes the
            sum (2 buffer accesses + 1 add per partial). Only one copy of the tensor is ever stored.
    [Returns] dict component -> energy
    """
    c = COST
    if path == "compute":
        return {"buffer": (2 * P + 1) * elems * c["buffer"], "noc": (2 * P + 1) * elems * c["noc"],
                "rf": P * elems * c["rf"], "alu": (P - 1) * elems * c["alu"]}
    if path == "nmp":
        return {"buffer": 2 * P * elems * c["buffer"], "noc": P * elems * c["noc"], "rf": 0.0,
                "alu": P * elems * c["alu"]}
    raise ValueError("path must be 'compute' or 'nmp'")


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    cfg = GBConfig()
    # one client streaming sequentially: one access per cycle, no stalls
    r = simulate(cfg, [Client("seq", stream("r", 0, 256))])
    assert r.cycles == 256 and r.clients["seq"][1] == 0
    # two clients on the same bank every cycle (stride = banks): they alternate, ~2x slower
    a = Client("a", stream("r", 0, 64, stride=16))
    b = Client("b", stream("r", 1024, 64, stride=16))
    r = simulate(cfg, [a, b])
    assert 127 <= r.cycles <= 129 and r.clients["a"][1] + r.clients["b"][1] >= 60
    # NMP accumulation: P partial tiles accumulated with rmw equal their numpy sum
    P, W = 4, 64
    parts = rng.normal(size=(P, W, cfg.word_elems))
    clients = [Client(f"core{p}", stream("rmw", 0, W, parts[p])) for p in range(P)]
    r = simulate(cfg, clients)
    assert np.allclose(r.memory[:W], parts.sum(0))
    # rmw occupies a bank for rmw_cycles: with 1-cycle rmw the same reduction is faster
    r1 = simulate(GBConfig(rmw_cycles=1), [Client(f"core{p}", stream("rmw", 0, W, parts[p])) for p in range(P)])
    assert r1.cycles < r.cycles
    # blocked mapping: a range lives in one bank
    assert GBConfig(mapping="blocked").bank(4095) == 0 and GBConfig(mapping="blocked").bank(4096) == 1
    # energy: NMP saves the separate store-then-read trip of every partial
    e_c = sum(reduction_energy(4, 1000, "compute").values())
    e_n = sum(reduction_energy(4, 1000, "nmp").values())
    assert e_n < e_c, (e_n, e_c)
    print("global_buffer.py self-test passed")
    print(f"  {cfg.banks} banks x {cfg.bank_words} words x {cfg.word_bytes} B = {cfg.bytes / 2**20:.0f} MiB; "
          f"4-way accumulation of {W} words: {r.cycles} cycles (rmw = 2), {r1.cycles} (rmw = 1)")
