"""
gpu.py -- a GPU in miniature: SIMT warps and divergence, memory coalescing and shared-memory banks, a cycle-level
warp scheduler that hides memory latency, an occupancy calculator, the economics of tensor-core instructions, and a
GEMM tiling cost model of a whole H100
=====================================================================================================================

[Why we need it]
    A GPU is the "repurposed and augmented" accelerator of this course: a graphics processor whose thousands of
    simple lanes were opened to general programs (CUDA, 2007) and then augmented with matrix units (tensor cores,
    2017). To reason about why a kernel reaches 10% or 90% of an H100's peak we need a model of its parts:

    1. SIMT execution. Threads are grouped into WARPS of 32 that share one instruction stream. A branch on which the
       lanes disagree runs both paths with some lanes masked off (divergence). Memory accesses of the 32 lanes are
       merged ("coalesced") into 32-byte sectors; scattered addresses waste bandwidth.
    2. Latency hiding. A global-memory load takes hundreds of cycles. Instead of caches big enough to avoid misses or
       out-of-order cores, a GPU keeps MANY warps resident and switches to another warp every cycle. How many warps
       are needed follows from Little's law (Lecture 7): data in flight = latency x bandwidth.
    3. Occupancy. How many warps fit on a streaming multiprocessor (SM) is limited by registers, shared memory, and
       hardware slots -- a resource-allocation calculation every CUDA programmer meets.
    4. Tensor cores. One matrix instruction performs thousands of multiply-accumulates, so the cost of fetching,
       decoding and scheduling an instruction and of moving operands through the register file is amortized
       (Lecture 1's "instruction overhead" argument).
    5. A GEMM on the whole GPU: thread-block tiles, waves over 132 SMs, software pipelining of asynchronous copies,
       thread-block clusters that multicast tiles -- and the quantization effects that make efficiency depend on
       the matrix shape.

[Main pieces]
    divergence_efficiency, loop_divergence      : SIMT branch and loop divergence
    coalesce, warp_addresses, smem_conflicts    : global-memory sectors per warp access; shared-memory bank conflicts
    SMConfig, Kernel, simulate_sm               : cycle-level warp scheduling on one SM (latency hiding)
    SMLimits, H100_LIMITS, A100_LIMITS, occupancy : the CUDA occupancy calculation
    SM_COUNTS, per_sm_rates, MMA_INSTRUCTIONS, instruction_energy : tensor cores vs CUDA cores
    GPUModel, H100_GPU, gemm_time, best_gemm    : a GEMM tiling cost model of a whole GPU (an "autotuner" included)

[Sources and assumptions]  (every number below carries its source or the word ASSUMED)
    - SM counts, clocks and peak rates: NVIDIA V100/A100/H100 datasheets and architecture whitepapers, via
      Lecture 1's hw_specs.py.
    - Occupancy limits: CUDA C++ Programming Guide, "Technical Specifications per Compute Capability" (8.0, 9.0).
    - Memory latency (600 cycles), the L2 bandwidth (A100's published 5,120 B/clk applied at H100's clock), the
      per-SM bandwidth cap and the launch overhead are ASSUMED: NVIDIA does not publish them; microbenchmark papers
      report values of the same order. Every script that depends on them says so and shows a sensitivity check.
    - Energies come from Lecture 1's 45 nm Horowitz model: relative, not absolute, numbers for a modern GPU.

[Edge cases]
    - Everything is a model. Real GPUs add caches with hit rates, clock throttling under power limits, instruction
      issue constraints (dual issue, register bank conflicts) and many details NVIDIA does not document.
"""

import math
from dataclasses import dataclass, field

import course_path

course_path.use("lecture01")

import energy_model as em  # noqa: E402
from hw_specs import A100, H100, V100  # noqa: E402

WARP = 32                       # threads per warp on every NVIDIA GPU since 2006


# =====================================================================================================================
# 1. SIMT: divergence
# =====================================================================================================================

def divergence_efficiency(cond, then_cost, else_cost):
    """
    Cost of `if cond: <then> else: <else>` executed by warps of 32 threads.

    [Idea] All lanes of a warp follow one instruction stream. If every lane of a warp takes the same side, the warp
        executes only that side. If the lanes disagree, the warp executes BOTH sides one after the other, with the
        lanes of the other side masked off (they idle). Lane efficiency = useful lane-cycles / issued lane-cycles.
    [Args] cond: sequence of booleans, one per thread (length a multiple of 32 is typical; a partial last warp is
        allowed); then_cost, else_cost: instruction cycles of each side
    [Returns] dict(cycles = total warp-cycles, ideal = cycles if no warp diverged (each warp paying only for what its
        lanes need, averaged lane by lane), lane_eff = useful lane-cycles / (32 x cycles), divergent_warps)
    [Edge cases] A partial last warp still occupies a whole warp slot: its missing lanes count as idle.
    [Hardware link] Since Volta each thread has its own program counter ("independent thread scheduling"), which
        helps with deadlock-free synchronization, but divergent paths still execute one at a time.
    """
    cond = [bool(c) for c in cond]
    cycles = useful = div = 0
    for w0 in range(0, len(cond), WARP):
        lanes = cond[w0:w0 + WARP]
        n_then = sum(lanes)
        n_else = len(lanes) - n_then
        cost = (then_cost if n_then else 0) + (else_cost if n_else else 0)
        div += n_then > 0 and n_else > 0
        cycles += cost
        useful += n_then * then_cost + n_else * else_cost
    return {"cycles": cycles, "lane_eff": useful / (WARP * cycles) if cycles else 1.0, "divergent_warps": div,
            "warps": math.ceil(len(cond) / WARP)}


