"""
rdu.py -- SambaNova's Reconfigurable Dataflow Unit (SN40L) in miniature: a decoder layer as one streaming-dataflow
kernel vs kernel-by-kernel execution, decoding with per-layer calls vs kernel looping, and a three-tier memory
(SRAM / HBM / DDR) that lets one node switch among hundreds of expert models (composition of experts)
==================================================================================================================

[Why we need it]
    Plasticine (Lecture 12) was a research chip: 64 compute units, 16 MiB of SRAM, DDR3. SambaNova turned the same
    ideas into products. The SN40L (Prabhakar et al., MICRO 2024) has 1,040 pattern compute units and 1,040 memory
    units on two 5 nm dies, 520 MiB of on-chip SRAM, 64 GiB of HBM on the package and up to 1.5 TiB of DDR DRAM
    behind it. Two ideas matter for LLMs:
        1. STREAMING DATAFLOW: a whole decoder layer -- projections, attention, normalization, MLP -- is ONE kernel
           laid out across the chip; tiles stream from operator to operator on chip, and HBM carries only weights
           and the KV cache. Lecture 10 fused a few operators per kernel; here the fusion covers the layer.
        2. A THREE-TIER MEMORY: SRAM for the running program's tiles, HBM for the models being served, DDR for
           a large library of models. With fast DDR -> HBM copies, one node can serve a "composition of experts"
           (many specialized models plus a router) instead of one giant model.
    This module models both, reusing Lecture 10's decoder-block graph and Lecture 12's pipeline balancing.

[Main pieces]
    SN40L, RDUSystem, SN40L_NODE, GPUNode, DGX_H100, DGX_A100 : the machines (published numbers + labelled assumptions)
    GENERATIONS                                  : Plasticine -> SN10 -> SN40L, as published
    LLAMA2_7B, LLAMA31_405B (+ Lecture 1's LLAMA3_8B, LLAMA3_70B) : model shapes
    layer_graph, kernels_on, stream_layer        : one decoder layer kernel by kernel vs as one streaming kernel
    decode_token                                 : time per generated token, by call/launch mode and socket count
    footprint, switch_time, simulate_coe         : composition of experts: nodes needed, switching cost, serving

[Sources and assumptions]
    Published (SN40L paper, MICRO 2024): 1,040 PCUs + 1,040 PMUs, 638 BF16 TFLOPS, 520 MiB SRAM, 64 GiB HBM at
    "about 2 TB/s" (1.8 TB/s in its Table II), up to 1.5 TiB DDR at over 200 GB/s, 8 sockets per node, over 1 TB/s
    aggregate DDR -> HBM per node, a fused decoder layer using ~90% of the units and ~85% of the HBM bandwidth,
    DGX host -> GPU copies at 64 GB/s (H100) and 32 GB/s (A100).
    ASSUMED (no published number; swept by the scripts): kernel-call overheads (10 us software-orchestrated, 1 us
    hardware-orchestrated, 4 us per GPU kernel launch as in Lectures 10-11), a 5 us all-reduce latency between
    sockets/GPUs, the tile size of the streaming pipeline, and the fraction of HBM a node keeps for experts.

[Edge cases]
    - These are roofline-style models of SambaNova's published design, not SambaNova's software. The paper's
      own measurements are quoted separately and labelled.
"""

import math
import random
from dataclasses import dataclass, replace

import course_path

course_path.use("lecture01", "lecture10", "lecture12")

import cgra  # noqa: E402
import graph as gr  # noqa: E402
import workloads as wl  # noqa: E402
from hw_specs import A100, H100, Machine  # noqa: E402

# =====================================================================================================================
# The machines
# =====================================================================================================================

SN40L = Machine(
    name="SN40L", full_name="SambaNova SN40L RDU (one socket)", category="reconfigurable", year=2023,
    process="TSMC 5nm, two dies (CoWoS)", peak_ops={"bf16": 638e12},
    mem_name="HBM", mem_bw=2.0e12, mem_capacity=64 * 2**30, onchip_bytes=520 * 2**20,
    source="Prabhakar et al., SambaNova SN40L, MICRO 2024 (HBM 'about 2 TB/s' in the text, 1.8 TB/s in Table II)",
    notes="1,040 PCUs + 1,040 PMUs; up to 1.5 TiB DDR per socket behind the HBM")


