"""
toy_accel.py -- the course's toy accelerator at the top level (the block of Lab 4): cores with a systolic array and a
vector unit, a global buffer, a mesh NoC between them, and DRAM behind the buffer -- run end to end on a layer
=====================================================================================================================

[Why we need it]
    Lectures 5-8 built the blocks one at a time: a systolic array (systolic.py), a vector unit (vector_unit.py), a
    global buffer and DRAM (memory.py, global_buffer.py), a network-on-chip (noc.py). An accelerator is only as fast
    as the slowest of them on a given layer, and data movement BETWEEN them is often that slowest part. This module
    connects them and runs a layer Y = GELU(X @ W):
    1. functionally, on a small layer: every block's own simulator computes its part (the systolic arrays produce
       the GEMM results, the vector units apply GELU, the NoC replays every packet of the data movement), and the
       result is checked against numpy;
    2. analytically, on layer-sized problems: the time each resource needs (DRAM, NoC links, arrays, vector
       units), the bottleneck, and what multicast changes.

[The machine]
    - A k x k mesh NoC (noc.py). The global buffer is split into slices at the gb_nodes; `cores` other nodes each
      hold an R x C weight-stationary systolic array and a vector unit. A flit is flit_bytes wide; a GB slice
      injects and ejects one flit per cycle through its router's local port, so more slices = more GB bandwidth.
    - Work split: the N output columns are divided among the cores. Core c needs its own weight columns (unicast,
      from slice c mod S) and ALL of X (the same activations for every core: a broadcast -- unicast copies, or one
      multicast tree per slice; X's K dimension is spread evenly over the S slices).
    - DRAM feeds the GB at dram_bytes_per_cycle; outputs return to the GB and DRAM.

[Edge cases]
    - Functional mode uses integer inputs (the systolic simulator computes exactly in integers) and converts the
      GEMM results to float32 before GELU.
    - The analytic link loads assume XY routes and that every resource can overlap with every other (double
      buffering everywhere): the layer time is the busiest resource. The functional mode's NoC replay checks the
      NoC part of that assumption.
"""

import math
from dataclasses import dataclass

import numpy as np

import course_path

course_path.use("lecture05", "lecture06")

import noc  # noqa: E402
import systolic as sa  # noqa: E402
import vector_unit as vu  # noqa: E402


@dataclass(frozen=True)
class AccelConfig:
    """
    The toy accelerator.

    [Fields]
        name; k: NoC mesh size; gb_nodes: nodes holding a slice of the global buffer (one or more);
        cores: tuple of core nodes
        R, C: systolic array per core; lanes, sfu_lanes: vector unit per core
        flit_bytes: NoC link width (bytes per flit = per cycle); packet_flits: flits per packet
        dram_bytes_per_cycle: DRAM -> GB bandwidth; elem: bytes per element (2 = bf16)
        multicast: X is delivered by one multicast tree instead of one unicast copy per core
    """
    name: str = "toy accelerator"
    k: int = 3
    gb_nodes: tuple = (4,)
    cores: tuple = (0, 1, 2, 3, 5, 6, 7, 8)
    R: int = 32
    C: int = 32
    lanes: int = 32
    sfu_lanes: int = 8
    flit_bytes: int = 32
    packet_flits: int = 8
    dram_bytes_per_cycle: float = 256.0
    elem: int = 2
    multicast: bool = False

    @property
    def noc(self):
        return noc.NoCConfig(k=self.k, buffer_flits=2 * self.packet_flits)


# =====================================================================================================================
# Data movement: transfers, link loads, packet traces
# =====================================================================================================================

def layer_transfers(cfg, M, K, N):
    """
    The NoC transfers of one layer: (source, destinations, bytes) per logical transfer.

    [Returns] list of (src, [dst, ...], bytes): each GB slice's share of X to every core (one entry with all cores
        as destinations), the weight columns of each core from its slice, and each core's outputs back to its slice.
    """
    P, S = len(cfg.cores), len(cfg.gb_nodes)
    cols = [len(range(c, N, P)) for c in range(P)]          # core c takes columns c, c + P, ... (balanced)
    ks = [len(range(s, K, S)) for s in range(S)]            # slice s holds rows s, s + S, ... of X's K dimension
    out = [(g, list(cfg.cores), M * ks[s] * cfg.elem) for s, g in enumerate(cfg.gb_nodes)]
    for c, node in enumerate(cfg.cores):
        g = cfg.gb_nodes[c % S]
        out.append((g, [node], K * cols[c] * cfg.elem))
        out.append((node, [g], M * cols[c] * cfg.elem))
    return out


