"""
cgra.py -- a Plasticine-style reconfigurable dataflow architecture in miniature: parallel patterns and their hardware
templates, a compiler from element-wise expressions to pattern compute units, a coarse-grained pipeline simulator,
placement and routing on a 16 x 8 grid, and the cost of spatial (fused) versus kernel-by-kernel execution
=====================================================================================================================

[Why we need it]
    A GPU (Lecture 11) runs one kernel at a time on all its cores and hides latency with thousands of threads. A
    reconfigurable dataflow architecture does the opposite: it lays a whole computation out IN SPACE. Compute units
    are configured once, each with its own small piece of the program, and data streams from unit to unit through a
    static network and on-chip memories. Plasticine (Prabhakar et al., ISCA 2017) is the reference design:
        - Pattern Compute Units (PCUs): a pipeline of 6 stages x 16 SIMD lanes of floating-point units;
        - Pattern Memory Units (PMUs): 256 KiB banked scratchpads with their own address logic;
        - switches carrying scalar, vector and control streams between them;
        - a programming model of PARALLEL PATTERNS (map, reduce, filter, hash-reduce), which tells the compiler what
          is parallel, what is a reduction and what each memory access looks like.
    This module turns those ideas into models we can run.

[Main pieces]
    PlasticineConfig, PLASTICINE                 : the published architecture parameters (Table 3 / Table 5 of the paper)
    p_map, p_reduce, p_fold, p_filter, p_hashreduce, affine_scan : the patterns, executed functionally
    pattern_hw, hashreduce_conflicts             : hardware templates of the patterns (PCUs, PMUs, throughput, latency)
    Node, EXPAND, compile_expr, evaluate          : element-wise expression DAGs -> PCU stages (with port/register limits)
    black_scholes_dag                            : the paper's Black-Scholes benchmark as a DAG
    Stage, simulate_pipeline, balance             : coarse-grained pipelining with bounded FIFOs; PCU allocation
    grid_sites, place, route                      : placement by simulated annealing and XY routing on the unit grid
    gemm_spatial, gemm_tiled_reference            : a GEMM laid out on PCUs and PMUs (with a functional check)
    mlp_kernels, mlp_spatial                      : an MLP block executed kernel by kernel vs as one spatial pipeline

[Sources and assumptions]
    - Architecture numbers: Prabhakar et al., "Plasticine: a reconfigurable architecture for parallel patterns",
      ISCA 2017 -- 64 PCUs + 64 PMUs in a 16 x 8 grid; PCU 16 lanes x 6 stages, 6 registers per stage, 3 vector
      inputs/outputs; PMU 16 banks x 16 KiB; 1 GHz; 4 DDR3-1600 channels = 51.2 GB/s; 112.8 mm^2 at 28 nm; 49 W.
    - ASSUMED: how many FU stages an exp, log, divide or square root expands to (Lecture 6's recipes), the network
      hop latency (2 cycles), the reconfiguration time between kernels (a parameter, swept by the scripts), and the
      link capacity of the routing model. The scripts print them.

[Edge cases]
    - Plasticine computes in fp32 (4-byte words); all byte counts here use 4 bytes per element.
    - Models, not a cycle-accurate simulator of Plasticine: the paper's own numbers come from one, and the notes
      quote them separately.
"""

import math
import random
from dataclasses import dataclass, field

import numpy as np


# =====================================================================================================================
# The architecture
# =====================================================================================================================

@dataclass(frozen=True)
class PlasticineConfig:
    """
    Plasticine's final parameters (ISCA 2017, Tables 3 and 5).

    [Fields] lanes, stages, regs (pipeline registers per stage), vec_in/vec_out (vector ports per PCU), scalar_in;
        pcus, pmus, pmu_bytes, pmu_banks; cols x rows of the unit grid; clock_hz; dram_bw; areas in mm^2; max power.
        hop_cycles (ASSUMED) is the latency of one switch-to-switch hop.
    """
    name: str = "Plasticine (ISCA 2017)"
    lanes: int = 16
    stages: int = 6
    regs: int = 6
    vec_in: int = 3
    vec_out: int = 3
    scalar_in: int = 6
    pcus: int = 64
    pmus: int = 64
    pmu_bytes: int = 256 * 1024
    pmu_banks: int = 16
    cols: int = 16
    rows: int = 8
    clock_hz: float = 1e9
    dram_bw: float = 51.2e9
    pcu_mm2: float = 0.849
    pmu_mm2: float = 0.532
    interconnect_mm2: float = 18.796
    memctrl_mm2: float = 5.616
    total_mm2: float = 112.796
    max_power_w: float = 49.0
    hop_cycles: int = 2

    @property
    def peak_flops(self):
        """64 PCUs x 16 lanes x 6 stages x 2 FLOP (FMA) x 1 GHz = 12.3 TFLOPS (the paper's figure)."""
        return self.pcus * self.lanes * self.stages * 2 * self.clock_hz

    @property
    def pcu_flops(self):
        """Peak FLOP/s of one PCU (96 FMAs per cycle)."""
        return self.lanes * self.stages * 2 * self.clock_hz


PLASTICINE = PlasticineConfig()
WORD = 4                                   # fp32 bytes


# =====================================================================================================================
# 1. Parallel patterns, functionally
# =====================================================================================================================

def p_map(f, *xs):
    """Map: apply f to every element (or to zipped elements of several collections). Fully parallel."""
    return [f(*a) for a in zip(*xs)]