@dataclass(frozen=True)
class RDUSystem:
    """
    An SN40L node and the parameters of our models.

    [Fields] chip; pcus; ddr_bytes and ddr_bw per socket; sockets per node; node_ddr_to_hbm (aggregate copy
        bandwidth, published "over 1 TB/s"); usable_pcu (fraction a fused layer can use, published ~90%);
        hbm_eff (fraction of HBM bandwidth a fused kernel sustains, published ~85%);
        call_s / ho_call_s: ASSUMED overhead of one software- / hardware-orchestrated kernel call;
        allreduce_s: ASSUMED latency of one small all-reduce across sockets
    """
    chip: Machine = SN40L
    pcus: int = 1040
    ddr_bytes: float = 1.5 * 2**40
    ddr_bw: float = 200e9
    sockets: int = 8
    node_ddr_to_hbm: float = 1e12
    usable_pcu: float = 0.9
    hbm_eff: float = 0.85
    call_s: float = 10e-6
    ho_call_s: float = 1e-6
    allreduce_s: float = 5e-6


SN40L_NODE = RDUSystem()


@dataclass(frozen=True)
class GPUNode:
    """
    A DGX node (8 GPUs) for comparison.

    [Fields] gpu (hw_specs Machine); gpus; host_to_gpu_bw (the paper's comparison: 64 GB/s DGX H100, 32 GB/s DGX
        A100); launch_s (ASSUMED 4 us per kernel, Lectures 10-11); kernels_per_layer (7 after Lecture 10's fusion);
        hbm_eff (ASSUMED same as the RDU, to isolate the other effects); allreduce_s (ASSUMED 5 us)
    """
    name: str
    gpu: Machine
    gpus: int = 8
    host_to_gpu_bw: float = 64e9
    launch_s: float = 4e-6
    kernels_per_layer: int = 7
    hbm_eff: float = 0.85
    allreduce_s: float = 5e-6


DGX_H100 = GPUNode("DGX H100", H100, host_to_gpu_bw=64e9)
DGX_A100 = GPUNode("DGX A100", A100, host_to_gpu_bw=32e9)

# Published generations (Plasticine: ISCA 2017; SN10: Hot Chips 33, 2021, as reported; SN40L: MICRO 2024).
GENERATIONS = [
    # name, year, compute units, on-chip SRAM (bytes), peak (FLOP/s, format), memory tiers
    ("Plasticine (research)", 2017, "64 PCU + 64 PMU", 16 * 2**20, 12.3e12, "fp32", "DDR3, 51.2 GB/s"),
    ("SN10 (Cardinal)", 2021, "640 PCU + 640 PMU", 320e6, 320e12, "bf16", "DDR4, up to 1.5 TB"),
    ("SN40L", 2023, "1,040 PCU + 1,040 PMU", 520 * 2**20, 638e12, "bf16", "64 GiB HBM (~2 TB/s) + up to 1.5 TiB DDR"),
]

# Model shapes (Hugging Face config.json files); Llama 3 8B / 70B come from Lecture 1's workloads.py.
LLAMA2_7B = wl.TransformerConfig("Llama-2-7B", d_model=4096, n_layers=32, n_heads=32, n_kv_heads=32, head_dim=128,
                                 d_ff=11008, vocab=32000)
LLAMA31_405B = wl.TransformerConfig("Llama-3.1-405B", d_model=16384, n_layers=126, n_heads=128, n_kv_heads=8,
                                    head_dim=128, d_ff=53248, vocab=128256)
MODELS = [LLAMA2_7B, wl.LLAMA3_8B, wl.LLAMA3_70B, LLAMA31_405B]


def weight_bytes(cfg, bytes_per_param=2):
    """bf16 weights of a whole model."""
    return cfg.params() * bytes_per_param


def kv_bytes_per_token(cfg, bytes_per_elem=2):
    """KV-cache bytes per token of context, all layers (K and V, KV heads x head_dim each)."""
    return 2 * cfg.n_layers * cfg.n_kv_heads * cfg.head_dim * bytes_per_elem


# =====================================================================================================================
# 1. One decoder layer: kernel by kernel vs streaming dataflow
# =====================================================================================================================

def layer_graph(T, cfg=wl.LLAMA3_8B):
    """Lecture 10's decoder-block graph for T tokens with cfg's sizes (multi-head attention, as in Lecture 10)."""
    return gr.decoder_block(T=T, d=cfg.d_model, H=cfg.n_heads, hd=cfg.head_dim, F=cfg.d_ff)


