"""
fabrics.py -- interconnect topologies by the numbers, a Benes permutation network with its looping algorithm,
multicast and reduction trees, and a SIGMA-style flexible fabric for sparse and irregular GEMMs
=============================================================================================================

[Why we need it]
    A NoC (noc.py) moves packets between arbitrary nodes. Inside a compute engine the patterns are more specific:
    the same weight or activation goes to many PEs (MULTICAST), partial sums from many PEs combine into one output
    (REDUCTION), and a sparse computation needs each PE to receive an arbitrary operand (a PERMUTATION). The
    fabric that carries these patterns -- bus, crossbar, tree, mesh, Benes network -- trades wires and switches
    against bandwidth and flexibility. This module puts numbers on that trade:
    1. topology metrics: links, switches, bisection bandwidth, diameter, average hops, and the uniform-traffic
       throughput bound each topology allows;
    2. a Benes network routed by the classic looping algorithm (any permutation, conflict-free, with
       N/2 x (2 log2 N - 1) 2x2 switches instead of a crossbar's N^2 crosspoints), checked by simulation;
    3. multicast and reduction on a mesh: unicast copies vs trees;
    4. SIGMA (Qin et al., HPCA 2020): a Benes distribution network plus a forwarding adder network let a flat pool
       of multipliers hold only the NON-ZERO weights of a sparse layer, in groups of any size -- compared with a
       rigid systolic array (Lecture 5) that spends a PE on every zero.

[Edge cases]
    - Topology formulas assume N = k x k nodes (mesh, torus) or a power of two (trees, Benes); avg_hops for mesh and
      torus is computed exactly by enumeration (small N only: N <= 1024).
    - The flexible-fabric model counts cycles at the level of "folds" (one load of stationary operands); it does
      not simulate the networks cycle by cycle.
"""

import math
from dataclasses import dataclass

import numpy as np

import course_path

course_path.use("lecture05")

import systolic as sa  # noqa: E402


# =====================================================================================================================
# 1. Topologies by the numbers
# =====================================================================================================================

@dataclass
class Topology:
    """
    Static properties of a topology connecting N nodes.

    [Fields] name; nodes; links (bidirectional links, a bus counted as 1); switch_cost (crosspoints of all
        switches: a radix-r crossbar router costs r^2); bisection (links cut by the best balanced cut, one
        direction); diameter (hops); avg_hops (uniform traffic); radix (router ports)
    [Properties] uniform_bound: max flits/node/cycle under uniform traffic = 4 x bisection / nodes (half of all
        traffic crosses the cut, half of that in each direction); for a bus, 1 / nodes (one transfer per cycle)
    """
    name: str
    nodes: int
    links: int
    switch_cost: int
    bisection: float
    diameter: int
    avg_hops: float
    radix: int

    @property
    def uniform_bound(self):
        if self.name.startswith("bus"):
            return 1.0 / self.nodes
        return min(1.0, 4.0 * self.bisection / self.nodes)


def _grid_avg_hops(k, torus):
    """Exact average hop count between distinct nodes of a k x k mesh or torus (minimal routing)."""
    d1 = np.abs(np.arange(k)[:, None] - np.arange(k)[None, :])
    if torus:
        d1 = np.minimum(d1, k - d1)
    s = d1.sum()                                       # sum over ordered pairs of one coordinate
    total = 2 * s * k * k                              # x and y contributions over all ordered node pairs
    n = k * k
    return total / (n * (n - 1))