def p_fold(f, init, xs):
    """
    Fold: a SEQUENTIAL accumulation, acc = f(acc, x) element by element.

    [Edge cases] Nothing tells the compiler that f is associative, so it must run the elements in order: one per
        cycle at best, no matter how many lanes the hardware has.
    """
    acc = init
    for x in xs:
        acc = f(acc, x)
    return acc


def p_reduce(op, xs, init, lanes=16, layout="strided"):
    """
    Reduce: combine all elements with an ASSOCIATIVE op, in the order a 16-lane SIMD unit would.

    [Idea] layout="strided" (how vectors stream through a PCU): lane l accumulates elements l, l + 16, l + 32, ...;
        then a log2(16) = 4-level tree combines the lanes. This reorders elements, so op must be associative AND
        commutative (like + or max). layout="blocked": lane l takes a contiguous chunk and the tree combines chunks
        in order, so associativity alone suffices (e.g. composing functions). Either way the result equals a
        sequential fold -- exactly for integers, up to rounding for floats (a different order of additions).
    [Python tip] range(l, n, lanes) walks every lanes-th index starting at l.
    """
    accs = []
    chunk = math.ceil(len(xs) / lanes) if xs else 0
    for l in range(lanes):
        acc = init
        idx = range(l, len(xs), lanes) if layout == "strided" else range(l * chunk, min(len(xs), (l + 1) * chunk))
        for i in idx:
            acc = op(acc, xs[i])
        accs.append(acc)
    while len(accs) > 1:                   # the reduction tree
        accs = [op(accs[i], accs[i + 1]) if i + 1 < len(accs) else accs[i] for i in range(0, len(accs), 2)]
    return accs[0]


def p_filter(pred, xs):
    """Filter (a FlatMap with 0 or 1 outputs per element): keep the elements for which pred holds."""
    return [x for x in xs if pred(x)]


def p_hashreduce(key, val, op, init, xs):
    """
    HashReduce (groupBy + reduce): accumulate val(x) into a bucket chosen by key(x).

    [Hardware link] The buckets live in a banked PMU; elements whose keys map to the same bank in the same cycle
        conflict (Lecture 7) -- see hashreduce_conflicts.
    """
    out = {}
    for x in xs:
        k = key(x)
        out[k] = op(out.get(k, init), val(x))
    return out


def affine_scan(pairs, x0):
    """
    The recurrence x_{i+1} = a_i x_i + b_i, written two ways.

    [Idea] As a fold it looks sequential. But affine maps COMPOSE associatively:
            (a2, b2) o (a1, b1) = (a2 a1, a2 b1 + b2)
        so the same recurrence is a reduce over (a, b) pairs and can run as a parallel tree. Recognizing an
        associative combine is what turns a "sequential" loop into a parallel pattern (Lecture 10's online softmax
        is the same trick).
    [Returns] (x_n by the sequential fold, x_n by the tree of compositions)
    """
    seq = p_fold(lambda x, ab: ab[0] * x + ab[1], x0, pairs)
    comp = p_reduce(lambda f, g: (g[0] * f[0], g[0] * f[1] + g[1]), pairs, (1.0, 0.0), lanes=16, layout="blocked")
    return seq, comp[0] * x0 + comp[1]


# =====================================================================================================================
# 2. Hardware templates of the patterns
# =====================================================================================================================

@dataclass
class PatternHW:
    """Resources and timing of one pattern instance on Plasticine."""
    pcus: int
    pmus: int
    elems_per_cycle: float
    latency: int
    cycles: float
    notes: str = ""


def pattern_hw(kind, n, body_ops, par=16, arch=PLASTICINE, selectivity=1.0, conflict_factor=1.0):
    """
    Hardware template of one pattern: how many PCUs/PMUs it takes, its throughput and pipeline latency.

    [Idea]
        map       : par lanes, each running the body's FU ops in a pipeline -> ceil(par / 16) lane groups, each a
                    chain of ceil(body_ops / 6) PCUs; one element per lane per cycle.
        reduce    : map + an in-PCU tree across the 16 lanes (log2 16 = 4 stages) + an accumulator stage; lane groups
                    are combined by a tree of PCUs.
        filter    : map (the predicate) + compaction of the surviving lanes (a log2 16-stage prefix sum) -> output
                    rate = selectivity x par.
        hashreduce: map + read-modify-write of buckets in PMU banks; bank conflicts divide the rate by
                    conflict_factor (from hashreduce_conflicts).
        fold      : a loop-carried dependence: one element per (dependent-op latency) cycles, whatever par is.
    [Args] kind; n elements; body_ops: FU operations per element; par: parallelization factor (lanes)
    [Returns] PatternHW
    [Edge cases] par is rounded up to whole 16-lane groups; latency counts FU stages plus ASSUMED 2-cycle hops
        between chained PCUs.
    """
    groups = math.ceil(par / arch.lanes)
    chain = max(1, math.ceil(body_ops / arch.stages))
    lat = body_ops + arch.hop_cycles * (chain - 1)
    if kind == "map":
        pcus = groups * chain
        return PatternHW(pcus, 0, par, lat, n / par + lat, "one element per lane per cycle")
    if kind == "reduce":
        extra = int(math.log2(arch.lanes)) + 1
        chain_r = math.ceil((body_ops + extra) / arch.stages)
        tree = groups - 1                       # PCUs combining the groups' partial results
        tree_depth = math.ceil(math.log2(groups)) if groups > 1 else 0
        lat = body_ops + extra + arch.hop_cycles * (chain_r - 1 + tree_depth) + tree_depth
        return PatternHW(groups * chain_r + tree, 0, par, lat, n / par + lat, "lane tree + accumulator")
    if kind == "filter":
        extra = int(math.log2(arch.lanes))
        chain_f = math.ceil((body_ops + extra) / arch.stages)
        lat = body_ops + extra + arch.hop_cycles * (chain_f - 1)
        return PatternHW(groups * chain_f, 0, par * selectivity, lat, n / par + lat,
                         f"output rate = {selectivity:.0%} of the input rate")
    if kind == "hashreduce":
        rate = par / conflict_factor
        return PatternHW(groups * chain, groups, rate, lat + 2, n / rate + lat + 2,
                         f"bank conflicts slow it {conflict_factor:.2f}x")
    if kind == "fold":
        return PatternHW(1, 0, 1 / max(1, body_ops), lat, n * max(1, body_ops) + lat, "loop-carried dependence")
    raise ValueError(f"unknown pattern {kind!r}")


