"""
neuron.py -- AWS Inferentia and Trainium as a model: NeuronCores with separate tensor, vector, scalar and GpSimd
engines and software-managed SRAM (SBUF, PSUM), a transformer layer scheduled across those engines tile by tile,
SBUF size vs off-chip traffic, collective communication over NeuronLink and EFA, and the numerics of low-precision
training (stochastic rounding, configurable FP8)
==================================================================================================================

[Why we need it]
    A cloud provider that buys accelerators pays the vendor's margin and depends on its supply; one that designs its
    own controls cost, supply and integration with its servers, network and software. AWS's chips are Inferentia
    (inference) and Trainium (training and inference). Their building block, the NeuronCore, makes a design choice
    that this course has met piecemeal (Lectures 5-6): instead of one kind of core, FOUR engines that run in
    parallel, each built for one kind of work --
        Tensor engine  : a 128 x 128 systolic array for matrix multiplication (Lecture 5)
        Vector engine  : 128 lanes for element-wise math and reductions (Lecture 6)
        Scalar engine  : 128 lanes with hardware for non-linear functions (exp, GELU, rsqrt ...) fused with
                         multiply-add before and a reduction after
        GpSimd engine  : 8 programmable 512-bit SIMD processors for everything else (custom C code)
    -- sharing a software-managed SRAM: SBUF (the working memory, 128 partitions) and PSUM (the tensor engine's
    accumulation buffer). Nothing is cached: the compiler (or an NKI kernel) moves every tile with DMA and orders the
    engines with semaphores. This module models that machine at the level of engines and tiles.

[Main pieces]
    NeuronCore, NC_V2, NC_V3, NC_V4         : per-core engine rates and SRAM sizes (published, from AWS's Neuron docs)
    NeuronChip, INF2, TRN1, TRN2, TRN3      : chips (cores, HBM, NeuronLink) with their published peaks
    matmul_seconds, vector_seconds, ...     : time of one operation on one engine (cost rules from the NKI docs)
    Task, schedule                          : an in-order, multi-engine list scheduler (one queue per engine)
    layer_tasks                             : one tensor-parallel shard of a Llama-style decoder layer as engine tasks,
                                              tiled over tokens, with weight / KV DMA and two-deep weight buffering
    ring_allreduce_s, torus_allreduce_s, ultraserver_allreduce_s, efa_allreduce_s : collective times

[Sources and assumptions]
    Published (AWS Neuron documentation, 2024-2026): NeuronCore-v2: 128 x 128 tensor engine at 2.8 GHz (92 TFLOPS
    BF16), vector engine 128 lanes at 1.12 GHz, scalar engine 128 lanes at 1.4 GHz, GpSimd 8 x 512-bit processors,
    SBUF 24 MiB (128 x 192 KiB), PSUM 2 MiB (8 banks of 512 FP32 per partition), 16 DMA engines of 27 GiB/s;
    matmul cost ~max(N, 64) cycles per instruction (N = moving free size <= 512), LoadStationary up to 4x faster and
    overlapped. NeuronCore-v3: tensor 2.4 GHz (79 TFLOPS BF16, 158 FP8 with the double-row mode), vector 512 BF16 /
    256 other elements per cycle at 0.96 GHz, scalar 128 at 1.2 GHz, SBUF 28 MiB. NeuronCore-v4: tensor 2.4 GHz with
    an 8 x 128 MXFP8 input path, SBUF 32 MiB. Chips: Inferentia2 / Trainium (2 x v2, 32 GiB, 820 GB/s), Trainium2
    (8 x v3, 96 GiB, 2.9 TB/s, NeuronLink 1.28 TB/s), Trainium3 (8 x v4, 144 GiB, 4.9 TB/s, NeuronLink 2.56 TB/s).
    Trn2 instance: 16 chips in a 4 x 4 2D torus (1,024 GiB/s per chip inside, 256 GiB/s per chip between instances
    of an UltraServer of 64 chips), EFA 3.2 Tbps per instance.
    ASSUMED (varied by the scripts): per-instruction overheads (64 cycles), a DMA latency per transfer (2 us), the
    vector engine's BF16 speed-up (2x), NeuronCore-v4's vector/scalar rates (= v3), a ring's share of a chip's
    NeuronLink bandwidth (half: one torus dimension), collective step latency (2 us NeuronLink, 10 us EFA).

[Edge cases]
    - The scheduler models engines and DMA as independent in-order queues; SBUF capacity is enforced only through
      two-deep weight buffering, PSUM bank conflicts and SBUF port sharing are ignored.
    - Times are for one NeuronCore running a 1/tp shard of a layer; the all-reduce that joins the shards is costed
      separately (collective functions).
"""