def kernels_on(g, chip, strategy, call_s, compute_eff=SN40L_NODE.usable_pcu, mem_eff=SN40L_NODE.hbm_eff):
    """
    Kernel-by-kernel execution of a layer graph on one chip: Lecture 10's fusion strategies and cost model
    (compulsory traffic per kernel, roofline time) plus a fixed overhead per kernel call.

    [Idea] For a fair comparison with stream_layer, every kernel gets the same efficiencies: compute_eff of the peak
        (the streaming kernel uses 90% of the units) and mem_eff of the memory bandwidth (85%).
    [Returns] dict(kernels, flops, hbm_bytes, seconds)
    """
    derated = replace(chip, peak_ops={k: v * compute_eff for k, v in chip.peak_ops.items()},
                      mem_bw=chip.mem_bw * mem_eff)
    n, fl, by, t = gr.summarize(gr.kernel_costs(g, gr.fuse(g, strategy), machine=derated, launch_s=call_s))
    return {"kernels": n, "flops": fl, "hbm_bytes": by, "seconds": t}


def stream_layer(g, system=SN40L_NODE, tile_tokens=32, call_s=None):
    """
    The whole layer as ONE streaming-dataflow kernel on one socket.

    [Idea] Every operator gets its own share of the PCUs, in proportion to its FLOPs (Lecture 12's balance(), over
        usable_pcu x 1,040 units, at least one unit each). Tokens stream through in tiles of tile_tokens; the
        pipeline runs at the speed of its slowest operator, plus a fill: the first tile's trip along the longest
        path of the operator graph (parallel branches such as Q/K/V overlap). Intermediate
        tensors never leave the chip: HBM carries the weights, the layer's input and its output only.
            time = max(pipeline time, HBM bytes / (hbm_eff x bandwidth)) + one kernel call
    [Returns] dict(seconds, hbm_bytes, units (per operator), utilization (useful FLOPs / (time x peak)),
        sram_tile_bytes (tiles in flight), bound)
    [Edge cases] Element-wise operators get one PCU minimum -- the granularity cost seen in Lecture 12. The attention
        operators are charged their full T x T work (Lecture 10's convention).
    """
    chip = system.chip
    call_s = system.call_s if call_s is None else call_s
    peak = chip.peak("bf16")
    per_pcu = peak / system.pcus
    ops = [n for n in g.order if g.nodes[n].op not in gr.SOURCES]
    work = [max(g.flops(n), 1.0) / per_pcu for n in ops]                 # seconds with ONE PCU
    budget = int(system.usable_pcu * system.pcus)
    units = cgra.balance(work, budget)
    steady = max(w / u for w, u in zip(work, units))
    T = g.nodes["x"].shape[0]
    frac = min(tile_tokens, T) / T
    # pipeline fill: the first tile must traverse the longest path of the operator DAG; each operator holds a tile
    # for (its time per T tokens) x tile / T. Parallel branches (Q/K/V, gate/up) overlap.
    lat = {}
    per = dict(zip(ops, (w / u for w, u in zip(work, units))))
    for n in ops:
        prev = [lat[i] for i in g.nodes[n].inputs if i in lat]
        lat[n] = per[n] * frac + (max(prev) if prev else 0.0)
    fill = max(lat.values()) - steady * frac
    t_pipe = steady + fill
    weights = sum(g.nbytes(n) for n in g.order if g.nodes[n].op == "weight")
    io = g.nbytes("x") + g.nbytes("y")
    hbm = weights + io
    t_mem = hbm / (system.hbm_eff * chip.mem_bw)
    t = max(t_pipe, t_mem) + call_s
    flops = sum(g.flops(n) for n in ops)
    tile_bytes = sum(min(tile_tokens, T) / T * g.nbytes(n) for n in ops) * 2   # double-buffered tiles in PMUs
    return {"seconds": t, "hbm_bytes": hbm, "units": dict(zip(ops, units)), "utilization": flops / (t * peak),
            "sram_tile_bytes": tile_bytes, "bound": "pipeline (slowest operator)" if t_pipe >= t_mem else "HBM",
            "flops": flops}


# =====================================================================================================================
# 2. Decoding: per-kernel calls, per-layer calls, kernel looping
# =====================================================================================================================

MODES = ("per-kernel calls", "per-layer calls", "per-layer, hardware-orchestrated", "kernel looping")