def hashreduce_conflicts(keys_per_cycle=16, banks=16, buckets=1024, trials=2000, seed=0, skew=0.0):
    """
    Average slowdown of a hash-reduce from PMU bank conflicts: cycles per batch of 16 keys = the most keys landing
    in one bank (balls into bins, Lecture 7). With skew > 0 a fraction of keys hit one hot bucket.

    [Returns] float, mean max-bank load (1.0 = no conflicts)
    [Edge cases] Several keys for the SAME bucket in one batch still conflict (a read-modify-write each).
    """
    rng = random.Random(seed)
    tot = 0
    for _ in range(trials):
        load = [0] * banks
        for _ in range(keys_per_cycle):
            b = 0 if rng.random() < skew else rng.randrange(buckets)
            load[b % banks] += 1
        tot += max(load)
    return tot / trials


# =====================================================================================================================
# 3. Compiling element-wise expressions onto PCUs
# =====================================================================================================================

# FU stages per operation. Basic float ops take one stage. Transcendentals and divisions are expanded into
# polynomial/Newton-Raphson sequences (Lecture 6); the counts are ASSUMED, of the order Lecture 6 measured.
EXPAND = {"add": 1, "sub": 1, "mul": 1, "fma": 1, "max": 1, "min": 1, "abs": 1, "neg": 1, "cmp": 1, "select": 1,
          "exp": 6, "log": 6, "recip": 4, "div": 5, "sqrt": 5}


@dataclass(frozen=True)
class Node:
    """One operation of an element-wise expression: name = op(args); args are node or input names, or numbers."""
    name: str
    op: str
    args: tuple


def evaluate(nodes, inputs):
    """
    Evaluate an expression DAG with numpy (the functional reference for the compiled pipeline).

    [Args] nodes: list of Node in a valid order; inputs: dict name -> array or scalar
    [Returns] dict name -> value for every node and input
    """
    env = dict(inputs)

    def val(a):
        return a if isinstance(a, (int, float)) else env[a]

    fns = {"add": lambda a, b: a + b, "sub": lambda a, b: a - b, "mul": lambda a, b: a * b,
           "fma": lambda a, b, c: a * b + c, "max": np.maximum, "min": np.minimum, "abs": np.abs,
           "neg": lambda a: -a, "cmp": lambda a, b: (a < b).astype(float), "select": lambda c, a, b: np.where(c > 0, a, b),
           "exp": np.exp, "log": np.log, "recip": lambda a: 1.0 / a, "div": lambda a, b: a / b, "sqrt": np.sqrt}
    for nd in nodes:
        env[nd.name] = fns[nd.op](*[val(a) for a in nd.args])
    return env