def topologies(N):
    """
    The classic topologies for N nodes (N a perfect square and a power of two, e.g. 16, 64, 256).

    [Returns] list of Topology
    """
    k = int(round(math.sqrt(N)))
    lg = int(round(math.log2(N)))
    out = [
        Topology("bus (shared)", N, 1, N, 1, 1, 1.0, N),
        Topology("ring", N, N, N * 9, 2, N // 2, N * N / 4 / (N - 1), 3),
        Topology(f"mesh {k}x{k}", N, 2 * k * (k - 1), N * 25, k, 2 * (k - 1), _grid_avg_hops(k, False), 5),
        Topology(f"torus {k}x{k}", N, 2 * k * k, N * 25, 2 * k, 2 * (k // 2), _grid_avg_hops(k, True), 5),
        Topology("binary tree", N, 2 * N - 2, (N - 1) * 9, 1, 2 * lg, None, 3),
        Topology("fat tree (full bisection)", N, N * lg, (N // 2) * lg * 16, N / 2, 2 * lg, None, 4),
        Topology("crossbar", N, N, N * N, N / 2, 1, 1.0, N),
    ]
    # average hops of the trees: half of all pairs are in different halves (path through the root), recursively
    for t in out:
        if t.avg_hops is None:
            hops = 0.0
            for level in range(1, lg + 1):                 # pairs whose lowest common ancestor is `level` up
                pairs = N * (2 ** (level - 1))             # ordered pairs with LCA at this level
                hops += pairs * 2 * level
            t.avg_hops = hops / (N * (N - 1))
    return out


# =====================================================================================================================
# 2. Benes network
# =====================================================================================================================

def benes_route(perm):
    """
    Switch settings that make a Benes network realize a permutation (output perm[i] receives input i).

    [Idea] (The looping algorithm.) A Benes network of N = 2^n ports is: a column of N/2 input switches, two
        Benes networks of N/2 ports (upper U and lower L), a column of N/2 output switches. Each input switch
        must send its two inputs to DIFFERENT subnetworks, and each output switch must receive its two outputs
        from different subnetworks. Build a graph whose nodes are the N connections: link two connections if they
        share an input switch or an output switch. Every node has degree 2 and the graph is a union of even
        cycles, so it can be 2-coloured: colour = subnetwork. Then each subnetwork must realize a smaller
        permutation, routed recursively.
    [Args] perm: list of length N (a power of two >= 2); perm[i] = output port of input i
    [Returns] nested settings: for N = 2, a single bool (True = crossed); otherwise a dict with "in" (list of
        N/2 bools), "out" (list of N/2 bools), "up", "low" (settings of the subnetworks)
    [Edge cases] Raises ValueError if perm is not a permutation of range(N) or N is not a power of two.
    """
    N = len(perm)
    if N < 2 or N & (N - 1) or sorted(perm) != list(range(N)):
        raise ValueError("perm must be a permutation of range(N), N a power of two >= 2")
    if N == 2:
        return perm[0] == 1
    inv = [0] * N
    for i, o in enumerate(perm):
        inv[o] = i
    color = [None] * N                                  # subnetwork of the connection that starts at input i
    for start in range(N):
        if color[start] is not None:
            continue
        i, c = start, 0
        while color[i] is None:
            color[i] = c
            partner_in = i ^ 1                          # the other input of the same input switch
            if color[partner_in] is None:
                color[partner_in] = 1 - c
            # the partner's output shares an output switch with another connection: it must take colour c
            o = perm[partner_in] ^ 1
            i, c = inv[o], c
    half = N // 2
    sub = {0: [None] * half, 1: [None] * half}
    in_set, out_set = [False] * half, [False] * half
    for i in range(N):
        s = color[i]
        sw_in, sw_out = i // 2, perm[i] // 2
        if (i % 2) != s:
            in_set[sw_in] = True                         # crossed: input i leaves on the other side
        if (perm[i] % 2) != s:
            out_set[sw_out] = True
        sub[s][sw_in] = sw_out
    return {"in": in_set, "out": out_set, "up": benes_route(sub[0]), "low": benes_route(sub[1])}


def benes_apply(settings, values):
    """
    Push `values` (one per input port) through a Benes network with the given settings; returns the outputs.

    [Idea] Input switch j takes inputs 2j, 2j+1; straight sends 2j to the upper subnetwork's port j and 2j+1 to
        the lower subnetwork's port j (crossed swaps them). Output switch j receives upper port j and lower port j
        and sends them to outputs 2j, 2j+1 (swapped when crossed).
    """
    N = len(values)
    if N == 2:
        return list(reversed(values)) if settings else list(values)
    half = N // 2
    up, low = [None] * half, [None] * half
    for j in range(half):
        a, b = values[2 * j], values[2 * j + 1]
        if settings["in"][j]:
            a, b = b, a
        up[j], low[j] = a, b
    up = benes_apply(settings["up"], up)
    low = benes_apply(settings["low"], low)
    out = [None] * N
    for j in range(half):
        a, b = up[j], low[j]
        if settings["out"][j]:
            a, b = b, a
        out[2 * j], out[2 * j + 1] = a, b
    return out


def butterfly_conflicts(perm):
    """
    Link conflicts when a butterfly network (log2 N stages, one path per input-output pair) routes a permutation.

    [Idea] With destination-tag routing, after stage s a message occupies the row whose top s + 1 bits are the
        destination's and whose remaining bits are still the source's. Two messages on the same row after the same
        stage need the same link: a conflict (one must wait or be sent again). A Benes network is a butterfly
        followed by its mirror image; the extra log2 N - 1 stages give every connection a choice of paths, which
        is what makes it rearrangeably non-blocking.
    [Returns] number of (stage, row) links requested by more than one message
    """
    N = len(perm)
    n = int(round(math.log2(N)))
    conflicts = 0
    for s in range(n):
        low = n - 1 - s
        rows = [((d >> low) << low) | (i & ((1 << low) - 1)) for i, d in enumerate(perm)]
        conflicts += len(rows) - len(set(rows))
    return conflicts


def benes_switches(N):
    """2x2 switches in an N-port Benes network: N/2 per stage, 2 log2 N - 1 stages."""
    return (N // 2) * (2 * int(round(math.log2(N))) - 1)


# =====================================================================================================================
# 3. Multicast and reduction on a mesh
# =====================================================================================================================

def mesh_broadcast(k, flits, src=0, hop=2):
    """
    Deliver `flits` flits from node src to every other node of a k x k mesh (e.g. a weight tile to all PEs).

    [Idea]
        unicast : N - 1 separate packets. They all leave through src's injection port, one flit per cycle, so the
                  last one leaves after (N - 1) x flits cycles; link traversals = flits x sum of hop distances.
        tree    : one packet that routers replicate (an XY tree: along src's row, then up and down every column).
                  Every link of the spanning tree carries the data once: (N - 1) x flits link traversals, and the
                  time is the flits plus the depth of the tree (the mesh diameter) x per-hop delay.
    [Returns] dict with "unicast" and "tree": (cycles, link-flit traversals)
    """
    N = k * k
    sx, sy = src % k, src // k
    dist = sum(abs(n % k - sx) + abs(n // k - sy) for n in range(N))
    far = max(abs(n % k - sx) + abs(n // k - sy) for n in range(N))
    unicast = ((N - 1) * flits + far * hop, dist * flits)
    tree = (flits + far * hop, (N - 1) * flits)
    return {"unicast": unicast, "tree": tree}


def mesh_reduce(k, flits, dst=0, hop=2):
    """
    Combine `flits` flits of partial sums from every node into node dst (e.g. split-K partial outputs).

    [Idea]
        gather : every node sends its partials to dst, which adds them; dst's ejection port receives
                 (N - 1) x flits flits, one per cycle.
        tree   : routers add as packets meet on an XY reduction tree (in-network reduction); each link carries the
                 partial sums once, and the time is flits + depth x per-hop delay.
    [Returns] dict with "gather" and "tree": (cycles, link-flit traversals)
    """
    b = mesh_broadcast(k, flits, dst, hop)
    return {"gather": b["unicast"], "tree": b["tree"]}


# =====================================================================================================================
# 4. Flexible reduction and SIGMA
# =====================================================================================================================

def segmented_reduce(values, groups):
    """
    Sums of contiguous groups of `values`, computed level by level as a forwarding adder tree would.

    [Idea] At level l, neighbouring partial sums are added if they belong to the same group; a partial sum at a
        group boundary is FORWARDED (not added) to the next level. Any mix of group sizes is reduced in
        ceil(log2 N) levels with at most N - 1 additions -- the property of SIGMA's forwarding adder network (FAN),
        which a plain binary adder tree lacks (it can only reduce aligned power-of-two groups).
    [Args] values: 1-D array; groups: list of group sizes summing to len(values)
    [Returns] (sums: array of one sum per group, levels: tree depth, adds: additions performed)
    """
    vals = np.asarray(values, dtype=np.float64)
    if sum(groups) != len(vals):
        raise ValueError("group sizes must add up to the number of values")
    gid = np.repeat(np.arange(len(groups)), groups)
    items = list(zip(gid.tolist(), vals.tolist()))
    levels = adds = 0
    while len(items) > len(groups):
        nxt = []
        i = 0
        while i < len(items):
            if i + 1 < len(items) and items[i][0] == items[i + 1][0]:
                nxt.append((items[i][0], items[i][1] + items[i + 1][1]))
                adds += 1
                i += 2
            else:
                nxt.append(items[i])                        # forwarded
                i += 1
        items = nxt
        levels += 1
    return np.array([v for _, v in items]), levels, adds


def rigid_tree_cost(groups, N):
    """
    Multiplier slots a plain binary adder tree needs: every group must occupy an aligned power-of-two block.

    [Returns] slots used (<= N means it fits in one pass)
    """
    return sum(1 << max(0, math.ceil(math.log2(g))) for g in groups if g > 0)


def sparse_weights(K, N, density, rng):
    """A K x N weight matrix with random unstructured sparsity (each entry non-zero with probability density)."""
    W = rng.normal(size=(K, N))
    return W * (rng.random((K, N)) < density)


def sigma_cycles(M, W, n_mult, depth_pipeline=None):
    """
    Cycles and utilization of a SIGMA-style flexible engine on X (M x K) @ W (K x N) with sparse W.

    [Idea] The non-zeros of W are the stationary operands. They are packed column by column into the pool of
        n_mult multipliers -- a column's non-zeros form one contiguous group, reduced by the forwarding adder
        network. A "fold" is one such load; per fold, the rows of X stream through: each cycle the Benes
        distribution network delivers to every multiplier the X element its weight needs (multicast), and the
        FAN reduces the groups. If all non-zeros fit with room to spare, the stationary set is REPLICATED
        floor(n_mult / nnz) times and that many rows of X are processed per cycle (spatial unrolling over M).
        Cycles = folds x ceil(M / copies) + pipeline depth (distribution + reduction, ~2 log2 n_mult).
    [Returns] (cycles, utilization = useful MACs / (cycles x n_mult), folds)
    [Edge cases] An all-zero W costs only the pipeline depth.
    """
    nnz_cols = (W != 0).sum(axis=0)
    nnz = int(nnz_cols.sum())
    depth = depth_pipeline if depth_pipeline is not None else 2 * int(math.ceil(math.log2(n_mult)))
    if nnz == 0:
        return depth, 0.0, 0
    if nnz <= n_mult:
        copies = n_mult // nnz
        folds = 1
        cycles = math.ceil(M / copies) + depth
    else:
        folds, used = 1, 0
        for c in nnz_cols:                                 # first-fit packing of column groups into folds
            c = int(c)
            while c > 0:
                take = min(c, n_mult - used)
                used += take
                c -= take
                if used == n_mult:
                    folds += 1
                    used = 0
        if used == 0:
            folds -= 1
        cycles = folds * M + depth
    return cycles, M * nnz / (cycles * n_mult), folds


def rigid_cycles(M, W, R, C):
    """
    Cycles and utilization of a rigid R x C weight-stationary systolic array (Lecture 5) on the same GEMM: zeros
    occupy PEs like any weight, so useful MACs = M x nnz(W).
    """
    K, N = W.shape
    est = sa.estimate(M, K, N, R, C, "WS")
    useful = M * int((W != 0).sum())
    return est.cycles, useful / (est.cycles * R * C)


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # Benes: every random permutation is routed conflict-free
    for N in (2, 4, 8, 16, 64):
        for _ in range(50):
            perm = list(rng.permutation(N))
            st = benes_route(perm)
            out = benes_apply(st, list(range(N)))
            assert all(out[perm[i]] == i for i in range(N)), (N, perm)
    assert benes_switches(64) == 32 * 11
    assert butterfly_conflicts(list(range(16))) == 0                  # the identity is easy for a butterfly
    assert sum(butterfly_conflicts(list(rng.permutation(64))) > 0 for _ in range(50)) == 50
    # topology numbers
    t = {x.name: x for x in topologies(64)}
    assert t["mesh 8x8"].bisection == 8 and abs(t["mesh 8x8"].uniform_bound - 0.5) < 1e-12
    assert abs(t["mesh 8x8"].avg_hops - 2 * (64 - 1) / (3 * 8) * 64 / 63) < 0.01 or t["mesh 8x8"].avg_hops > 5
    # multicast tree vs unicast
    b = mesh_broadcast(4, 64)
    assert b["tree"][0] < b["unicast"][0] and b["tree"][1] < b["unicast"][1]
    # segmented reduction = numpy group sums, in ceil(log2 N) levels at most, with N - groups additions
    v = rng.normal(size=64)
    groups = [3, 1, 7, 13, 8, 32]
    sums, levels, adds = segmented_reduce(v, groups)
    ref = [v[s:s + g].sum() for s, g in zip(np.cumsum([0] + groups[:-1]), groups)]
    assert np.allclose(sums, ref) and levels <= 6 and adds == 64 - len(groups)
    assert rigid_tree_cost(groups, 64) > 64                 # a plain tree must pad: it does not fit
    # SIGMA beats a rigid array on sparse weights, and loses nothing much on dense ones
    W = sparse_weights(256, 256, 0.1, rng)
    c_s, u_s, _ = sigma_cycles(512, W, 16384)
    c_r, u_r = rigid_cycles(512, W, 128, 128)
    assert u_s > 5 * u_r, (u_s, u_r)
    print("fabrics.py self-test passed")
    print(f"  64-port Benes: {benes_switches(64)} 2x2 switches (= {4 * benes_switches(64)} crosspoints) vs 4,096 for a crossbar")
    print(f"  10%-dense 256x256 weights, M = 512: flexible utilization {u_s:.2f} vs rigid 128x128 {u_r:.3f}")