def loop_divergence(trips, body_cost=1):
    """
    A loop whose trip count differs per thread: a warp keeps looping until its LONGEST thread is done.

    [Args] trips: per-thread trip counts; body_cost: cycles per iteration
    [Returns] dict(cycles, lane_eff = mean trip / max trip averaged over warps)
    [Edge cases] All-zero trips cost nothing (lane_eff reported as 1).
    """
    cycles = useful = 0
    for w0 in range(0, len(trips), WARP):
        t = trips[w0:w0 + WARP]
        cycles += max(t) * body_cost
        useful += sum(t) * body_cost
    return {"cycles": cycles, "lane_eff": useful / (WARP * cycles) if cycles else 1.0}


# =====================================================================================================================
# 2. Memory coalescing and shared-memory banks
# =====================================================================================================================

def coalesce(addresses, elem_bytes=4, sector=32):
    """
    How many 32-byte DRAM/L2 sectors one warp-wide load touches.

    [Idea] The load/store unit merges the 32 lanes' requests: every distinct 32-byte sector touched is fetched once.
        Consecutive 4-byte elements -> 4 sectors (128 B) for 128 useful bytes (100%). Stride-2 -> 8 sectors for
        the same useful bytes (50%). Random addresses -> up to 32 sectors (12.5% for 4-byte elements).
    [Args] addresses: byte addresses of the active lanes; elem_bytes: bytes each lane needs; sector: 32
    [Returns] dict(sectors, bytes_moved, useful, efficiency)
    [Edge cases] An element straddling a sector boundary touches two sectors (misaligned access). Duplicate addresses
        are served once (a broadcast), so their efficiency can exceed what the lane count suggests -- we count the
        useful bytes as the DISTINCT bytes requested.
    [Python tip] A set keeps only distinct values: len(set(...)) counts distinct sectors.
    """
    sectors = set()
    wanted = set()
    for a in addresses:
        for b in range(a, a + elem_bytes):
            wanted.add(b)
        sectors.add(a // sector)
        sectors.add((a + elem_bytes - 1) // sector)
    moved = len(sectors) * sector
    return {"sectors": len(sectors), "bytes_moved": moved, "useful": len(wanted), "efficiency": len(wanted) / moved}


def warp_addresses(pattern, elem_bytes=4, stride=1, offset=0, seed=0, struct_fields=1, span=1 << 24):
    """
    Byte addresses of the 32 lanes of one warp for a few classic access patterns.

    [Args] pattern: "unit" (lane i reads element i), "stride" (element i*stride), "offset" (element i + offset: a
        misaligned start), "random" (random elements in a span of `span` bytes), "aos" (array of structs with
        `struct_fields` 4-byte fields: lane i reads field 0 of struct i), "broadcast" (all lanes read element 0)
    [Returns] list of 32 byte addresses
    [Edge cases] The random pattern uses its own seeded generator, so the result is reproducible.
    """
    import random
    if pattern == "unit":
        return [i * elem_bytes for i in range(WARP)]
    if pattern == "stride":
        return [i * stride * elem_bytes for i in range(WARP)]
    if pattern == "offset":
        return [(i + offset) * elem_bytes for i in range(WARP)]
    if pattern == "aos":
        return [i * struct_fields * 4 for i in range(WARP)]
    if pattern == "broadcast":
        return [0] * WARP
    if pattern == "random":
        rng = random.Random(seed)
        return [rng.randrange(0, span // elem_bytes) * elem_bytes for _ in range(WARP)]
    raise ValueError(f"unknown pattern {pattern!r}")


def smem_conflicts(word_addresses, banks=32):
    """
    Shared-memory bank-conflict degree of one warp access (4-byte words, 32 banks).

    [Idea] Shared memory is 32 banks, each 4 bytes wide; word w lives in bank w mod 32. A warp access takes as many
        passes as the largest number of DISTINCT words requested from one bank (lanes reading the same word get a
        broadcast). This is Lecture 7's banked-SRAM model with the GPU's numbers: a column walk of a 32 x 32
        float tile hits one bank 32 times; padding each row to 33 words spreads it over all banks (gcd rule).
    [Args] word_addresses: 4-byte word indices, one per lane
    [Returns] int, passes (1 = conflict-free)
    """
    per_bank = {}
    for w in word_addresses:
        per_bank.setdefault(w % banks, set()).add(w)
    return max(len(s) for s in per_bank.values())


# =====================================================================================================================
# 3. A cycle-level SM: warp scheduling and latency hiding
# =====================================================================================================================

@dataclass(frozen=True)
class SMConfig:
    """
    One streaming multiprocessor, as far as instruction issue and memory latency are concerned.

    [Fields]
        schedulers     : warp schedulers (sub-cores); each issues at most one instruction per cycle (Volta and later: 4)
        max_warps      : resident-warp limit of the SM (64 on A100/H100)
        alu_latency    : cycles until a dependent arithmetic instruction may issue (4 for FFMA since Volta)
        mem_latency    : cycles from a global load's issue to its data -- ASSUMED 600 (several hundred cycles is the
                         order microbenchmarks report for DRAM accesses)
        mem_bytes_per_cycle : this SM's share of DRAM bandwidth: 3.35 TB/s / 132 SMs / 1.83 GHz = 13.9 B/cycle
        policy         : "lrr" (loose round-robin) or "gto" (greedy-then-oldest) warp selection
    """
    schedulers: int = 4
    max_warps: int = 64
    alu_latency: int = 4
    mem_latency: int = 600
    mem_bytes_per_cycle: float = H100.mem_bw / 132 / (H100.clock_ghz * 1e9)
    policy: str = "lrr"


@dataclass(frozen=True)
class Kernel:
    """
    A synthetic kernel: every warp runs `iters` iterations of
        `loads` independent global loads of `load_bytes` each (128 B = 32 lanes x 4 B; 512 B = 32 lanes x 16 B),
        then `alu` arithmetic instructions arranged in `ilp` independent dependence chains; the first instruction
        of each chain needs the data of all the loads of the iteration.
    [Hardware link] loads > 1 or ilp > 1 is instruction-level parallelism INSIDE a warp; more warps is thread-level
        parallelism. Both put independent work in flight -- Volkov's "better performance at lower occupancy"
        (GTC 2010) is the observation that one can replace the other.
    """
    iters: int = 16
    loads: int = 1
    alu: int = 8
    ilp: int = 1
    load_bytes: int = 128


def _iteration_program(k):
    """
    The instructions of one iteration as (kind, deps) with deps = indices of earlier instructions in the iteration.

    [Edge cases] alu = 0 gives a pure streaming kernel (loads only); loads = 0 a pure compute kernel.
    """
    prog = [("ld", ()) for _ in range(k.loads)]
    load_ids = tuple(range(k.loads))
    last_in_chain = {}
    for j in range(k.alu):
        chain = j % max(1, k.ilp)
        deps = (last_in_chain[chain],) if chain in last_in_chain else load_ids
        prog.append(("alu", deps))
        last_in_chain[chain] = len(prog) - 1
    return prog


def simulate_sm(kernel, warps, cfg=SMConfig()):
    """
    Cycle-level simulation of `warps` resident warps running `kernel` on one SM.

    [Idea] Warp w belongs to scheduler w mod cfg.schedulers. Every cycle each scheduler issues at most one
        instruction: from its warps whose NEXT instruction (warps issue in order) has all its inputs ready, it picks
        one by the policy. An ALU result is ready alu_latency cycles later. A load's data arrives after
        mem_latency cycles, but the SM's memory pipe returns at most mem_bytes_per_cycle, so loads queue behind
        each other when bandwidth is the limit:
            done = max(issue + latency, previous_done + bytes / bandwidth)
        The simulation jumps over cycles in which no scheduler can issue (event-driven), so long stalls cost
        nothing to simulate.
    [Args] kernel: Kernel; warps: number of resident warps (1 .. cfg.max_warps); cfg: SMConfig
    [Returns] dict(cycles, alu_util = ALU issues / (cycles x schedulers), issue_util = all issues / (...),
        mem_util = bytes / (cycles x bandwidth), bytes, warp_finish = completion cycle of each warp)
    [Edge cases] warps > cfg.max_warps raises ValueError (the hardware cannot hold them).
    """
    if not 1 <= warps <= cfg.max_warps:
        raise ValueError(f"warps must be in 1..{cfg.max_warps}")
    prog = _iteration_program(kernel)
    n_instr = len(prog) * kernel.iters
    # per-warp state: next instruction index, issue time of the previous instruction, completion times
    pos = [0] * warps
    last_issue = [-1] * warps
    done = [[0.0] * len(prog) for _ in range(warps)]     # completion times of the current iteration's instructions
    sched_warps = [[w for w in range(warps) if w % cfg.schedulers == s] for s in range(cfg.schedulers)]
    rr = [0] * cfg.schedulers                             # round-robin pointer per scheduler
    greedy = [None] * cfg.schedulers                      # last warp issued per scheduler (GTO policy)
    mem_done = 0.0
    t = 0
    alu_issues = issues = 0
    bytes_moved = 0
    finished = 0
    finish_time = 0.0
    warp_finish = [0.0] * warps

    def ready_time(w):
        """Earliest cycle at which warp w's next instruction may issue (in order, after its inputs are ready)."""
        i = pos[w] % len(prog)
        kind, deps = prog[i]
        r = last_issue[w] + 1
        for d in deps:
            r = max(r, done[w][d])
        return r

    while finished < warps:
        next_t = math.inf
        for s in range(cfg.schedulers):
            cands = [w for w in sched_warps[s] if pos[w] < n_instr]
            if not cands:
                continue
            rts = {w: ready_time(w) for w in cands}
            ready = [w for w in cands if rts[w] <= t]
            if not ready:
                next_t = min(next_t, min(rts.values()))
                continue
            if cfg.policy == "gto":    # greedy: keep issuing from the same warp while it can; else the oldest
                w = greedy[s] if greedy[s] in ready else min(ready)
                greedy[s] = w
            else:   # loose round-robin: the first ready warp after the last one issued
                order = sched_warps[s]
                start = rr[s]
                w = next(order[(start + j) % len(order)] for j in range(len(order))
                         if order[(start + j) % len(order)] in ready)
                rr[s] = (order.index(w) + 1) % len(order)
            i = pos[w] % len(prog)
            kind, _ = prog[i]
            if kind == "ld":
                mem_done = max(t + cfg.mem_latency, mem_done + kernel.load_bytes / cfg.mem_bytes_per_cycle)
                done[w][i] = mem_done
                bytes_moved += kernel.load_bytes
            else:
                done[w][i] = t + cfg.alu_latency
                alu_issues += 1
            issues += 1
            last_issue[w] = t
            pos[w] += 1
            if pos[w] == n_instr:
                finished += 1
                warp_finish[w] = max(done[w])
                finish_time = max(finish_time, warp_finish[w])
            next_t = min(next_t, t + 1)
        if next_t is math.inf:
            break
        t = max(t + 1, math.ceil(next_t)) if next_t > t else t + 1
    cycles = max(finish_time, t)
    return {"cycles": cycles,
            "alu_util": alu_issues / (cycles * cfg.schedulers),
            "issue_util": issues / (cycles * cfg.schedulers),
            "mem_util": bytes_moved / (cycles * cfg.mem_bytes_per_cycle),
            "bytes": bytes_moved,
            "warp_finish": warp_finish}


def littles_law_warps(kernel, cfg=SMConfig()):
    """
    Warps needed to saturate (a) the memory pipe and (b) the schedulers, from Little's law.

    [Idea] (a) Bytes in flight must equal latency x bandwidth; one warp has at most `loads` loads of `load_bytes`
        in flight per iteration: warps_mem = latency x B / (loads x load_bytes).
        (b) Each scheduler issues one instruction per cycle; a dependence chain allows one instruction per
        alu_latency cycles, so each scheduler needs alu_latency / ilp warps: warps_alu = schedulers x alu_latency
        / ilp.
    [Returns] (warps_mem, warps_alu) as floats
    [Edge cases] A kernel without loads (or without ALU work) returns 0 for that bound.
    """
    wm = cfg.mem_latency * cfg.mem_bytes_per_cycle / (kernel.loads * kernel.load_bytes) if kernel.loads else 0.0
    wa = cfg.schedulers * cfg.alu_latency / max(1, kernel.ilp) if kernel.alu else 0.0
    return wm, wa


# =====================================================================================================================
# 4. Occupancy
# =====================================================================================================================

@dataclass(frozen=True)
class SMLimits:
    """
    Per-SM resource limits of one compute capability (CUDA C++ Programming Guide, technical specifications).

    [Fields] registers per SM (32-bit), allocation granularity of registers (per warp), shared memory per SM and per
        block (bytes), its allocation granularity, the shared memory the runtime reserves per block, and the hardware
        limits on warps, blocks and threads.
    """
    name: str
    max_warps: int = 64
    max_blocks: int = 32
    max_threads_per_block: int = 1024
    regs_per_sm: int = 65536
    max_regs_per_thread: int = 255
    reg_alloc_unit: int = 256          # registers are allocated per warp in units of 256
    smem_per_sm: int = 228 * 1024
    max_smem_per_block: int = 227 * 1024
    smem_alloc_unit: int = 128
    smem_reserved_per_block: int = 1024


H100_LIMITS = SMLimits("H100 (cc 9.0)")
A100_LIMITS = SMLimits("A100 (cc 8.0)", smem_per_sm=164 * 1024, max_smem_per_block=163 * 1024)


def occupancy(limits, threads_per_block, regs_per_thread, smem_per_block):
    """
    How many thread blocks of a kernel fit on one SM, which resource limits them, and the resulting occupancy.

    [Idea] A block is resident only if ALL its resources are available. The number of resident blocks is the minimum
        over four limits:
            warps     : max_warps // warps_per_block
            blocks    : max_blocks
            registers : regs_per_sm // (warps_per_block x round_up(regs_per_thread x 32, 256))
            shared mem: smem_per_sm // round_up(smem_per_block + reserved, 128)
        Occupancy = resident warps / max_warps.
    [Args] limits: SMLimits; threads_per_block; regs_per_thread; smem_per_block (bytes, dynamic + static)
    [Returns] dict(blocks, warps, occupancy, limiter, per_limit = {name: blocks})
    [Edge cases] A block that can never fit (too many threads, registers or shared memory) returns blocks = 0 and
        limiter naming the violated limit -- the kernel would fail to launch.
    """
    wpb = math.ceil(threads_per_block / WARP)
    if threads_per_block > limits.max_threads_per_block:
        return {"blocks": 0, "warps": 0, "occupancy": 0.0, "limiter": "threads per block", "per_limit": {}}
    if regs_per_thread > limits.max_regs_per_thread:
        return {"blocks": 0, "warps": 0, "occupancy": 0.0, "limiter": "registers per thread", "per_limit": {}}
    if smem_per_block > limits.max_smem_per_block:
        return {"blocks": 0, "warps": 0, "occupancy": 0.0, "limiter": "shared memory per block", "per_limit": {}}
    regs_per_warp = math.ceil(regs_per_thread * WARP / limits.reg_alloc_unit) * limits.reg_alloc_unit
    smem = math.ceil((smem_per_block + limits.smem_reserved_per_block) / limits.smem_alloc_unit) * \
        limits.smem_alloc_unit
    per = {
        "warps": limits.max_warps // wpb,
        "blocks": limits.max_blocks,
        "registers": limits.regs_per_sm // (wpb * regs_per_warp) if regs_per_thread else limits.max_blocks,
        "shared memory": limits.smem_per_sm // smem if smem_per_block else limits.max_blocks,
    }
    blocks = min(per.values())
    limiter = " & ".join(k for k, v in per.items() if v == blocks)     # several resources can tie
    warps = blocks * wpb
    return {"blocks": blocks, "warps": warps, "occupancy": warps / limits.max_warps, "limiter": limiter,
            "per_limit": per}


# =====================================================================================================================
# 5. Tensor cores vs CUDA cores
# =====================================================================================================================

# SM counts (NVIDIA architecture whitepapers): V100 80, A100 108, H100 SXM5 132 SMs.
SM_COUNTS = {"V100": 80, "A100": 108, "H100": 132}
# Architectural per-SM counts (whitepapers): FP32 lanes per SM, dense fp16 tensor-core FMAs per clock per SM.
FP32_LANES = {"V100": 64, "A100": 64, "H100": 128}
TC_FMA_PER_CLK = {"V100": 512, "A100": 1024, "H100": 2048}


def per_sm_rates(machine):
    """
    Datasheet peaks turned into FLOP per clock per SM: peak / (SMs x clock).

    [Returns] dict dtype -> FLOP per cycle per SM
    [Edge cases] The H100 datasheet's FP32 figure (67 TFLOPS) implies a higher clock (1.98 GHz) than its tensor
        figure (1.83 GHz); dividing both by 1.83 GHz makes FP32 look like 277 FLOP/clk instead of the architectural
        256 (128 lanes x 2). The scripts print both.
    """
    sms = SM_COUNTS[machine.name]
    clk = machine.clock_ghz * 1e9
    return {dt: v / (sms * clk) for dt, v in machine.peak_ops.items()}


@dataclass(frozen=True)
class MatrixInstr:
    """
    One instruction family, described by its multiply-accumulates and the operand bytes it moves.

    [Fields] fmas: multiply-accumulates per instruction (per warp, or per warpgroup of 4 warps for wgmma);
        rf_bytes: register-file bytes read + written; smem_bytes: shared-memory bytes read; mac: Lecture 1 MAC
        recipe ("fp32" or "fp16" = fp16 multiply, fp32 accumulate)
    """
    name: str
    fmas: int
    rf_bytes: float
    smem_bytes: float
    mac: str
    note: str = ""


def _mma(m, n, k, a_from, b_from):
    """Operand bytes of an m x n x k fp16 MMA with fp32 accumulators read and written in the register file."""
    a, b, acc = m * k * 2, k * n * 2, m * n * 4
    rf = 2 * acc + (a if a_from == "rf" else 0) + (b if b_from == "rf" else 0)
    smem = (a if a_from == "smem" else 0) + (b if b_from == "smem" else 0)
    return rf, smem


MMA_INSTRUCTIONS = [
    MatrixInstr("CPU-style scalar FMA (1 lane)", 1, 3 * 4 + 4, 0, "fp32", "one instruction per FMA"),
    MatrixInstr("SIMT FFMA (32 lanes, fp32)", 32, 32 * (3 * 4 + 4), 0, "fp32", "CUDA cores"),
    MatrixInstr("HMMA m16n8k16 (warp, fp16->fp32)", 16 * 8 * 16, *_mma(16, 8, 16, "rf", "rf"), "fp16",
                "Ampere-style tensor core; operands in registers"),
    MatrixInstr("wgmma m64n256k16 (warpgroup)", 64 * 256 * 16, *_mma(64, 256, 16, "smem", "smem"), "fp16",
                "Hopper; A and B read from shared memory"),
]


def output_stationary(K):
    """
    A matrix unit that keeps its accumulators inside the unit for a whole K-long reduction (a systolic array,
    Lecture 5; Blackwell's tensor memory is a step in this direction): the accumulators are read and written once
    per K, operands still come from shared memory at the wgmma rate.
    """
    m, n, k = 64, 256, 16
    a, b, acc = m * k * 2, k * n * 2, m * n * 4
    return MatrixInstr(f"accumulators kept in the unit (K = {K:,})", m * n * k, 2 * acc * k / K, a + b, "fp16",
                       "output-stationary: accumulator traffic once per K")


RF_BANK_BYTES = 16 * 1024        # ASSUMED register-file bank size used for the access energy
SMEM_BYTES = 228 * 1024          # H100 shared memory per SM


def instruction_energy(instr, ctrl_pj=em.HOROWITZ_INSTRUCTION_PJ, rf_bank=RF_BANK_BYTES, smem=SMEM_BYTES):
    """
    Energy per multiply-accumulate of one instruction family (45 nm, Lecture 1's model).

    [Idea] Energy per FMA = (instruction overhead + operand traffic) / FMAs per instruction + the MAC itself.
            overhead : ctrl_pj per issued instruction (fetch, decode, schedule) -- Horowitz's 70 pJ by default
            operands : register-file bytes x E(RF bank) + shared-memory bytes x E(SMEM)
    [Args] instr: MatrixInstr; ctrl_pj: overhead per instruction (sensitivity: try 20); rf_bank, smem: SRAM sizes
    [Returns] dict(control, register file, shared memory, math, total, math_share) in pJ per FMA
    [Edge cases] Wires between units, pipeline registers and leakage are not counted, so the absolute numbers are
        low; the RATIOS between instruction families are the point.
    """
    e_rf = em.sram_pj_per_byte(rf_bank)
    e_sm = em.sram_pj_per_byte(smem)
    parts = {"control": ctrl_pj / instr.fmas,
             "register file": instr.rf_bytes * e_rf / instr.fmas,
             "shared memory": instr.smem_bytes * e_sm / instr.fmas,
             "math": em.mac_energy_pj(instr.mac)}
    total = sum(parts.values())
    parts["total"] = total
    parts["math_share"] = parts["math"] / total
    return parts


# =====================================================================================================================
# 6. GEMM on a whole GPU
# =====================================================================================================================

@dataclass(frozen=True)
class GPUModel:
    """
    The parameters of the GEMM cost model.

    [Fields]
        sms, clock_hz, flops_per_clk_sm : 132 SMs x 1.83 GHz x 4,096 dense bf16 FLOP/clk/SM = 989 TFLOPS (datasheet)
        smem_per_sm, max_smem_per_block, max_blocks : occupancy limits (programming guide)
        hbm_bw          : 3.35 TB/s (datasheet)
        l2_bw           : ASSUMED 5,120 B/clk x 1.83 GHz = 9.4 TB/s (A100's published L2 rate at H100's clock)
        smem_bytes_per_clk : 128 B/clk per SM (32 banks x 4 B)
        latency_s       : ASSUMED 600 cycles from issuing an asynchronous tile copy to its arrival
        per_sm_cap      : one SM may draw at most this multiple of its fair share of L2/HBM bandwidth (ASSUMED 2x,
                          the same assumption as Lecture 10's split-KV model)
        launch_s        : ASSUMED kernel launch overhead (4 us, as in Lecture 10)
    """
    name: str = "H100 SXM (model)"
    sms: int = 132
    clock_hz: float = 1.83e9
    flops_per_clk_sm: float = 4096.0
    smem_per_sm: int = 228 * 1024
    max_smem_per_block: int = 227 * 1024
    max_blocks: int = 32
    hbm_bw: float = 3.35e12
    l2_bw: float = 5120 * 1.83e9
    smem_bytes_per_clk: float = 128.0
    latency_s: float = 600 / 1.83e9
    per_sm_cap: float = 2.0
    launch_s: float = 4e-6

    @property
    def peak(self):
        return self.sms * self.clock_hz * self.flops_per_clk_sm


H100_GPU = GPUModel()


@dataclass
class GemmResult:
    """Outcome of gemm_time: time, efficiency and the quantities that explain it."""
    seconds: float
    tflops: float
    efficiency: float
    tiles: int
    waves: int
    ctas_per_sm: int
    bound: str
    step_parts: dict = field(default_factory=dict)
    l2_bytes: float = 0.0
    dram_bytes: float = 0.0
    config: tuple = ()


def gemm_time(M, N, K, BM=128, BN=128, BK=64, stages=4, cluster=(1, 1), split_k=1, gpu=H100_GPU, elem=2,
              launch=True):
    """
    Time of C (M x N) = A (M x K) B (K x N) on a GPU with thread-block tiles of BM x BN.

    [Idea] Each thread block (CTA) owns a BM x BN tile of C and walks over K in steps of BK:
            per step  compute c = 2 BM BN BK / (SM FLOP rate / r)      r = co-resident CTAs sharing the SM
                      load    m = (BM/cn + BN/cm) BK elem / (SM's L2 bandwidth / r)
                                  (a cluster of cm x cn CTAs multicasts A along N and B along M)
                      shared-memory reads s = (BM + BN) BK elem / (128 B/clk / r)
            pipelining with S stages keeps S-1 tile copies in flight; each copy takes latency + m, so
                      step = max(c, m, s, (latency + m) / (S - 1))         (S = 1: step = latency + m + c)
            CTA time = prologue (latency + m) + steps x step + epilogue (write the C tile)
        Tile copies are served by the L2 cache. The CTAs of one wave cover a gm x gn block of tiles (rasterized
        to be roughly square, as CUTLASS's "swizzle" does), so DRAM delivers each A row-panel and B column-panel
        of that block once per wave; L2 serves the re-reads:
            wave time = max(CTA time, (gm BM + gn BN) K elem / HBM bandwidth)
            total     = waves x wave time,  waves = ceil(CTAs / (SMs x CTAs per SM))
        split_k > 1 splits K over that many CTAs, which then add their fp32 partial tiles (extra traffic charged).
    [Args] M, N, K; BM, BN, BK tile sizes; stages; cluster = (cm, cn); split_k; gpu: GPUModel; elem: bytes per input
        element (2 = bf16); launch: add the launch overhead
    [Returns] GemmResult (config = (BM, BN, BK, stages, cluster, split_k)); seconds = inf if the tile does not fit
    [Edge cases] Partial tiles at the edges compute a full tile (tile quantization: the wasted work is real on the
        hardware). The last wave may be partly empty (wave quantization). Both are what makes efficiency jump
        with the shape.
    """
    cm, cn = cluster
    tm, tn = math.ceil(M / BM), math.ceil(N / BN)
    tiles = tm * tn
    ctas = tiles * split_k
    smem_cta = stages * (BM + BN) * BK * elem
    cfg = (BM, BN, BK, stages, cluster, split_k)
    if smem_cta > gpu.max_smem_per_block or stages < 1:
        return GemmResult(math.inf, 0.0, 0.0, tiles, 0, 0, "does not fit", {}, 0, 0, cfg)
    per_sm = min(gpu.max_blocks, gpu.smem_per_sm // (smem_cta + 1024))
    waves = math.ceil(ctas / (gpu.sms * per_sm))
    r = min(per_sm, math.ceil(ctas / gpu.sms))                 # CTAs actually sharing one SM
    active_sms = min(gpu.sms, ctas)

    def share(bw):
        """Bandwidth one SM gets when `active_sms` SMs pull from a level of bandwidth bw."""
        return min(bw / active_sms, gpu.per_sm_cap * bw / gpu.sms)

    f_sm = gpu.flops_per_clk_sm * gpu.clock_hz
    k_cta = math.ceil(K / split_k)
    steps = math.ceil(k_cta / BK)
    c = 2 * BM * BN * BK / (f_sm / r)
    load_bytes = (BM / cn + BN / cm) * BK * elem
    m = load_bytes / (share(gpu.l2_bw) / r)
    s = (BM + BN) * BK * elem / (gpu.smem_bytes_per_clk * gpu.clock_hz / r)
    lat = gpu.latency_s
    if stages == 1:
        step = lat + m + c
        parts = {"compute": c, "load": m, "latency": lat}
    else:
        parts = {"compute": c, "load": m, "smem": s, "latency": (lat + m) / (stages - 1)}
        step = max(parts.values())
    out_bytes = BM * BN * (4 if split_k > 1 else elem)
    epilogue = out_bytes / (share(gpu.hbm_bw) / r)
    cta_time = (lat + m) + steps * step + epilogue
    # DRAM traffic of one wave: the A and B panels of the gm x gn block of tiles it covers
    per_wave = min(ctas, gpu.sms * per_sm)
    tiles_wave = max(1, per_wave // split_k)
    gn = min(tn, max(1, round(math.sqrt(tiles_wave * BM / BN))))
    gm = min(tm, math.ceil(tiles_wave / gn))
    gn = min(tn, math.ceil(tiles_wave / gm))                  # re-balance when gm hit the edge of the matrix
    wave_dram = (min(gm * BM, M) + min(gn * BN, N)) * K * elem
    t_dram_wave = wave_dram / gpu.hbm_bw
    t = waves * max(cta_time, t_dram_wave)
    dram = waves * wave_dram + M * N * elem
    # split-K: partial fp32 tiles are written and summed by a second pass (read split_k partials, write C)
    extra = 0.0
    if split_k > 1:
        extra = (split_k * M * N * 4 + M * N * elem) / gpu.hbm_bw
        dram += split_k * M * N * 4 * 2
    t = max(t + extra, (M * K + K * N + M * N) * elem / gpu.hbm_bw)
    if launch:
        t += gpu.launch_s * (2 if split_k > 1 else 1)
    flops = 2 * M * N * K
    bound_part = max(parts, key=parts.get) if stages > 1 else "serial"
    if t_dram_wave >= cta_time:
        bound = "HBM bandwidth"
    else:
        bound = {"compute": "tensor cores", "load": "L2/HBM bandwidth per SM", "smem": "shared-memory bandwidth",
                 "latency": "copy latency (too few stages)", "serial": "no pipelining"}[bound_part]
    l2_traffic = ctas * steps * load_bytes
    return GemmResult(t, flops / t / 1e12, flops / t / gpu.peak, tiles, waves, per_sm, bound, parts, l2_traffic,
                      dram, cfg)


TILES = [(64, 64), (64, 128), (128, 64), (128, 128), (128, 256), (256, 128)]


def best_gemm(M, N, K, gpu=H100_GPU, tiles=TILES, stages_list=(2, 3, 4, 5, 6), clusters=((1, 1), (2, 1), (1, 2)),
              split_ks=(1, 2, 4, 8, 16), BK=64):
    """
    A tiny autotuner: the fastest configuration of gemm_time over tiles, stages, clusters and split-K.

    [Idea] cuBLAS and CUTLASS ship many kernel variants and pick one per shape by heuristics or measurement; we
        enumerate ours (6 tiles x 5 stage counts x 3 clusters x 5 split factors = 450 evaluations, instant).
    [Returns] GemmResult of the best configuration
    [Edge cases] Configurations whose shared memory does not fit are skipped (time = inf). split_k is only tried
        when it leaves at least BK of K per CTA.
    """
    best = None
    for BM, BN in tiles:
        for st in stages_list:
            for cl in clusters:
                for sk in split_ks:
                    if sk > 1 and K / sk < BK:
                        continue
                    r = gemm_time(M, N, K, BM, BN, BK, st, cl, sk, gpu)
                    if best is None or r.seconds < best.seconds:
                        best = r
    return best


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

if __name__ == "__main__":
    # divergence
    d = divergence_efficiency([i % 2 == 0 for i in range(64)], 10, 10)
    assert d["cycles"] == 40 and abs(d["lane_eff"] - 0.5) < 1e-12
    d = divergence_efficiency([i < 32 for i in range(64)], 10, 10)
    assert d["cycles"] == 20 and d["lane_eff"] == 1.0
    # coalescing
    assert coalesce(warp_addresses("unit"))["sectors"] == 4
    assert coalesce(warp_addresses("stride", stride=2))["sectors"] == 8
    assert coalesce(warp_addresses("stride", stride=8))["sectors"] == 32
    assert coalesce(warp_addresses("offset", offset=1))["sectors"] == 5
    # shared-memory banks: column of a 32x32 float tile, unpadded vs padded
    assert smem_conflicts([r * 32 for r in range(32)]) == 32
    assert smem_conflicts([r * 33 for r in range(32)]) == 1
    # latency hiding: a streaming kernel gets faster with more warps, a compute kernel saturates at 16 warps
    k_mem = Kernel(iters=8, loads=1, alu=2, ilp=1)
    u1 = simulate_sm(k_mem, 4)["mem_util"]
    u2 = simulate_sm(k_mem, 64)["mem_util"]
    assert u2 > 4 * u1, (u1, u2)
    k_alu = Kernel(iters=8, loads=0, alu=32, ilp=1)
    assert simulate_sm(k_alu, 16)["alu_util"] > 0.95
    assert simulate_sm(k_alu, 4)["alu_util"] < 0.3
    # occupancy: 256 threads, 32 registers, no shared memory -> 8 blocks, 100%
    o = occupancy(H100_LIMITS, 256, 32, 0)
    assert o["blocks"] == 8 and o["occupancy"] == 1.0
    o = occupancy(H100_LIMITS, 256, 255, 0)            # 255 regs -> 256 x 32 = 8,192 regs per warp -> 1 block
    assert o["blocks"] == 1 and o["limiter"] == "registers", o
    # tensor-core rates from the datasheets agree with the architectural counts
    assert abs(per_sm_rates(H100)["bf16"] - 2 * TC_FMA_PER_CLK["H100"]) / 4096 < 0.01
    assert abs(per_sm_rates(A100)["fp16"] - 2 * TC_FMA_PER_CLK["A100"]) / 2048 < 0.01
    e = [instruction_energy(i)["math_share"] for i in MMA_INSTRUCTIONS]
    assert e == sorted(e), e
    # GEMM: a big square GEMM is near peak; a decode GEMV is HBM-bound
    big = best_gemm(8192, 8192, 8192)
    assert big.efficiency > 0.85, big
    gemv = best_gemm(1, 4096, 4096)
    assert gemv.bound in ("HBM bandwidth", "L2/HBM bandwidth per SM"), gemv
    print("gpu.py self-test passed")
    print(f"  8192^3 bf16 GEMM: best {big.config} -> {big.tflops:.0f} TFLOPS ({big.efficiency:.0%}), {big.waves} waves;"
          f" 1 x 4096 x 4096 GEMV: {gemv.seconds * 1e6:.1f} us ({gemv.bound})")