def decode_token(cfg, sockets=8, batch=1, ctx=2048, mode="kernel looping", system=SN40L_NODE, gpu_node=None):
    """
    Time to generate one token for each of `batch` sequences with tensor parallelism over `sockets` chips.

    [Idea] Decode reads every weight once per step (shared by the batch) and each sequence's KV cache:
            bytes per chip = (weights + batch x KV(ctx)) / sockets
            time = max(bytes / (hbm_eff x HBM bandwidth), FLOPs / (sockets x peak)) + calls + all-reduces
        calls: "per-kernel calls" = kernels_per_layer x layers x call; "per-layer calls" = layers x call (one fused
        layer kernel each); hardware-orchestrated = layers x ho_call; "kernel looping" = one call per token, the
        layer loop running inside the kernel. Tensor parallelism adds 2 all-reduces per layer when sockets > 1.
        With gpu_node given, the GPU's chip, launch overhead and kernels per layer are used instead.
    [Returns] dict(seconds, memory_s, compute_s, calls_s, comm_s, tokens_per_s_user = 1 / seconds)
    [Edge cases] If a chip's share of weights + KV exceeds its HBM, the RDU streams the overflow from DDR (200 GB/s)
        and a GPU is reported as not fitting (time = inf). The final LM head is counted in the weights; prefill is
        not included. KV heads are assumed to split
        evenly across the chips (true for 8 KV heads on 8 chips; with fewer KV heads than chips the KV would be
        replicated and this underestimates the traffic).
    """
    chip = gpu_node.gpu if gpu_node else system.chip
    eff = gpu_node.hbm_eff if gpu_node else system.hbm_eff
    ar = gpu_node.allreduce_s if gpu_node else system.allreduce_s
    by = (weight_bytes(cfg) + batch * kv_bytes_per_token(cfg) * ctx) / sockets
    cap = chip.mem_capacity
    fits = by <= cap
    if fits:
        t_mem = by / (eff * chip.mem_bw)
    elif gpu_node:
        t_mem = math.inf                                  # a GPU cannot stream the overflow fast enough to serve
    else:                                                 # an RDU streams the overflow from its DDR tier
        t_mem = cap / (eff * chip.mem_bw) + (by - cap) / system.ddr_bw
    flops = batch * (2 * cfg.params() + 4 * cfg.n_layers * cfg.n_heads * cfg.head_dim * ctx)
    t_comp = flops / (sockets * chip.peak("bf16"))
    L = cfg.n_layers
    if gpu_node:
        calls = gpu_node.kernels_per_layer * L * gpu_node.launch_s
    elif mode == "per-kernel calls":
        calls = 7 * L * system.call_s
    elif mode == "per-layer calls":
        calls = L * system.call_s
    elif mode == "per-layer, hardware-orchestrated":
        calls = L * system.ho_call_s
    elif mode == "kernel looping":
        calls = system.call_s
    else:
        raise ValueError(f"mode must be one of {MODES}")
    comm = 2 * L * ar if sockets > 1 else 0.0
    t = max(t_mem, t_comp) + calls + comm
    return {"seconds": t, "memory_s": t_mem, "compute_s": t_comp, "calls_s": calls, "comm_s": comm,
            "tokens_per_s_user": 1 / t, "fits_hbm": fits, "bytes_per_chip": by}


# =====================================================================================================================
# 3. Composition of experts
# =====================================================================================================================

def footprint(n_experts, expert_bytes, node, weight_frac=0.95):
    """
    Nodes needed to keep n_experts available.

    [Idea] RDU node: the experts live in DDR (8 x 1.5 TiB) and are copied into HBM on demand. GPU node: the experts
        must be in HBM (8 x 80 GB) -- host memory is too slow to serve from (see switch_time). weight_frac is the
        share of the holding memory usable for weights.
    [Returns] int, nodes
    """
    if isinstance(node, RDUSystem):
        cap = node.sockets * node.ddr_bytes * weight_frac
    else:
        cap = node.gpus * node.gpu.mem_capacity * weight_frac
    return math.ceil(n_experts * expert_bytes / cap)


def switch_time(expert_bytes, node):
    """
    Time to bring one expert into accelerator memory: DDR -> HBM on an RDU node (over 1 TB/s aggregate),
    host DRAM -> GPU HBM over PCIe on a DGX (the paper's 64 / 32 GB/s).
    """
    if isinstance(node, RDUSystem):
        return expert_bytes / node.node_ddr_to_hbm
    return expert_bytes / node.host_to_gpu_bw


