"""
cluster.py -- NVIDIA GPUs from one chip to a data center: a decade of GPU generations and where their speedup came
from, scale-up (NVLink domains of 8 or 72 GPUs) and scale-out (InfiniBand) collectives, LLM serving with tensor and
pipeline parallelism, and LLM training with 3D (tensor x pipeline x data) parallelism
=================================================================================================================

[Why we need it]
    Lecture 11 looked inside one GPU. Since Volta, NVIDIA's gains have come as much from what surrounds the SM as
    from the SM: narrower number formats in the tensor cores (FP16 -> FP8 -> FP4), structured sparsity, asynchronous
    data movement (TMA), and ever larger NVLink domains -- from 8 GPUs in an HGX server to 72 in a GB200 NVL72 rack.
    A model of a modern LLM deployment must therefore span three scales:
        chip    : peak FLOPs per format, HBM bandwidth and capacity, power (the datasheets)
        domain  : GPUs joined by NVLink switches -- ~1 TB/s per GPU, microsecond latencies
        cluster : domains joined by InfiniBand / Ethernet -- ~50 GB/s per GPU
    and the three parallelisms that map a model onto them: tensor (split every layer; chatty: needs the domain),
    pipeline (split the layers; point-to-point), data (split the batch; one big all-reduce per step).

[Main pieces]
    GPU, GPUS, K40 ... GB200        : dense peaks per format, memory, power (published; a few ASSUMED, labelled)
    DALLY_2023                      : Dally's published decomposition of 1000x single-chip inference gain
    decompose(old, new)             : our own decomposition from datasheet numbers
    Fabric, NVLINK_H100, NVLINK_B200, IB_400G : link bandwidth per GPU and per-step latency
    allreduce_s, hier_allreduce_s, alltoall_s : collective times (ring or in-switch reduction; hierarchical)
    Domain, HGX_H100, NVL72         : a scale-up domain (GPU, size, fabric) inside a cluster (network)
    decode_step                     : one decode step of a dense LLM with TP within / across domains and PP
    train_step                      : one training step with TP x PP x DP: GEMM time (Lecture 11's GEMM model),
                                      pipeline bubble, TP/PP/DP communication, memory per GPU

[Sources and assumptions]
    Published: NVIDIA datasheets (K40, P100, V100, A100, H100, B200; dense = half of "with sparsity"); GB200 NVL72
    specification page (72 GPUs; 360 PFLOPS sparse BF16 = 2.5 PFLOPS dense per GPU; 13.4 TB HBM3E at 576 TB/s;
    130 TB/s NVLink = 1.8 TB/s per GPU); Dally, Hot Chips 2023 keynote (16x number representation, 12.5x complex
    instructions, 2.5x process, 2x sparsity = 1000x); Llama 3 paper (Dubey et al. 2024): 405B trained on up to
    16K H100 GPUs with 3D parallelism, 38-43% BF16 MFU; activation memory per layer 34 s b d bytes with selective
    recomputation (Korthikanti et al. 2022).
    ASSUMED: B200's die area (2 x 800 mm^2) and GB200's power per GPU (1,200 W); NVLink step latency 1 us and IB
    5 us; 400 Gb/s of network per GPU; communication overlap fractions; GEMM efficiency taken from Lecture 11's H100
    model for every generation.

[Edge cases]
    - Dense models only (no mixture-of-experts routing except the all-to-all helper).
    - Times are roofline-style sums of compute, memory and communication with explicit overlap factors; no
      congestion, stragglers or failures.
"""

import math
from dataclasses import dataclass, field

import course_path

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

import gpu as gpu11  # noqa: E402
import workloads as wl  # noqa: E402

# =====================================================================================================================
# 1. GPU generations (dense peaks, published unless marked)
# =====================================================================================================================


@dataclass(frozen=True)
class GPU:
    """
    One GPU generation.

    [Fields] peak: dict format -> dense FLOP/s ("fp32" = CUDA cores; "tf32"/"fp16"/"bf16"/"fp8"/"fp4" = tensor
        cores where they exist); hbm_bw (B/s), hbm (bytes), tdp_w, die_mm2 (total silicon of the GPU), node (process)
    """
    name: str
    year: int
    node: str
    peak: dict
    hbm_bw: float
    hbm: float
    tdp_w: float
    die_mm2: float
    notes: str = ""

    def best(self):
        """(format, FLOP/s) of the fastest dense format."""
        f = max(self.peak, key=self.peak.get)
        return f, self.peak[f]