def compile_expr(nodes, outputs, arch=PLASTICINE, vector_inputs=()):
    """
    Pack an element-wise expression into a chain of PCUs, one FU operation per pipeline stage.

    [Idea] Each node expands to EXPAND[op] FU operations (a chain). The FU operations are placed, in the given
        topological order, into consecutive stages: a PCU holds `stages` of them. Two limits close a PCU early:
            - live values: at every stage boundary at most `regs` values may sit in the pipeline registers;
            - ports: values entering a PCU from outside (vector inputs or earlier PCUs) are limited to vec_in.
        Numbers and names not in vector_inputs are scalars (broadcast constants) and use the scalar network.
    [Args] nodes: list of Node; outputs: names that leave the pipeline; vector_inputs: names streamed per element
    [Returns] dict(fu_ops, pcus, stages_used, max_live, max_in, max_out, groups = list of node-name lists per PCU,
        violations = list of strings)
    [Edge cases] A single node needing more inputs than vec_in is reported as a violation (it would need a wider PCU
        or a pre-combining PCU). Output ports are checked after packing.
    """
    vec_inputs = set(vector_inputs)
    # expand nodes into FU operations: (fu_id, node_name, consumed values)
    fu = []
    for nd in nodes:
        k = EXPAND[nd.op]
        args = [a for a in nd.args if isinstance(a, str)]
        for j in range(k):
            consumed = args if j == 0 else [f"{nd.name}#{j - 1}"]
            fu.append((f"{nd.name}#{j}", nd.name, consumed))
    # the value a node exposes is its last FU op
    last = {nd.name: f"{nd.name}#{EXPAND[nd.op] - 1}" for nd in nodes}
    resolve = lambda v: last.get(v, v)                        # noqa: E731
    uses = {}
    for idx, (fid, _, cons) in enumerate(fu):
        for c in cons:
            uses.setdefault(resolve(c), []).append(idx)
    for o in outputs:
        uses.setdefault(resolve(o), []).append(len(fu))      # outputs are used "after the end"
    produced_at = {fid: i for i, (fid, _, _) in enumerate(fu)}

    groups, cur = [], []
    violations = []

    def pcu_inputs(ids):
        vals = set()
        idset = set(ids)
        for i in ids:
            for c in fu[i][2]:
                v = resolve(c)
                p = produced_at.get(v)
                if p is None:
                    if v in vec_inputs:
                        vals.add(v)
                elif p not in idset:
                    vals.add(v)
        return vals

    def live_inside(ids):
        """
        Max number of values held in pipeline registers at a stage boundary inside the PCU: values produced in the
        PCU (or entering it) and still needed after the boundary -- by a later stage, or by a later PCU / the output,
        in which case they ride the pipeline to the PCU's output.
        """
        idset = set(ids)
        ext = pcu_inputs(ids)
        best = 0
        for b in ids[:-1]:
            alive = 0
            for v, us in uses.items():
                p = produced_at.get(v)
                if p is not None and p in idset:
                    alive += p <= b and any(u > b for u in us)
                elif v in ext:
                    alive += any(u > b and u in idset for u in us)
            best = max(best, alive)
        return best

    for i in range(len(fu)):
        trial = cur + [i]
        if cur and (len(trial) > arch.stages or len(pcu_inputs(trial)) > arch.vec_in or
                    live_inside(trial) > arch.regs):
            groups.append(cur)
            trial = [i]
        if len(pcu_inputs(trial)) > arch.vec_in:
            violations.append(f"{fu[i][1]} needs {len(pcu_inputs(trial))} vector inputs")
        cur = trial
    if cur:
        groups.append(cur)
    max_in = max_out = max_live = 0
    for g in groups:
        gs = set(g)
        ins = pcu_inputs(g)
        outs = {fu[i][0] for i in g if any(u not in gs for u in uses.get(fu[i][0], []))}
        max_in, max_out = max(max_in, len(ins)), max(max_out, len(outs))
        max_live = max(max_live, live_inside(g))
        if len(outs) > arch.vec_out:
            violations.append(f"a PCU with {len(outs)} vector outputs (limit {arch.vec_out})")
    return {"fu_ops": len(fu), "pcus": len(groups), "stages_used": len(fu) / (len(groups) * arch.stages),
            "max_live": max_live, "max_in": max_in, "max_out": max_out,
            "groups": [sorted({fu[i][1] for i in g}, key=lambda n: [nd.name for nd in nodes].index(n)) for g in groups],
            "violations": violations}


def black_scholes_dag():
    """
    European call price C = S N(d1) - K e^{-rT} N(d2), with the standard normal CDF N computed by the
    Zelen & Severo polynomial (Abramowitz & Stegun 26.2.17, |error| < 7.5e-8).

    [Returns] (nodes, outputs, vector_inputs); inputs S, K, T are vectors; r and sigma are scalars.
    """
    n = []
    a = n.append
    a(Node("sqrtT", "sqrt", ("T",)))
    a(Node("vol", "mul", ("sigma", "sqrtT")))
    a(Node("ratio", "div", ("S", "K")))
    a(Node("lr", "log", ("ratio",)))
    a(Node("drift", "mul", ("mu", "T")))                  # mu = r + sigma^2 / 2, a scalar
    a(Node("num", "add", ("lr", "drift")))
    a(Node("d1", "div", ("num", "vol")))
    a(Node("d2", "sub", ("d1", "vol")))
    for d in ("d1", "d2"):                                 # N(d) by Zelen & Severo
        a(Node(f"{d}_abs", "abs", (d,)))
        a(Node(f"{d}_t0", "fma", (f"{d}_abs", 0.2316419, 1.0)))
        a(Node(f"{d}_t", "recip", (f"{d}_t0",)))
        a(Node(f"{d}_p4", "fma", (f"{d}_t", 1.330274429, -1.821255978)))
        a(Node(f"{d}_p3", "fma", (f"{d}_t", f"{d}_p4", 1.781477937)))
        a(Node(f"{d}_p2", "fma", (f"{d}_t", f"{d}_p3", -0.356563782)))
        a(Node(f"{d}_p1", "fma", (f"{d}_t", f"{d}_p2", 0.319381530)))
        a(Node(f"{d}_p", "mul", (f"{d}_t", f"{d}_p1")))
        a(Node(f"{d}_sq", "mul", (f"{d}_abs", f"{d}_abs")))
        a(Node(f"{d}_e", "exp", (f"{d}_sq",)))            # exp(-x^2/2) via a scaled input below
        a(Node(f"{d}_phi", "mul", (f"{d}_e", 0.3989422804014327)))
        a(Node(f"{d}_tail", "mul", (f"{d}_phi", f"{d}_p")))
        a(Node(f"{d}_up", "sub", (1.0, f"{d}_tail")))
        a(Node(f"{d}_neg", "cmp", (d, 0.0)))
        a(Node(f"{d}_N", "select", (f"{d}_neg", f"{d}_tail", f"{d}_up")))
    a(Node("disc", "exp", ("mrT",)))                      # mrT = -r T (scalar-times-vector folded upstream)
    a(Node("kd", "mul", ("K", "disc")))
    a(Node("c1", "mul", ("S", "d1_N")))
    a(Node("c2", "mul", ("kd", "d2_N")))
    a(Node("C", "sub", ("c1", "c2")))
    return n, ["C"], ("S", "K", "T", "mrT")