def hbm_slots(expert_bytes, node, keep=0.7):
    """How many experts fit in the node's HBM at once, keeping (1 - keep) for KV cache and activations (ASSUMED)."""
    if isinstance(node, RDUSystem):
        hbm = node.sockets * node.chip.mem_capacity
    else:
        hbm = node.gpus * node.gpu.mem_capacity
    return int(hbm * keep // expert_bytes)


def zipf_sampler(n, s, rng):
    """Draw expert ids 0..n-1 with probability ~ 1 / (rank + 1)^s (s = 0: uniform)."""
    w = [1 / (i + 1) ** s for i in range(n)]
    tot = sum(w)
    cdf = []
    acc = 0.0
    for x in w:
        acc += x / tot
        cdf.append(acc)

    def draw():
        u = rng.random()
        lo, hi = 0, n - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if cdf[mid] < u:
                lo = mid + 1
            else:
                hi = mid
        return lo
    return draw


def simulate_coe(node, n_experts=150, requests=400, out_tokens=20, batch=1, zipf_s=1.0, cfg=LLAMA2_7B, seed=0,
                 mode="kernel looping"):
    """
    Serve a stream of request batches, each routed to one expert, on one node.

    [Idea] The node's HBM caches the most recently used experts (LRU, hbm_slots of them). A batch whose expert is
        not cached first waits for switch_time (DDR -> HBM on the RDU, host -> GPU on a DGX); then it generates
        out_tokens tokens at decode_token's speed (tensor parallel over the 8 chips). Requests are served one batch
        at a time (latency-oriented serving). The cache starts warm with the most popular experts. Experts that do
        not fit in HBM wait in DDR on the RDU (it holds 850+) and in host memory on a DGX.
    [Returns] dict(seconds, per_batch_s (mean latency), hit_rate, switch_share, decode_share)
    """
    rng = random.Random(seed)
    draw = zipf_sampler(n_experts, zipf_s, rng)
    eb = weight_bytes(cfg)
    slots = hbm_slots(eb, node)
    # warm start: the server has preloaded the most popular experts (least popular first in LRU order)
    cache = list(range(min(slots, n_experts)))[::-1]
    t = sw = dec = 0.0
    hits = 0
    gpu = node if isinstance(node, GPUNode) else None
    sockets = node.gpus if gpu else node.sockets
    per_tok = decode_token(cfg, sockets, batch, 1024, mode, gpu_node=gpu)["seconds"]
    for _ in range(requests):
        e = draw()
        if e in cache:
            hits += 1
            cache.remove(e)
        else:
            s = switch_time(eb, node)
            sw += s
            t += s
            if len(cache) >= slots:
                cache.pop(0)
        cache.append(e)
        d = out_tokens * per_tok
        dec += d
        t += d
    return {"seconds": t, "per_batch_s": t / requests, "hit_rate": hits / requests, "switch_share": sw / t,
            "decode_share": dec / t, "slots": slots, "per_token_s": per_tok}


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

if __name__ == "__main__":
    assert abs(SN40L.peak("bf16") / 1040 - 613.5e9) < 1e9
    g = layer_graph(2048)
    k = kernels_on(g, SN40L, "none", SN40L_NODE.call_s)
    s = stream_layer(g)
    assert s["hbm_bytes"] < k["hbm_bytes"] and s["seconds"] < k["seconds"], (s, k)
    assert sum(s["units"].values()) == int(0.9 * 1040)
    # decode: kernel looping is never slower than per-layer calls
    d_loop = decode_token(wl.LLAMA3_8B, 16, 1, 8192, "kernel looping")
    d_layer = decode_token(wl.LLAMA3_8B, 16, 1, 8192, "per-layer calls")
    assert d_loop["seconds"] < d_layer["seconds"]
    # composition of experts: one RDU node holds ~850 Llama-2-7B experts in DDR, a DGX H100 ~45 in HBM
    eb = weight_bytes(LLAMA2_7B)
    assert footprint(850, eb, SN40L_NODE) == 1, footprint(850, eb, SN40L_NODE)
    assert 17 <= footprint(850, eb, DGX_H100) <= 21
    assert abs(switch_time(eb, DGX_H100) / switch_time(eb, SN40L_NODE) - 15.6) < 0.5
    r = simulate_coe(SN40L_NODE, requests=100)
    assert 0 < r["hit_rate"] < 1
    print("rdu.py self-test passed")
    print(f"  Llama-3-8B-sized layer, 2,048 tokens on one SN40L: {k['kernels']} unfused kernels {k['seconds'] * 1e3:.2f} ms"
          f" -> one streaming kernel {s['seconds'] * 1e3:.2f} ms; Llama 3 8B decode on 16 sockets with kernel looping:"
          f" {d_loop['tokens_per_s_user']:,.0f} tokens/s/user (model)")