K40 = GPU("K40", 2013, "28 nm", {"fp32": 4.29e12}, 288e9, 12e9, 235, 561, "Kepler; no fast FP16")
P100 = GPU("P100", 2016, "16 nm", {"fp32": 10.6e12, "fp16": 21.2e12}, 732e9, 16e9, 300, 610, "Pascal; FP16 at 2x FP32")
V100 = GPU("V100", 2017, "12 nm", {"fp32": 15.7e12, "fp16": 125e12}, 900e9, 32e9, 300, 815, "Volta; 1st tensor cores")
A100 = GPU("A100", 2020, "7 nm", {"fp32": 19.5e12, "tf32": 156e12, "bf16": 312e12}, 2.039e12, 80e9,
           400, 826, "Ampere; BF16, TF32, 2:4 sparsity; INT8 (624 TOPS) not listed: floating-point formats only")
H100 = GPU("H100", 2022, "4N", {"fp32": 67e12, "tf32": 494.7e12, "bf16": 989.4e12, "fp8": 1978.9e12}, 3.35e12, 80e9,
           700, 814, "Hopper; FP8, TMA, clusters")
B200 = GPU("B200", 2024, "4NP (2 dies)", {"fp32": 80e12, "tf32": 1.1e15, "bf16": 2.25e15, "fp8": 4.5e15,
                                          "fp4": 9e15}, 8e12, 192e9, 1000, 1600,
           "Blackwell; FP4/NVFP4, 2 dies; die area ASSUMED 2 x 800 mm^2")
GB200 = GPU("GB200 (per GPU)", 2024, "4NP (2 dies)", {"fp32": 80e12, "tf32": 1.25e15, "bf16": 2.5e15, "fp8": 5e15,
                                                     "fp4": 10e15}, 8e12, 186e9, 1200, 1600,
            "NVL72 rack / 72 (published); power per GPU ASSUMED")
GPUS = [K40, P100, V100, A100, H100, B200]

# Dally, Hot Chips 2023: single-chip inference performance, ~1000x over ~10 years
DALLY_2023 = {"number representation": 16.0, "complex instructions": 12.5, "process": 2.5, "sparsity": 2.0}


def decompose(old, new):
    """
    Split the gain of the best dense format between two GPUs into three multiplicative factors:
        format        : new best format vs the new GPU's BF16/FP16 tensor rate (narrower numbers)
        tensor cores  : the new GPU's 16-bit tensor rate vs its own FP32 CUDA-core rate (specialized instructions)
        FP32 engine   : the new FP32 rate vs the old best rate (process, area, power, clocks, more cores)
    [Returns] dict of factors and their product (= the total gain), plus "power", "area", "bandwidth" ratios
    [Edge cases] Assumes the old GPU's best format is FP32 (true for K40); otherwise the "FP32 engine" factor mixes
        in the old GPU's own format and tensor-core gains.
    """
    f_new, p_new = new.best()
    half = new.peak.get("bf16", new.peak.get("fp16"))
    _, p_old = old.best()
    out = {"format": p_new / half, "tensor cores": half / new.peak["fp32"], "FP32 engine": new.peak["fp32"] / p_old}
    out["total"] = p_new / p_old
    out["power"] = new.tdp_w / old.tdp_w
    out["area"] = new.die_mm2 / old.die_mm2
    out["bandwidth"] = new.hbm_bw / old.hbm_bw
    return out


# =====================================================================================================================
# 2. Fabrics and collectives
# =====================================================================================================================


@dataclass(frozen=True)
class Fabric:
    """
    A link technology as seen by one GPU: bw = bytes/s per direction per GPU; alpha = latency of one algorithm step;
    in_switch = the switches can reduce (NVLink SHARP), so an all-reduce sends and receives each byte once.
    """
    name: str
    bw: float
    alpha: float
    in_switch: bool = False