import math
from dataclasses import dataclass, field, replace

import course_path

course_path.use("lecture01", "lecture04", "lecture07")

import workloads as wl  # noqa: E402

GiB = 2 ** 30
MiB = 2 ** 20

# =====================================================================================================================
# 1. Cores and chips (published numbers)
# =====================================================================================================================


@dataclass(frozen=True)
class NeuronCore:
    """
    One NeuronCore: engine rates and SRAM.

    [Fields]
        tensor_hz      : tensor-engine clock; one 128-element column enters the 128 x 128 array per cycle (BF16)
        k_rows         : contraction rows per pass per dtype ({"bf16": 128, "fp8": 256 with v3's double-row mode,
                         "mxfp8": 512 with v4's 8 x 128 input path}); "fp32" runs at 1/4 speed
        vector_hz, vector_lanes, vector_bf16_factor : vector engine (lanes x clock elements/s; BF16 gets a
                         performance mode on v3, ASSUMED 2x on average)
        scalar_hz, scalar_lanes : scalar engine (activation functions)
        gpsimd_hz      : GpSimd: 8 processors x 16 FP32 lanes
        sbuf_bytes, psum_bytes : software-managed SRAM
        hbm_bw         : this core's share of the chip's HBM bandwidth
        overhead_cycles: fixed cost per vector/scalar instruction (ASSUMED 64: the NKI docs give ~60 cycles of
                         static access overhead)
    """
    name: str
    tensor_hz: float
    k_rows: dict
    vector_hz: float
    vector_lanes: int
    vector_bf16_factor: float
    scalar_hz: float
    scalar_lanes: int
    gpsimd_hz: float
    sbuf_bytes: float
    psum_bytes: float
    hbm_bw: float
    overhead_cycles: int = 64
    partitions: int = 128

    def tensor_flops(self, dtype="bf16"):
        """Peak dense FLOP/s of the tensor engine: 2 x 128 columns x k_rows x clock (FP32: a quarter of BF16)."""
        if dtype == "fp32":
            return 2 * 128 * self.k_rows["bf16"] * self.tensor_hz / 4
        return 2 * 128 * self.k_rows[dtype] * self.tensor_hz

    def engine_rate(self, engine, bf16=True):
        """Elements per second of a vector-like engine at full lanes."""
        if engine == "vector":
            return self.vector_lanes * self.vector_hz * (self.vector_bf16_factor if bf16 else 1.0)
        if engine == "scalar":
            return self.scalar_lanes * self.scalar_hz
        if engine == "gpsimd":
            return 8 * 16 * self.gpsimd_hz
        raise ValueError(engine)


NC_V2 = NeuronCore("NeuronCore-v2 (Inf2, Trn1)", tensor_hz=2.8e9, k_rows={"bf16": 128, "fp8": 128},
                   vector_hz=1.12e9, vector_lanes=128, vector_bf16_factor=1.0, scalar_hz=1.4e9, scalar_lanes=128,
                   gpsimd_hz=1.4e9, sbuf_bytes=24 * MiB, psum_bytes=2 * MiB, hbm_bw=820e9 / 2)
NC_V3 = NeuronCore("NeuronCore-v3 (Trn2)", tensor_hz=2.4e9, k_rows={"bf16": 128, "fp8": 256},
                   vector_hz=0.96e9, vector_lanes=256, vector_bf16_factor=2.0, scalar_hz=1.2e9, scalar_lanes=128,
                   gpsimd_hz=1.2e9, sbuf_bytes=28 * MiB, psum_bytes=2 * MiB, hbm_bw=2.9e12 / 8)