def _xy_path(ncfg, src, dst):
    """Directed links (node, port) of the XY route from src to dst."""
    path, node = [], src
    while node != dst:
        port = noc.route_options(ncfg, node, dst)[0]
        path.append((node, port))
        node = ncfg.neighbor(node, port)
    return path


def link_loads(cfg, transfers, multicast=None):
    """
    Flits carried by every directed link, injection port and ejection port.

    [Idea] A unicast transfer loads every link of its XY route with its flits. A multicast transfer loads every
        link of the UNION of its XY routes once (routers replicate the flits), injects once and ejects at every
        destination. The busiest port bounds the NoC time from below: it carries one flit per cycle.
    [Returns] dict (node, port) -> flits, where port is "inj" / "ej" for the local ports
    """
    ncfg = cfg.noc
    mc = cfg.multicast if multicast is None else multicast
    loads = {}

    def add(key, f):
        loads[key] = loads.get(key, 0) + f

    for src, dsts, nbytes in transfers:
        flits = math.ceil(nbytes / cfg.flit_bytes)
        dsts = [d for d in dsts if d != src]
        if not dsts:
            continue
        if mc and len(dsts) > 1:
            links = set()
            for d in dsts:
                links.update(_xy_path(ncfg, src, d))
            for key in links:
                add(key, flits)
            add((src, "inj"), flits)
            for d in dsts:
                add((d, "ej"), flits)
        else:
            for d in dsts:
                for key in _xy_path(ncfg, src, d):
                    add(key, flits)
                add((src, "inj"), flits)
                add((d, "ej"), flits)
    return loads


def packet_trace(cfg, transfers):
    """
    Packets (release cycle 0, src, dst, flits) for the unicast version of the transfers, interleaved over the
    destinations so that no core waits for all the others (round-robin over transfers).
    """
    queues = []
    for src, dsts, nbytes in transfers:
        flits = math.ceil(nbytes / cfg.flit_bytes)
        for d in dsts:
            if d == src:
                continue
            n_full, rest = divmod(flits, cfg.packet_flits)
            sizes = [cfg.packet_flits] * n_full + ([rest] if rest else [])
            queues.append([(0, src, d, z) for z in sizes])
    trace = []
    while any(queues):
        for q in queues:
            if q:
                trace.append(q.pop(0))
    return trace


# =====================================================================================================================
# The layer, analytically
# =====================================================================================================================

def estimate_layer(cfg, M, K, N):
    """
    Time of Y = GELU(X @ W) by resource, assuming every resource overlaps with the others.

    [Returns] dict resource -> cycles (DRAM, NoC busiest port, systolic arrays, vector units), plus "total"
        (the maximum), "bottleneck" and "serial" (the sum: no overlap at all)
    """
    P = len(cfg.cores)
    cols = [len(range(c, N, P)) for c in range(P)]
    dram = (M * K + K * N + M * N) * cfg.elem / cfg.dram_bytes_per_cycle
    loads = link_loads(cfg, layer_transfers(cfg, M, K, N))
    noc_t = max(loads.values())
    arrays = max(sa.estimate(M, K, n, cfg.R, cfg.C, "WS").cycles for n in cols if n)
    work = vu.work_per_element("gelu")
    vec = max(M * n * vu.cycles_per_element(work, cfg.lanes, cfg.sfu_lanes) for n in cols if n)
    res = {"DRAM": dram, "NoC": noc_t, "arrays": arrays, "vector units": vec}
    key = max(res, key=res.get)
    res.update(total=res[key], bottleneck=key, serial=sum(res[k] for k in ("DRAM", "NoC", "arrays", "vector units")))
    return res


# =====================================================================================================================
# The layer, functionally
# =====================================================================================================================