NVLINK_H100 = Fabric("NVLink 4 (H100)", 450e9, 1e-6, True)      # 900 GB/s bidirectional per GPU (published)
NVLINK_B200 = Fabric("NVLink 5 (Blackwell)", 900e9, 1e-6, True)  # 1.8 TB/s bidirectional per GPU (published)
IB_400G = Fabric("InfiniBand 400 Gb/s per GPU", 50e9, 5e-6)      # ConnectX-7 class NIC per GPU; latency ASSUMED


def allreduce_s(nbytes, p, fabric, algo="auto"):
    """
    All-reduce of nbytes over p GPUs on one fabric.

    [Idea] ring: 2 (p - 1) steps of nbytes / p each -> 2 (p - 1)/p n / bw + 2 (p - 1) alpha. In-switch (NVLS): every
        GPU sends its n bytes to the switch, which reduces and multicasts -> n / bw + 2 alpha. "auto" picks in-switch
        when the fabric has it.
    [Edge cases] p = 1 costs 0.
    """
    if p <= 1:
        return 0.0
    if algo == "auto":
        algo = "switch" if fabric.in_switch else "ring"
    if algo == "switch":
        return nbytes / fabric.bw + 2 * fabric.alpha
    return 2 * (p - 1) / p * nbytes / fabric.bw + 2 * (p - 1) * fabric.alpha


def hier_allreduce_s(nbytes, p_in, p_out, inner, outer):
    """
    Hierarchical all-reduce: reduce-scatter inside each domain of p_in GPUs, all-reduce of the 1/p_in shards across
    p_out domains, all-gather inside. Inside, reduce-scatter + all-gather cost about one all-reduce.
    """
    return allreduce_s(nbytes, p_in, inner) + allreduce_s(nbytes / p_in, p_out, outer, algo="ring")


def alltoall_s(nbytes_per_gpu, p, fabric):
    """All-to-all: each GPU sends (p - 1)/p of its nbytes to the others (direct, one step per peer pipelined)."""
    if p <= 1:
        return 0.0
    return (p - 1) / p * nbytes_per_gpu / fabric.bw + fabric.alpha * math.log2(p)


# =====================================================================================================================
# 3. Domains and serving
# =====================================================================================================================


@dataclass(frozen=True)
class Domain:
    """A scale-up domain: `size` GPUs of one kind joined by `fabric`; domains joined by `network`."""
    name: str
    gpu: GPU
    size: int
    fabric: Fabric
    network: Fabric = IB_400G


HGX_H100 = Domain("HGX H100 (8 GPUs, NVLink)", H100, 8, NVLINK_H100)
HGX_B200 = Domain("HGX B200 (8 GPUs, NVLink)", B200, 8, NVLINK_B200)
NVL72 = Domain("GB200 NVL72 (72 GPUs, NVLink)", GB200, 72, NVLINK_B200)


def tp_allreduce_s(nbytes, tp, dom):
    """All-reduce over a TP group: inside the domain if it fits, otherwise hierarchical over the network."""
    if tp <= dom.size:
        return allreduce_s(nbytes, tp, dom.fabric)
    return hier_allreduce_s(nbytes, dom.size, math.ceil(tp / dom.size), dom.fabric, dom.network)