NC_V4 = NeuronCore("NeuronCore-v4 (Trn3)", tensor_hz=2.4e9, k_rows={"bf16": 128, "fp8": 512, "mxfp8": 512},
                   vector_hz=0.96e9, vector_lanes=256, vector_bf16_factor=2.0, scalar_hz=1.2e9, scalar_lanes=128,
                   gpsimd_hz=1.2e9, sbuf_bytes=32 * MiB, psum_bytes=2 * MiB, hbm_bw=4.9e12 / 8)


@dataclass(frozen=True)
class NeuronChip:
    """
    One chip: cores, HBM, chip-to-chip links, and its PUBLISHED peaks (dense, per chip).

    [Fields] link_bw: NeuronLink bandwidth per chip (bytes/s); year: general availability of its instances (approximate);
        published: dict dtype -> FLOP/s from AWS's tables
        (they can differ by a few % from cores x per-core rates: the tables round and may use other clocks)
    """
    name: str
    core: NeuronCore
    cores: int
    hbm_bytes: float
    hbm_bw: float
    link_bw: float
    year: int
    published: dict = field(default_factory=dict)

    @property
    def sbuf_total(self):
        return self.cores * self.core.sbuf_bytes

    def peak(self, dtype="bf16"):
        return self.cores * self.core.tensor_flops(dtype)


INF2 = NeuronChip("Inferentia2", NC_V2, 2, 32 * GiB, 820e9, None, 2023,
                  {"bf16": 190e12, "fp8": 190e12, "int8": 380e12, "fp32": 47.5e12})
TRN1 = NeuronChip("Trainium", NC_V2, 2, 32 * GiB, 820e9, 384e9, 2022,
                  {"bf16": 191e12, "fp8": 191e12, "fp32": 48e12})
TRN2 = NeuronChip("Trainium2", NC_V3, 8, 96 * GiB, 2.9e12, 1.28e12, 2024,
                  {"bf16": 667e12, "fp8": 1299e12, "fp32": 181e12})
TRN3 = NeuronChip("Trainium3", NC_V4, 8, 144 * GiB, 4.9e12, 2.56e12, 2025,
                  {"bf16": 671e12, "mxfp8": 2517e12, "fp32": 183e12})
CHIPS = [INF2, TRN1, TRN2, TRN3]

# =====================================================================================================================
# 2. Time of one operation on one engine
# =====================================================================================================================