def run_layer(cfg, X, W, scale=1.0 / 64):
    """
    Run Y = GELU(scale * (X @ W)) with every block's own simulator.

    [Idea] 1. The NoC replays the exact packets of the data movement (X to every core, weights to their cores,
              outputs back): noc.run_trace gives the delivery makespan.
           2. Each core's systolic array computes its columns: systolic.simulate (integer, cycle-accurate).
           3. Each core's vector unit applies GELU to its outputs: vector_unit.run on the gelu kernel.
           4. The pieces are assembled and compared with numpy.
    [Args] cfg: AccelConfig; X: integer M x K; W: integer K x N; scale: applied before GELU
    [Returns] dict with Y, cycles per block ("NoC", "arrays", "vector units"), "max_error" vs numpy, and the
        analytic estimate of the same layer for comparison
    [Edge cases] Rows of the vector program are the output columns of one core (length M <= vlen of the unit).
    """
    M, K = X.shape
    N = W.shape[1]
    P = len(cfg.cores)
    transfers = layer_transfers(cfg, M, K, N)
    ms, _ = noc.run_trace(cfg.noc, packet_trace(cfg, transfers))
    Y = np.zeros((M, N), dtype=np.float32)
    arr_cycles, vec_cycles = [], []
    vcfg = vu.VUConfig(lanes=cfg.lanes, sfu_lanes=cfg.sfu_lanes, vlen=max(256, M))
    for c in range(P):
        cols = list(range(c, N, P))
        if not cols:
            continue
        r = sa.simulate(X, W[:, cols], cfg.R, cfg.C, "WS")
        arr_cycles.append(r.cycles)
        acc = (r.C.astype(np.float64) * scale).astype(np.float32)          # (M, n): one vector row per column
        prog = vu.build("gelu", vcfg, len(cols), M, interleave=2)
        out = vu.run(vcfg, prog, {"x": acc.T.ravel()}, vu.DEFAULT_ELEM_BYTES)
        vec_cycles.append(out.cycles)
        Y[:, cols] = out.memory["y"].reshape(len(cols), M).T
    ref = vu.reference("gelu", {"x": (X @ W * scale).T.ravel()}, M)["y"].reshape(N, M).T
    err = float(np.abs(Y - ref).max() / np.abs(ref).max())
    est = estimate_layer(cfg, M, K, N)
    return {"Y": Y, "NoC": ms, "arrays": max(arr_cycles), "vector units": max(vec_cycles), "max_error": err,
            "estimate": est}


# =====================================================================================================================
# Beyond one chip: links between accelerators
# =====================================================================================================================

# Per-direction bandwidth of common links, from the public specifications (GB/s).
LINKS = {
    "PCIe 3.0 x16": 16.0,
    "PCIe 4.0 x16": 32.0,
    "PCIe 5.0 x16": 64.0,
    "NVLink 2 (V100, 6 links)": 150.0,
    "NVLink 3 (A100, 12 links)": 300.0,
    "NVLink 4 (H100, 18 links)": 450.0,
}


def ring_allreduce_seconds(nbytes, P, link_gbps, latency_s=5e-6):
    """
    Time of a ring all-reduce of nbytes over P devices, each with one link of link_gbps (GB/s per direction) to its
    ring neighbour.

    [Idea] (Patarasuk & Yuan 2009) Reduce-scatter then all-gather: 2 (P - 1) steps, each moving nbytes / P per
        device. Bandwidth term 2 (P - 1) / P x nbytes / bandwidth -- almost independent of P -- plus a latency term
        2 (P - 1) x latency per step that dominates small messages.
    """
    if P <= 1:
        return 0.0
    return 2 * (P - 1) / P * nbytes / (link_gbps * 1e9) + 2 * (P - 1) * latency_s


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    cfg = AccelConfig(R=8, C=8, lanes=16, sfu_lanes=4)
    X = rng.integers(-8, 8, (32, 48))
    W = rng.integers(-8, 8, (48, 64))
    res = run_layer(cfg, X, W)
    assert res["max_error"] < 1e-5, res["max_error"]
    # multicast never increases the busiest NoC port; it removes the GB's injection bottleneck for X
    tr = layer_transfers(cfg, 256, 256, 256)
    uni, mc = link_loads(cfg, tr, False), link_loads(cfg, tr, True)
    assert max(mc.values()) < max(uni.values())
    # the analytic NoC bound is a lower bound of the replayed trace, and not far below it
    est = res["estimate"]["NoC"]
    assert est <= res["NoC"] <= 2.0 * est, (est, res["NoC"])
    # all-reduce: bandwidth term ~ 2 x bytes / link for large P
    t = ring_allreduce_seconds(16e9, 8, 300.0, 0.0)
    assert abs(t - 2 * 7 / 8 * 16e9 / 300e9) < 1e-9
    print("toy_accel.py self-test passed")
    print(f"  32 x 48 x 64 layer on {len(cfg.cores)} cores: NoC {res['NoC']} cycles (bound {est:.0f}), arrays "
          f"{res['arrays']}, vector units {res['vector units']}; max error vs numpy {res['max_error']:.1e}")