def decode_step(cfg, dom, tp, pp=1, batch=1, ctx=4096, w_bytes=2, kv_bytes=2, mem_eff=0.85):
    """
    One decode step of a dense Llama-style model on tp x pp GPUs.

    [Idea] Each layer streams its weights (1/tp of them per GPU) and the batch's KV cache from HBM at mem_eff of the
        peak bandwidth, then joins its tensor-parallel shards with two all-reduces of batch x d_model activations.
        Pipeline stages run one after another for a token: the step is the sum over all layers, plus a
        point-to-point hop between stages (over the network when a stage boundary leaves the domain).
    [Returns] dict: seconds, hbm_s, comm_s, hop_s, tokens_per_s_user, tokens_per_s_gpu, fits, bytes_per_gpu
    [Edge cases] fits = False when weights + KV exceed 90% of the GPUs' HBM; the times are still returned. The KV
        cache splits over at most n_kv_heads GPUs: with tp > n_kv_heads, KV heads are replicated (each GPU still
        reads one KV head's cache for its query heads).
    """
    L, d = cfg.n_layers, cfg.d_model
    w_layer = cfg.layer_params() * w_bytes
    kv_layer = batch * ctx * 2 * cfg.n_kv_heads * cfg.head_dim * kv_bytes
    kv_split = min(tp, cfg.n_kv_heads)
    hbm = L * (w_layer / tp + kv_layer / kv_split) / (dom.gpu.hbm_bw * mem_eff)
    comm = L * 2 * tp_allreduce_s(batch * d * 2, tp, dom)
    gpus = tp * pp
    crosses = pp > 1 and gpus > dom.size
    hop = (pp - 1) * ((dom.network.alpha if crosses else dom.fabric.alpha) + batch * d * 2 / dom.fabric.bw)
    t = hbm + comm + hop
    per_gpu = cfg.params() * w_bytes / gpus + L * kv_layer / (kv_split * pp)
    return {"seconds": t, "hbm_s": hbm, "comm_s": comm, "hop_s": hop, "tokens_per_s_user": 1 / t,
            "tokens_per_s_gpu": batch / t / gpus, "fits": per_gpu <= 0.9 * dom.gpu.hbm, "bytes_per_gpu": per_gpu}


# =====================================================================================================================
# 4. Training with 3D parallelism
# =====================================================================================================================

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)


def gemm_efficiency(M, N, K):
    """Efficiency (fraction of peak) of one BF16 GEMM on Lecture 11's H100 model (best of a few tile shapes)."""
    best = 0.0
    for BM, BN, cl in ((128, 256, (2, 1)), (128, 128, (1, 1)), (256, 128, (1, 2))):
        r = gpu11.gemm_time(M, N, K, BM, BN, 64, 4, cl)
        best = max(best, r.efficiency)
    return best


@dataclass
class TrainConfig:
    """
    [Fields] tp, pp, dp: parallel degrees; micro: sequences per microbatch; seq: sequence length; batch_tokens: global
        batch; interleave: virtual pipeline stages per GPU (interleaved 1F1B divides the bubble by it and multiplies
        the stage-to-stage transfers); zero: shard optimizer states over dp (ZeRO-1); dp_overlap / tp_overlap: fractions of that
        communication hidden behind compute (ASSUMED); other: extra time for non-GEMM work (norms, softmax,
        optimizer step...) as a fraction of GEMM time (ASSUMED 0.15)
    """
    tp: int = 8
    pp: int = 16
    dp: int = 128
    micro: int = 1
    seq: int = 8192
    batch_tokens: float = 16e6
    interleave: int = 1
    zero: bool = True
    dp_overlap: float = 0.8
    tp_overlap: float = 0.0
    other: float = 0.15
    extra: dict = field(default_factory=dict)