def black_scholes_inputs(n=1000, seed=0, r=0.03, sigma=0.25):
    """Random option parameters and the extra inputs the DAG expects (mu, mrT and the -x^2/2 scaling)."""
    rng = np.random.default_rng(seed)
    S = rng.uniform(50, 150, n)
    K = rng.uniform(50, 150, n)
    T = rng.uniform(0.1, 2.0, n)
    return {"S": S, "K": K, "T": T, "sigma": sigma, "mu": r + sigma * sigma / 2, "mrT": -r * T}, (S, K, T, r, sigma)


def black_scholes_reference(S, K, T, r, sigma):
    """Closed-form Black-Scholes call price with the exact CDF (math.erf)."""
    d1 = (np.log(S / K) + (r + sigma ** 2 / 2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    N = np.vectorize(lambda x: 0.5 * (1 + math.erf(x / math.sqrt(2))))
    return S * N(d1) - K * np.exp(-r * T) * N(d2)


def _fix_phi(nodes):
    """The DAG computes exp(x^2); the CDF needs exp(-x^2/2). Insert the scaling into the 'sq' nodes."""
    out = []
    for nd in nodes:
        if nd.name.endswith("_sq"):
            x = nd.args[0]
            out.append(Node(nd.name, "mul", (x, x)))
            out.append(Node(nd.name + "h", "mul", (nd.name, -0.5)))
        elif nd.name.endswith("_e"):
            out.append(Node(nd.name, "exp", (nd.args[0] + "h",)))
        else:
            out.append(nd)
    return out


# =====================================================================================================================
# 4. Coarse-grained pipelines
# =====================================================================================================================

@dataclass(frozen=True)
class Stage:
    """
    One stage of a coarse-grained pipeline (a PCU chain, a memory unit, a DRAM loader ...).

    [Fields] ii: cycles between consecutive tokens (initiation interval); latency: cycles from start to output;
        ii_jitter: the interval of each token is drawn uniformly from [ii, ii + ii_jitter] (bursty units, e.g. data-
        dependent work or bank conflicts); max_inflight: at most this many tokens inside the stage at once (e.g.
        outstanding DRAM requests); None = unlimited (a fully pipelined unit)
    """
    name: str
    ii: float
    latency: float
    ii_jitter: float = 0.0
    max_inflight: int = None


def simulate_pipeline(stages, tokens, fifo_depth=2, seed=0):
    """
    Token-level simulation of a linear pipeline with bounded FIFOs between stages.

    [Idea] For token i and stage s:
            start[i][s] = max( done[i][s-1],                     the input is available
                               start[i-1][s] + ii_i[s],          the stage accepts tokens at its (possibly varying)
                                                                 initiation interval
                               done[i-M][s],                     at most M = max_inflight tokens inside the stage
                               start[i-D][s+1] - latency[s] )    the output FIFO (depth D) will have a free slot
            done[i][s]  = start[i][s] + latency[s]
        This is the standard recurrence for pipelines with back-pressure (Lecture 2's ready/valid channels at the
        granularity of whole units). Latencies are fixed, so outputs leave in order.
    [Args] stages: list of Stage; tokens: number of tokens (tiles, vectors); fifo_depth: D >= 1; seed: for jitter
    [Returns] dict(cycles, throughput = tokens / cycles, busy = per-stage fraction of cycles spent accepting tokens)
    [Edge cases] With bursty stages and shallow FIFOs the faster stage waits for the slower one token by token.
    """
    rng = random.Random(seed)
    S = len(stages)
    start = [[0.0] * S for _ in range(tokens)]
    done = [[0.0] * S for _ in range(tokens)]
    work = [0.0] * S
    for i in range(tokens):
        for s, st in enumerate(stages):
            ii = st.ii + (rng.uniform(0, st.ii_jitter) if st.ii_jitter else 0.0)
            work[s] += ii
            t = done[i][s - 1] if s > 0 else 0.0
            if i > 0:
                t = max(t, start[i - 1][s] + ii)
            if st.max_inflight and i >= st.max_inflight:
                t = max(t, done[i - st.max_inflight][s])
            if s + 1 < S and i >= fifo_depth:
                t = max(t, start[i - fifo_depth][s + 1] - st.latency)
            start[i][s] = t
            done[i][s] = t + st.latency
    cycles = done[-1][-1]
    return {"cycles": cycles, "throughput": tokens / cycles, "busy": [w / cycles for w in work]}


def balance(work, budget):
    """
    Allocate `budget` units (PCUs) to pipeline stages whose cycles per token with ONE unit are `work`, so that the
    slowest stage is as fast as possible.

    [Idea] Throughput is set by the slowest stage, work[s] / units[s]. Greedily give the next unit to the current
        bottleneck (optimal for this min-max problem with integer units, since each stage's time only falls).
    [Returns] list of units per stage (each >= 1)
    [Edge cases] budget < number of stages raises ValueError.
    """
    if budget < len(work):
        raise ValueError("need at least one unit per stage")
    units = [1] * len(work)
    for _ in range(budget - len(work)):
        s = max(range(len(work)), key=lambda j: work[j] / units[j])
        units[s] += 1
    return units


# =====================================================================================================================
# 5. Placement and routing on the grid
# =====================================================================================================================

def grid_sites(arch=PLASTICINE):
    """
    Sites of the 16 x 8 unit grid: a checkerboard of PCUs and PMUs (as in the paper's figure), plus address
    generators (AGs, the DRAM interfaces) along the left and right edges.

    [Returns] dict kind -> list of (x, y)
    """
    sites = {"PCU": [], "PMU": [], "AG": []}
    for y in range(arch.rows):
        for x in range(arch.cols):
            sites["PCU" if (x + y) % 2 == 0 else "PMU"].append((x, y))
        sites["AG"] += [(-1, y), (arch.cols, y)]
    return sites


def _cost(pos, edges):
    return sum(w * (abs(pos[a][0] - pos[b][0]) + abs(pos[a][1] - pos[b][1])) for a, b, w in edges)


def place(units, edges, arch=PLASTICINE, seed=0, iters=20000, anneal=True):
    """
    Place virtual units on physical sites of the same kind, minimizing weighted wire length (sum of w x Manhattan
    distance) by simulated annealing.

    [Idea] Start from a random legal placement. Repeatedly propose swapping two units of the same kind, or moving a
        unit to a free site of its kind; accept improvements always and worsenings with probability exp(-delta/T),
        with T falling geometrically -- the classic FPGA/CGRA placement algorithm (VPR).
    [Args] units: list of (name, kind); edges: list of (a, b, weight); anneal=False keeps the random placement
    [Returns] (positions dict, initial cost, final cost)
    [Edge cases] More units of a kind than sites raises ValueError.
    """
    rng = random.Random(seed)
    sites = grid_sites(arch)
    pos, free = {}, {}
    for kind in sites:
        names = [u for u, k in units if k == kind]
        if len(names) > len(sites[kind]):
            raise ValueError(f"{len(names)} {kind}s but only {len(sites[kind])} sites")
        avail = sites[kind][:]
        rng.shuffle(avail)
        for u in names:
            pos[u] = avail.pop()
        free[kind] = avail
    kind_of = dict(units)
    adj = {}
    for a, b, w in edges:
        adj.setdefault(a, []).append((b, w))
        adj.setdefault(b, []).append((a, w))

    def local(u, p):
        return sum(w * (abs(p[0] - pos[v][0]) + abs(p[1] - pos[v][1])) for v, w in adj.get(u, []) if v != u)

    c0 = _cost(pos, edges)
    if not anneal:
        return pos, c0, c0
    names = [u for u, _ in units]
    T = max(1.0, c0 / max(1, len(edges)))
    cool = (0.01 / T) ** (1 / iters) if T > 0.01 else 1.0
    for _ in range(iters):
        u = rng.choice(names)
        k = kind_of[u]
        if free[k] and rng.random() < 0.3:
            j = rng.randrange(len(free[k]))
            new = free[k][j]
            d = local(u, new) - local(u, pos[u])
            if d <= 0 or rng.random() < math.exp(-d / T):
                free[k][j] = pos[u]
                pos[u] = new
        else:
            same = [v for v in names if kind_of[v] == k and v != u]
            if not same:
                continue
            v = rng.choice(same)
            pu, pv = pos[u], pos[v]
            before = local(u, pu) + local(v, pv)
            pos[u], pos[v] = pv, pu
            after = local(u, pv) + local(v, pu)
            d = after - before
            if not (d <= 0 or rng.random() < math.exp(-d / T)):
                pos[u], pos[v] = pu, pv
        T *= cool
    return pos, c0, _cost(pos, edges)


def route(pos, edges):
    """
    Route every edge with dimension-order (X then Y) routing over the switch grid and count streams per link.

    [Returns] dict(max_load, total_hops, mean_hops, loads = {link: streams})
    [Edge cases] Edge weights are stream counts; a link is the directed connection between neighbouring switches.
    """
    loads = {}
    hops = 0
    for a, b, w in edges:
        (x0, y0), (x1, y1) = pos[a], pos[b]
        x, y = x0, y0
        while x != x1:
            nx = x + (1 if x1 > x else -1)
            loads[((x, y), (nx, y))] = loads.get(((x, y), (nx, y)), 0) + w
            x = nx
            hops += w
        while y != y1:
            ny = y + (1 if y1 > y else -1)
            loads[((x, y), (x, ny))] = loads.get(((x, y), (x, ny)), 0) + w
            y = ny
            hops += w
    total_w = sum(w for _, _, w in edges)
    return {"max_load": max(loads.values()) if loads else 0, "total_hops": hops,
            "mean_hops": hops / total_w if total_w else 0.0, "loads": loads}


# =====================================================================================================================
# 6. GEMM laid out in space
# =====================================================================================================================

def gemm_tiled_reference(A, B, mt, nt, kt):
    """
    C = A B computed tile by tile in the order the spatial GEMM uses (C tile stationary on chip, K streamed).

    [Returns] C (numpy array); equals A @ B up to fp rounding
    """
    M, K = A.shape
    N = B.shape[1]
    C = np.zeros((M, N))
    for i0 in range(0, M, mt):
        for j0 in range(0, N, nt):
            acc = np.zeros((min(mt, M - i0), min(nt, N - j0)))
            for k0 in range(0, K, kt):
                acc += A[i0:i0 + mt, k0:k0 + kt] @ B[k0:k0 + kt, j0:j0 + nt]
            C[i0:i0 + mt, j0:j0 + nt] = acc
    return C


def gemm_spatial(M, N, K, pcus, arch=PLASTICINE, pmus=None, kt=64):
    """
    A GEMM laid out on `pcus` PCUs and the PMUs: the C tile (mt x nt) stays on chip, A and B panels stream in.

    [Idea] The PCUs compute at most pcus x 96 FMA/cycle. The PMUs hold the C tile and double-buffered A (mt x kt) and
        B (kt x nt) panels. DRAM traffic is the panels re-read for each C tile:
            bytes = 4 (M N K / nt + M N K / mt) + 4 M N        (Lecture 7's tiling formula)
        so larger tiles -- more PMU capacity -- mean fewer DRAM bytes per FLOP (the sqrt(S) law). We pick the
        largest square-ish tile that fits the PMUs (all PMUs by default) and report the bound.
    [Args] M, N, K; pcus; pmus: PMUs available (default all); kt: K panel depth
    [Returns] dict(tile, pmus_used, compute_s, dram_s, seconds, tflops, utilization (of the whole chip), bound,
        intensity (FLOP per DRAM byte))
    [Edge cases] Each PCU needs operand vectors every cycle; we assume the static network multicasts the A and B
        vectors to the PCUs that share them and that PMU banking supplies them (Plasticine's GEMM reached 56% FU
        utilization in the paper -- our compute bound is an upper bound).
    """
    pmus = arch.pmus if pmus is None else pmus
    cap = pmus * arch.pmu_bytes
    best = None
    for mt in (16, 32, 64, 128, 256, 512, 1024, 2048):
        for nt in (16, 32, 64, 128, 256, 512, 1024, 2048):
            if mt > M * 2 or nt > N * 2:
                continue
            need = WORD * (mt * nt + 2 * (mt * kt + kt * nt))
            if need > cap:
                continue
            traffic = WORD * (M * N * K / nt + M * N * K / mt) + WORD * M * N
            if best is None or traffic < best[0]:
                best = (traffic, mt, nt, need)
    traffic, mt, nt, need = best
    flops = 2 * M * N * K
    compute = flops / (pcus * arch.pcu_flops)
    dram = traffic / arch.dram_bw
    t = max(compute, dram)
    return {"tile": (mt, nt), "pmus_used": math.ceil(need / arch.pmu_bytes), "compute_s": compute, "dram_s": dram,
            "seconds": t, "tflops": flops / t / 1e12, "utilization": flops / t / arch.peak_flops,
            "bound": "compute (PCUs)" if compute >= dram else "DRAM bandwidth", "intensity": flops / traffic}


# =====================================================================================================================
# 7. An MLP block: kernel by kernel vs one spatial pipeline
# =====================================================================================================================

GELU_OPS = 10              # FU ops per element of a tanh-approximated GELU (ASSUMED, Lecture 6-style expansion)


def mlp_ops(T, d, F):
    """
    The operators of y = x + W2 GELU(W1 x + b1) for T tokens, as (name, FLOPs, FU-ops-per-element or None,
    input bytes from outside, output bytes) for kernel-by-kernel execution.
    """
    return [
        ("GEMM1 (x W1)", 2 * T * d * F, WORD * (T * d + d * F), WORD * T * F),
        ("bias + GELU", (1 + GELU_OPS) * T * F, WORD * (T * F + F), WORD * T * F),
        ("GEMM2 (h W2)", 2 * T * F * d, WORD * (T * F + F * d), WORD * T * d),
        ("residual add", T * d, WORD * 2 * T * d, WORD * T * d),
    ]


def _elementwise_rate(arch, pcus, ops_per_elem):
    """Elements per second of an element-wise kernel on `pcus` PCUs: each 16-lane group needs ceil(ops/6) PCUs."""
    groups = pcus // max(1, math.ceil(ops_per_elem / arch.stages))
    return groups * arch.lanes * arch.clock_hz


def mlp_kernels(T, d, F, arch=PLASTICINE, reconfig_s=10e-6):
    """
    Kernel-by-kernel: each operator gets the whole fabric, reads its inputs from DRAM and writes its output to DRAM;
    the fabric is reconfigured between kernels (reconfig_s, ASSUMED and swept by the scripts).

    [Returns] dict(seconds, dram_bytes, per-kernel list of (name, seconds, bound))
    """
    rows = []
    total = dram = 0.0
    for name, flops, rd, wr in mlp_ops(T, d, F):
        if name.startswith("GEMM"):
            M, N, K = (T, F, d) if name.startswith("GEMM1") else (T, d, F)
            g = gemm_spatial(M, N, K, arch.pcus, arch)
            t_c = g["compute_s"]
            bytes_ = max(rd + wr, g["dram_s"] * arch.dram_bw)
        else:
            elems = T * (F if "GELU" in name else d)
            ops = GELU_OPS + 1 if "GELU" in name else 1
            t_c = elems / _elementwise_rate(arch, arch.pcus, ops)
            bytes_ = rd + wr
        t_m = bytes_ / arch.dram_bw
        t = max(t_c, t_m) + reconfig_s
        rows.append((name, t, "compute" if t_c >= t_m else "DRAM", bytes_))
        total += t
        dram += bytes_
    return {"seconds": total, "dram_bytes": dram, "kernels": rows}


def mlp_spatial(T, d, F, arch=PLASTICINE, tile_tokens=64, reconfig_s=10e-6):
    """
    One spatial pipeline: GEMM1 -> bias+GELU -> GEMM2 -> residual, all resident at once. Tokens stream through in
    tiles of `tile_tokens`; the hidden activations never leave the chip. Weights stay in PMUs if they fit.

    [Idea] PCUs are split among the stages in proportion to their work (balance()); the pipeline runs at the speed of
        its slowest stage; DRAM carries x in, y out and the weights once. If the weights do not fit in the PMUs the
        program cannot be resident: it is split into two configurations (temporal partitioning) with the hidden
        activations round-tripping through DRAM between them.
    [Returns] dict(seconds, dram_bytes, units per stage, fits, partitions, bound)
    """
    w_bytes = WORD * (2 * d * F + F)
    act_bytes = WORD * tile_tokens * (2 * d + 2 * F) * 2            # double-buffered tiles of x, h, h', y
    fits = w_bytes + act_bytes <= arch.pmus * arch.pmu_bytes
    # work per stage in PCU-cycles per token
    w = [2 * d * F / (arch.lanes * arch.stages * 2),               # GEMM1: FMAs per token / FMAs per PCU-cycle
         F * math.ceil((GELU_OPS + 1) / arch.stages) / arch.lanes,  # GELU: elements x PCUs per 16-lane group / 16
         2 * F * d / (arch.lanes * arch.stages * 2),
         d / arch.lanes]
    if fits:
        units = balance(w, arch.pcus)
        per_token = max(wi / ui for wi, ui in zip(w, units)) / arch.clock_hz
        # a balanced pipeline of S stages over T/tile tiles takes (T/tile + S - 1) tile times; the fill overlaps with
        # streaming the weights in from DRAM
        t_compute = T * per_token + (len(w) - 1) * min(tile_tokens, T) * per_token
        dram = WORD * (T * d * 2) + w_bytes
        t = max(t_compute, dram / arch.dram_bw) + reconfig_s
        return {"seconds": t, "dram_bytes": dram, "units": units, "fits": True, "partitions": 1,
                "bound": "compute (slowest stage)" if t_compute >= dram / arch.dram_bw else "DRAM bandwidth"}
    # temporal partitioning: [GEMM1 + GELU] then [GEMM2 + residual], each with the whole fabric
    parts = [(w[:2], WORD * (T * d + d * F + F) + WORD * T * F), (w[2:], WORD * (T * F + F * d + T * d) + WORD * T * d)]
    total = dram = 0.0
    units_all = []
    for ws, bytes_ in parts:
        units = balance(ws, arch.pcus)
        units_all += units
        per_token = max(wi / ui for wi, ui in zip(ws, units)) / arch.clock_hz
        total += max(T * per_token, bytes_ / arch.dram_bw) + reconfig_s
        dram += bytes_
    return {"seconds": total, "dram_bytes": dram, "units": units_all, "fits": False, "partitions": 2,
            "bound": "split into 2 configurations"}


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

if __name__ == "__main__":
    xs = list(range(1, 101))
    assert p_reduce(lambda a, b: a + b, xs, 0) == p_fold(lambda a, b: a + b, 0, xs) == 5050
    assert p_filter(lambda x: x % 7 == 0, xs)[:3] == [7, 14, 21]
    assert p_hashreduce(lambda x: x % 3, lambda x: 1, lambda a, b: a + b, 0, xs) == {1: 34, 2: 33, 0: 33}
    rng = random.Random(1)
    pairs = [(rng.uniform(0.9, 1.1), rng.uniform(-1, 1)) for _ in range(200)]
    s, c = affine_scan(pairs, 0.5)
    assert abs(s - c) < 1e-9 * max(1, abs(s)), (s, c)
    assert abs(PLASTICINE.peak_flops - 12.288e12) < 1e9
    # Black-Scholes: compiled DAG evaluates to the closed form (CDF polynomial error < 1e-7 relative to S)
    nodes, outs, vin = black_scholes_dag()
    nodes = _fix_phi(nodes)
    ins, (S, K, T, r, sig) = black_scholes_inputs(500)
    env = evaluate(nodes, ins)
    ref = black_scholes_reference(S, K, T, r, sig)
    err = float(np.max(np.abs(env["C"] - ref)))
    assert err < 1e-4, err
    comp = compile_expr(nodes, outs, vector_inputs=vin)
    assert comp["pcus"] >= math.ceil(comp["fu_ops"] / PLASTICINE.stages)
    # pipeline: balanced 3-stage pipeline with ii 1 reaches ~1 token per cycle
    r1 = simulate_pipeline([Stage("a", 1, 5), Stage("b", 1, 7), Stage("c", 1, 3)], 1000)
    assert r1["throughput"] > 0.98
    r2 = simulate_pipeline([Stage("a", 1, 5), Stage("b", 4, 7), Stage("c", 1, 3)], 1000)
    assert abs(r2["throughput"] - 0.25) < 0.01
    assert balance([8, 2, 4], 7) == [4, 1, 2]
    # GEMM tiling reference
    A = np.random.default_rng(0).normal(size=(70, 50))
    B = np.random.default_rng(1).normal(size=(50, 90))
    assert np.allclose(gemm_tiled_reference(A, B, 32, 16, 8), A @ B)
    g = gemm_spatial(4096, 4096, 4096, 64)
    # placement improves wire length
    units = [(f"c{i}", "PCU") for i in range(16)] + [(f"m{i}", "PMU") for i in range(16)]
    edges = [(f"m{i}", f"c{i}", 1) for i in range(16)] + [(f"c{i}", f"c{i + 1}", 1) for i in range(15)]
    pos, c0, c1 = place(units, edges, iters=5000)
    assert c1 < c0
    print("cgra.py self-test passed")
    print(f"  Black-Scholes: {comp['fu_ops']} FU ops -> {comp['pcus']} PCUs per 16 lanes (max error vs closed form "
          f"{err:.1e}); 4096^3 GEMM on 64 PCUs: tile {g['tile']}, {g['tflops']:.1f} TFLOPS ({g['bound']})")