def matmul_seconds(core, M, K, N, dtype="bf16"):
    """
    Tensor-engine time of C[M x N] = A[M x K] B[K x N] on one NeuronCore.

    [Idea] The NKI cost rule: one matmul instruction streams a "moving" tile of up to 512 columns through a
        "stationary" tile of up to k_rows x 128 held in the array, and takes ~max(n, 64) cycles (n = moving
        columns; 64 = the instruction's start-up). Loading the next stationary tile overlaps the current matmul
        and is up to 4x faster than streaming the same number of columns, so it hides unless n is tiny. Either
        operand can be the stationary one; we take the faster orientation:
            stationary = B (K x N in k_rows x 128 tiles), moving = A^T (M columns) -- good when M is large;
            stationary = A^T (K x M), moving = B (N columns) -- good when M is small (decode).
    [Args] M, K, N: matrix shape; dtype: "bf16", "fp8" (v3 double-row), "mxfp8" (v4), or "fp32" (4x slower)
    [Returns] seconds
    [Edge cases] M, N not multiples of 128 waste array columns; K not a multiple of k_rows wastes rows. This is the
        systolic utilization of Lecture 5.
    """
    kr = core.k_rows["bf16"] if dtype == "fp32" else core.k_rows[dtype]
    slow = 4 if dtype == "fp32" else 1

    def cycles(stat_free, moving):
        chunks = [512] * (moving // 512) + ([moving % 512] if moving % 512 else [])
        per_tile = sum(max(c, 64) for c in chunks)
        ls = 128 / 4                                  # LoadStationary of one tile, in the background
        return math.ceil(K / kr) * math.ceil(stat_free / 128) * max(per_tile, ls)

    return min(cycles(N, M), cycles(M, N)) * slow / core.tensor_hz


def vector_seconds(core, partitions, free, passes=1, engine="vector", bf16=True):
    """
    Time of an element-wise or reduction instruction sequence on the vector, scalar or GpSimd engine.

    [Idea] Data live as [partitions x free]; each engine processes all 128 partitions in parallel, one free element
        per lane per cycle (more for v3's BF16 vector mode). A tensor with fewer than 128 partitions leaves lanes
        idle; one with more is processed in ceil(partitions / 128) instructions. `passes` counts how many times the
        data stream through the engine (e.g. 2 for an op with two input tensors).
    [Args] core; partitions, free: the tensor's layout; passes; engine: "vector", "scalar", "gpsimd"; bf16: data
        in BF16 (vector speed-up)
    [Returns] seconds, including core.overhead_cycles per instruction
    """
    hz = {"vector": core.vector_hz, "scalar": core.scalar_hz, "gpsimd": core.gpsimd_hz}[engine]
    per_lane = core.engine_rate(engine, bf16) / (128 * hz)        # elements per lane per cycle
    instr = math.ceil(partitions / 128)
    return instr * (passes * free / per_lane + core.overhead_cycles) / hz


DMA_LATENCY_S = 2e-6       # ASSUMED fixed cost of one DMA transfer (the NKI docs give ~0.6 us for descriptor generation)


def dma_seconds(core, nbytes):
    """Time to move nbytes between HBM and SBUF at this core's share of HBM bandwidth, plus a fixed latency."""
    return DMA_LATENCY_S + nbytes / core.hbm_bw


# =====================================================================================================================
# 3. A multi-engine list scheduler
# =====================================================================================================================

ENGINES = ("tensor", "vector", "scalar", "gpsimd", "dma")


@dataclass
class Task:
    """One instruction-level task: runs on one engine for `seconds`, after all tasks in `deps` have finished."""
    name: str
    engine: str
    seconds: float
    deps: tuple = ()


def schedule(tasks, engines_map=None):
    """
    In-order list scheduling: every engine executes its tasks in program order, each as soon as the engine is free
    and its dependencies have finished (what the Neuron compiler's semaphores enforce).

    [Args] tasks: list of Task (deps refer to indices of earlier tasks); engines_map: optional dict renaming
        engines (e.g. every non-tensor engine -> "vector" to model a core with ONE general vector engine)
    [Returns] dict: start, finish (lists), makespan, busy (seconds per engine), util (busy / makespan)
    [Edge cases] A dependency on a later task raises ValueError (program order must respect data flow).
    """
    free = {}
    start, finish = [], []
    busy = {}
    for i, t in enumerate(tasks):
        eng = engines_map.get(t.engine, t.engine) if engines_map else t.engine
        ready = 0.0
        for d in t.deps:
            if d >= i:
                raise ValueError(f"task {i} ({t.name}) depends on a later task {d}")
            ready = max(ready, finish[d])
        s = max(ready, free.get(eng, 0.0))
        f = s + t.seconds
        start.append(s)
        finish.append(f)
        free[eng] = f
        busy[eng] = busy.get(eng, 0.0) + t.seconds
    makespan = max(finish) if finish else 0.0
    return {"start": start, "finish": finish, "makespan": makespan, "busy": busy,
            "util": {e: b / makespan for e, b in busy.items()} if makespan else {}}


# =====================================================================================================================
# 4. A decoder layer shard as engine tasks
# =====================================================================================================================


def layer_tasks(core, cfg=wl.LLAMA3_8B, tp=8, batch=1, q_len=2048, kv_len=2048, dtype="bf16", tile=128,
                layout="packed", softmax_engine="scalar"):
    """
    One 1/tp shard (heads and FFN columns split tp ways) of a Llama-style decoder layer on ONE NeuronCore, as a
    list of engine tasks, tiled over tokens and software-pipelined.

    [Idea] For each tile of `tile` tokens (prefill) or for the whole batch (decode), the layer runs:
            RMSNorm (vector: sum of squares; scalar: rsqrt and scale) -> QKV matmul (tensor) -> PSUM eviction (vector)
            -> RoPE (vector) -> per KV-head group: Q K^T (tensor), row max (vector), exp(x - max) with the row sum
            fused (scalar), P transpose (tensor), P V (tensor), divide by the sum (vector) -> O matmul (tensor)
            -> residual add (vector) -> RMSNorm -> gate/up matmul (tensor) -> SiLU (scalar) -> times up (vector)
            -> down matmul (tensor) -> residual add (vector).
        The program interleaves tiles the way a compiler software-pipelines a loop: step s of the program holds stage
        j of tile s - j, so while one tile is in the vector engine the next can be in the tensor engine. Weights are
        loaded by DMA once per layer, in the order they are first needed (prefetched as soon as the DMA queue is
        free: SBUF capacity is studied separately, Script 03); in decode the KV cache streams by DMA too.
    [Args] core; cfg: TransformerConfig; tp: tensor-parallel ways (the shard's heads and FFN width are 1/tp);
        batch, q_len, kv_len: tokens of the step (prefill: q_len = kv_len = prompt; decode: q_len = 1);
        dtype: matmul precision; tile: tokens per tile; layout: "packed" (element-wise ops use all 128 partitions,
        reductions across partitions take an extra tensor-engine pass) or "token-major" (tokens on partitions:
        decode with a small batch leaves lanes idle); softmax_engine: where exp runs ("scalar" or "vector")
    [Returns] list of Task in program order
    [Edge cases] Causal attention in prefill: query tile i attends to (i + 1) tiles of keys. Biases, the KV-cache
        append and sampling are ignored (small).
    """
    d, hd = cfg.d_model, cfg.head_dim
    hq, hkv, F = cfg.n_heads // tp, max(cfg.n_kv_heads // tp, 1), cfg.d_ff // tp
    T = batch * q_len
    wb = 1 if dtype in ("fp8", "mxfp8") else 2
    tiles = [(i, min(tile, T - i)) for i in range(0, T, tile)]
    prefill = q_len > 1

    def ew(n_tok, width, passes=1, engine="vector"):
        """Element-wise op over n_tok tokens x width features in the chosen layout."""
        if layout == "token-major":
            return vector_seconds(core, n_tok, width, passes, engine)
        return vector_seconds(core, 128, n_tok * width / 128, passes, engine)

    def red(n_tok, width, engine="vector"):
        """Reduction along the feature axis: free-axis reduce (token-major), or packed + a tensor-engine pass."""
        if layout == "token-major":
            return vector_seconds(core, n_tok, width, 1, engine), 0.0
        return vector_seconds(core, 128, n_tok * width / 128, 1, engine), matmul_seconds(core, n_tok, 128, 1)

    weights = {"qkv": d * (hq + 2 * hkv) * hd, "o": hq * hd * d, "gate_up": d * 2 * F, "down": F * d}
    external = {f"w_{k}": (f"DMA {k} weights", dma_seconds(core, v * wb)) for k, v in weights.items()}
    if not prefill:
        external["kv"] = ("DMA KV cache", dma_seconds(core, batch * kv_len * 2 * hkv * hd * 2))

    # 1) the stages of each tile: (name, engine, seconds, local deps (stage indices), external deps (keys))
    per_tile = []
    for t0, n in tiles:
        st = []

        def add(name, engine, sec, local=(), ext=()):
            st.append((name, engine, sec, tuple(local), tuple(ext)))
            return len(st) - 1

        def norm(prev, tag):
            v, extra = red(n, d)
            a = add(f"rmsnorm sum of squares ({tag})", "vector", v, [prev])
            if extra:
                a = add(f"rmsnorm cross-partition sum ({tag})", "tensor", extra, [a])
            return add(f"rmsnorm rsqrt * x ({tag})", "scalar", ew(n, d, 1, "scalar"), [a])

        x = add("DMA x tile", "dma", dma_seconds(core, n * d * 2))
        h = norm(x, "attn")
        qkv_w = (hq + 2 * hkv) * hd
        mm = add("qkv matmul", "tensor", matmul_seconds(core, n, d, qkv_w, dtype), [h], ["w_qkv"])
        ev = add("qkv PSUM->SBUF", "vector", ew(n, qkv_w), [mm])
        prev = add("rope", "vector", ew(n, (hq + hkv) * hd, 3), [ev])
        keys = (t0 + n) if prefill else kv_len
        rows = n * (hq // hkv)
        for g in range(hkv):
            s = add("Q K^T", "tensor", matmul_seconds(core, rows, hd, keys, dtype), [prev],
                    [] if prefill else ["kv"])
            v_m, extra = red(rows, keys)
            mx = add("row max", "vector", v_m, [s])
            if extra:
                mx = add("row max cross-partition", "tensor", extra, [mx])
            ex = add("exp + row sum", softmax_engine, ew(rows, keys, 1, softmax_engine), [mx])
            tr = add("P transpose", "tensor", matmul_seconds(core, keys, rows, 128), [ex])
            pv = add("P V", "tensor", matmul_seconds(core, rows, keys, hd, dtype), [tr])
            prev = add("divide by sum", "vector", ew(rows, hd), [pv])
        o = add("o matmul", "tensor", matmul_seconds(core, n, hq * hd, d, dtype), [prev], ["w_o"])
        r1 = add("residual add", "vector", ew(n, d, 2), [o])
        h2 = norm(r1, "ffn")
        gu = add("gate/up matmul", "tensor", matmul_seconds(core, n, d, 2 * F, dtype), [h2], ["w_gate_up"])
        si = add("silu(gate)", "scalar", ew(n, F, 1, "scalar"), [gu])
        mu = add("silu * up", "vector", ew(n, F, 2), [si])
        dn = add("down matmul", "tensor", matmul_seconds(core, n, F, d, dtype), [mu], ["w_down"])
        add("residual add", "vector", ew(n, d, 2), [dn])
        per_tile.append(st)

    # 2) software-pipelined program order: step s emits stage s - i of tile i; an external DMA is emitted just
    #    before its first user (so the DMA queue loads things in the order they are needed)
    tasks, ids, ext_ids = [], [[None] * len(st) for st in per_tile], {}
    for s in range(len(tiles) + max(len(st) for st in per_tile)):
        for i, st in enumerate(per_tile):
            j = s - i
            if not 0 <= j < len(st):
                continue
            name, engine, sec, local, ext = st[j]
            for key in ext:
                if key not in ext_ids:
                    tasks.append(Task(external[key][0], "dma", external[key][1]))
                    ext_ids[key] = len(tasks) - 1
            deps = [ids[i][k] for k in local] + [ext_ids[k] for k in ext]
            tasks.append(Task(name, engine, sec, tuple(deps)))
            ids[i][j] = len(tasks) - 1
    return tasks


def layer_time(core, **kw):
    """Schedule layer_tasks(core, **kw) and return the schedule dict (plus the task list under "tasks")."""
    engines_map = kw.pop("engines_map", None)
    tasks = layer_tasks(core, **kw)
    s = schedule(tasks, engines_map)
    s["tasks"] = tasks
    return s


def engine_totals(tasks):
    """Sum of task seconds per engine (the work, regardless of overlap)."""
    out = {e: 0.0 for e in ENGINES}
    for t in tasks:
        out[t.engine] = out.get(t.engine, 0.0) + t.seconds
    return out


# =====================================================================================================================
# 5. Collective communication
# =====================================================================================================================

NEURONLINK_ALPHA_S = 2e-6       # ASSUMED latency per collective step on NeuronLink
EFA_ALPHA_S = 10e-6             # ASSUMED latency per step over the EFA network
TRN2_INTRA_BW = 1024 * GiB      # published: NeuronLink-v3 bandwidth per chip inside a Trn2 instance
TRN2_INTER_BW = 256 * GiB       # published: per chip between the 4 instances of an UltraServer
TRN2_EFA_BW = 3.2e12 / 8        # published: 3.2 Tbps EFA per 16-chip instance (bytes/s)


def ring_allreduce_s(nbytes, p, bw, alpha):
    """
    Ring all-reduce of nbytes over p nodes: reduce-scatter then all-gather, 2 (p - 1) steps, each moving nbytes / p.

    [Returns] 2 (p - 1) / p x nbytes / bw + 2 (p - 1) alpha seconds (the classic bandwidth-optimal algorithm)
    [Edge cases] p = 1 costs 0.
    """
    if p <= 1:
        return 0.0
    return 2 * (p - 1) / p * nbytes / bw + 2 * (p - 1) * alpha


def torus_allreduce_s(nbytes, px, py, chip_bw, alpha):
    """
    All-reduce on a px x py 2D torus: reduce-scatter along X, all-reduce along Y on 1/px of the data, all-gather
    along X. Each ring uses one torus dimension, i.e. half of a chip's link bandwidth (ASSUMED).

    [Returns] seconds; with 4 x 4 chips there are 2 x 3 + 2 x 3 = 12 latency steps instead of 30 for a 16-chip ring
    """
    bw = chip_bw / 2
    rs = (px - 1) / px * nbytes / bw + (px - 1) * alpha
    ar = ring_allreduce_s(nbytes / px, py, bw, alpha)
    return 2 * rs + ar


def ultraserver_allreduce_s(nbytes, chip_bw=TRN2_INTRA_BW, inter_bw=TRN2_INTER_BW, alpha=NEURONLINK_ALPHA_S):
    """
    All-reduce over a Trn2 UltraServer (4 instances x 16 chips): reduce-scatter inside each 4 x 4 torus, all-reduce
    of the 1/16 shards around the rings that join chips with the same coordinates in the 4 instances, all-gather
    inside the torus.
    """
    bw = chip_bw / 2
    # reduce-scatter over the 16 chips of the torus (X then Y), then the inter-instance ring, then all-gather back
    rs = (3 / 4) * nbytes / bw + 3 * alpha + (3 / 4) * (nbytes / 4) / bw + 3 * alpha
    ar = ring_allreduce_s(nbytes / 16, 4, inter_bw, alpha)
    return 2 * rs + ar


def efa_allreduce_s(nbytes, instances, chip_bw=TRN2_INTRA_BW, efa_bw=TRN2_EFA_BW, alpha=EFA_ALPHA_S):
    """
    Hierarchical all-reduce over `instances` Trn2 instances joined by EFA: reduce-scatter inside each torus (each chip
    ends with 1/16), a ring all-reduce of those shards across instances (each chip gets 1/16 of the instance's EFA
    bandwidth), all-gather inside the torus.
    """
    bw = chip_bw / 2
    rs = (3 / 4) * nbytes / bw + 3 * NEURONLINK_ALPHA_S + (3 / 4) * (nbytes / 4) / bw + 3 * NEURONLINK_ALPHA_S
    ar = ring_allreduce_s(nbytes / 16, instances, efa_bw / 16, alpha)
    return 2 * rs + ar


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

def _self_test():
    # published peaks are reproduced by cores x per-core rates (within the tables' rounding)
    assert abs(NC_V2.tensor_flops("bf16") - 91.75e12) < 0.1e12
    assert abs(NC_V3.tensor_flops("bf16") - 78.6e12) < 0.1e12 and abs(NC_V3.tensor_flops("fp8") - 157.3e12) < 0.1e12
    assert abs(TRN3.peak("mxfp8") - TRN3.published["mxfp8"]) / TRN3.published["mxfp8"] < 0.01
    assert abs(TRN2.peak("fp8") - TRN2.published["fp8"]) / TRN2.published["fp8"] < 0.04
    # a 128 x 128 x 512 matmul is one full instruction: 512 cycles
    assert abs(matmul_seconds(NC_V3, 512, 128, 128) - 512 / 2.4e9) < 1e-15
    # decode GEMV: tiny M, either orientation is far below peak
    t = matmul_seconds(NC_V3, 1, 4096, 4096)
    assert 2 * 4096 * 4096 / t < 0.05 * NC_V3.tensor_flops()
    # scheduler: two independent tasks on different engines overlap; on the same engine they serialize
    s = schedule([Task("a", "tensor", 1.0), Task("b", "vector", 1.0)])
    assert s["makespan"] == 1.0
    s = schedule([Task("a", "tensor", 1.0), Task("b", "tensor", 1.0)])
    assert s["makespan"] == 2.0
    s = schedule([Task("a", "tensor", 1.0), Task("b", "vector", 1.0, (0,))])
    assert s["makespan"] == 2.0
    # a prefill layer is tensor-bound, a batch-1 decode layer DMA-bound
    pre = layer_time(NC_V3, q_len=2048, kv_len=2048)
    dec = layer_time(NC_V3, batch=1, q_len=1, kv_len=4096)
    assert pre["util"]["tensor"] > 0.6 and dec["util"]["dma"] > 0.8
    assert abs(ring_allreduce_s(1e9, 4, 1e9, 0) - 1.5) < 1e-12
    print("neuron.py self-test passed")


if __name__ == "__main__":
    _self_test()