def train_step(cfg, dom, tc, dtype="bf16"):
    """
    One training step of a dense transformer with tensor x pipeline x data parallelism.

    [Idea]
        model FLOPs per token  = 6 x params + 12 x layers x seq x d (attention scores, causal halves 6 of the 12)
        microbatches per step  m = batch_tokens / (dp x micro x seq)
        GEMM time              = model FLOPs / (GPUs x peak x GEMM efficiency (Lecture 11's model on the layer's
                                 GEMM shapes)) x (1 + other)
        pipeline bubble        = (pp - 1) / (interleave x m) of the compute time (1F1B, optionally interleaved)
        TP communication       = 4 all-reduces per layer per microbatch (2 forward, 2 backward) of micro x seq x d
                                 BF16 activations, over NVLink when tp fits the domain
        PP communication       = 2 x (pp - 1) activation transfers per microbatch, over the network if stages span
                                 domains
        DP communication       = reduce-scatter + all-gather of the GPU's gradient shard (2 x params/(tp pp) bytes),
                                 hierarchical, dp_overlap of it hidden behind the backward pass
    [Returns] dict with seconds, parts, mfu (model FLOPs / (time x GPUs x peak)), memory per GPU (bytes) and fits
    """
    gpus = tc.tp * tc.pp * tc.dp
    peak = dom.gpu.peak[dtype]
    tokens = tc.batch_tokens
    flops_tok = 6 * cfg.params() + 12 * cfg.n_layers * tc.seq * cfg.d_model / 2
    flops = flops_tok * tokens
    m = max(1, round(tokens / (tc.dp * tc.micro * tc.seq)))
    Mtok = tc.micro * tc.seq
    shapes = [(Mtok, (cfg.n_heads + 2 * cfg.n_kv_heads) * cfg.head_dim // tc.tp, cfg.d_model),
              (Mtok, cfg.d_model, cfg.n_heads * cfg.head_dim // tc.tp),
              (Mtok, 2 * cfg.d_ff // tc.tp, cfg.d_model), (Mtok, cfg.d_model, cfg.d_ff // tc.tp)]
    weights = [n * k for _, n, k in shapes]
    eff = sum(w * gemm_efficiency(*s) for w, s in zip(weights, shapes)) / sum(weights)
    compute = flops / (gpus * peak * eff) * (1 + tc.other)
    bubble = compute * (tc.pp - 1) / (tc.interleave * m)
    act = Mtok * cfg.d_model * 2
    layers_per_gpu = cfg.n_layers / tc.pp
    tp_comm = m * layers_per_gpu * 4 * tp_allreduce_s(act, tc.tp, dom) * (1 - tc.tp_overlap)
    stage_gpus = tc.tp
    crosses = tc.pp > 1 and stage_gpus * tc.pp > dom.size
    link = dom.network if crosses else dom.fabric
    pp_comm = m * 2 * tc.interleave * (link.alpha + act / tc.tp / link.bw) if tc.pp > 1 else 0.0
    grad = 2 * cfg.params() * 2 / (tc.tp * tc.pp)          # reduce-scatter + all-gather of BF16 grads/params
    in_dom = max(1, dom.size // (tc.tp * tc.pp)) if tc.tp * tc.pp < dom.size else 1
    dp_full = hier_allreduce_s(grad / 2, in_dom, math.ceil(tc.dp / in_dom), dom.fabric, dom.network)
    dp_comm = dp_full * (1 - tc.dp_overlap)
    t = compute + bubble + tp_comm + pp_comm + dp_comm
    # memory per GPU: BF16 weights + BF16 grads + FP32 master and two Adam moments (12 B), optimizer sharded by ZeRO
    shard = cfg.params() / (tc.tp * tc.pp)
    states = shard * (2 + 2 + 12 / (tc.dp if tc.zero else 1))
    acts = 34 * tc.seq * tc.micro * cfg.d_model / tc.tp * layers_per_gpu * min(tc.pp, m)
    mem = states + acts
    return {"seconds": t, "compute": compute, "bubble": bubble, "tp_comm": tp_comm, "pp_comm": pp_comm,
            "dp_comm": dp_comm, "dp_full": dp_full, "mfu": flops / (t * gpus * peak), "gemm_eff": eff,
            "microbatches": m, "gpus": gpus, "mem": mem, "fits": mem <= 0.9 * dom.gpu.hbm, "flops": flops}


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

def _self_test():
    d = decompose(K40, B200)
    assert abs(d["format"] * d["tensor cores"] * d["FP32 engine"] - d["total"]) / d["total"] < 1e-12
    assert abs(math.prod(DALLY_2023.values()) - 1000) < 1e-9
    assert abs(allreduce_s(1e9, 4, IB_400G, "ring") - (1.5e9 / 50e9 + 6 * 5e-6)) < 1e-12
    assert allreduce_s(1e9, 72, NVLINK_B200) < allreduce_s(1e9, 72, NVLINK_B200, "ring")
    s = decode_step(LLAMA31_405B, NVL72, tp=72)
    assert s["fits"] and s["tokens_per_s_user"] > decode_step(LLAMA31_405B, NVL72, tp=8, pp=1)["tokens_per_s_user"]
    t = train_step(LLAMA31_405B, HGX_H100, TrainConfig())
    assert 0.2 < t["mfu"] < 0.7 and t["gpus"] == 16384
    print("cluster.py self-test passed")


if __name__ == "__main__":
    _self_test()
