"""Kernel fusion: bytes moved and time for a chain of elementwise steps, and a CPU stand-in you can run.

Model used throughout the lesson: two levels of memory, as in the roofline lesson (tiled-matmul-roofline). Main memory is large and
has a limited bandwidth; fast memory is small and free to use. We count the elements that cross between them. An elementwise step
makes each output element from the one input element in the same place, so it does 1 FLOP of math per element and needs a full read
and a full write of the tensor. A bias is one number per column, tiny next to the tensor, so the code uses one number and counts it as free.

Run `python3 kernel_fusion.py` for the numbers quoted in the lesson, and `python3 kernel_fusion.py --time` to time numpy on your own machine.
"""
from __future__ import annotations

import sys
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass

import numpy as np

# --- the chip: copied from the roofline lesson (test_kernel_fusion.py checks the copy against ../../tiled-matmul-roofline/code/tiled_roofline.py)
# NVIDIA A100 Tensor Core GPU data sheet (revision "Jun21"), 80GB SXM column: 312 TFLOPS dense BFLOAT16/FP16 on the tensor cores, 2,039 GB/s
# (the 40GB cards list 1,555 GB/s). GB is 10**9 bytes. The tensor cores run only matrix multiplications.
# The steps here (add, multiply, max) run on the ordinary units. The NVIDIA Ampere Architecture In-Depth post gives 108 SMs, 64 FP32 cores
# per SM and a 1.41 GHz boost clock, and Table 1 gives 19.5 TFLOPS for FP32 (108 x 64 x 2 x 1.41 GHz = 19.49): the 2 counts one fused
# multiply-add (FMA) as two calculations. A plain add, multiply or max is one calculation per instruction, so these steps peak at half of
# it, 9.75 TFLOPS. PyTorch does FP16 pointwise math in FP32 (OpMathType.h: "For FP16 or BFloat16 inputs, ops should perform internal math
# in FP32"; torch/_inductor/config.py: codegen_upcast_to_fp32 = True), so the FP32 rate is the one that applies. Table 1 also gives
# 78 TFLOPS for FP16 arithmetic; half of that, 39 TFLOPS, is what a kernel doing its steps in FP16 would get (Go deeper uses it once).
A100_PEAK_FLOPS = 312e12
A100_BANDWIDTH = 2039e9
A100_FP32_FLOPS = 19.5e12
A100_FP16_FLOPS = 78e12
A100_STEP_FLOPS = A100_FP32_FLOPS / 2
FP16_BYTES = 2

SIDE = 4096                  # the tensor is SIDE x SIDE numbers, stored in 2 bytes each
ELEMS = SIDE * SIDE
MAX_STEPS = 8                # the widget's slider


# --- the model: bytes, intensity, time --------------------------------------------------

def pass_bytes(elems: int = ELEMS, elem_bytes: int = FP16_BYTES) -> int:
    """One full trip over the tensor, in one direction."""
    return elems * elem_bytes


def chain_bytes(steps: int, fused: bool, elems: int = ELEMS, elem_bytes: int = FP16_BYTES) -> int:
    """Traffic of `steps` elementwise steps. Unfused, every step reads and writes the tensor: 2 * steps passes. Fused: 2 passes."""
    return (2 if fused else 2 * steps) * pass_bytes(elems, elem_bytes)


def chain_intensity(steps: int, fused: bool, elem_bytes: int = FP16_BYTES) -> float:
    """FLOP per byte: `steps` FLOPs per element over the bytes each element moves."""
    return steps / (chain_bytes(steps, fused, 1, elem_bytes))


def ridge(peak_flops: float = A100_PEAK_FLOPS, bandwidth: float = A100_BANDWIDTH) -> float:
    return peak_flops / bandwidth


def kernel_time(flops: float, nbytes: float, peak_flops: float = A100_PEAK_FLOPS, bandwidth: float = A100_BANDWIDTH) -> float:
    """Seconds: math and traffic overlap, so a kernel takes the larger of its two floors."""
    return max(flops / peak_flops, nbytes / bandwidth)


def chain_time(steps: int, fused: bool, peak_flops: float = A100_STEP_FLOPS, elems: int = ELEMS) -> float:
    """Seconds for the chain, with the steps charged at A100_STEP_FLOPS. Unfused it is `steps` kernels one after another; fused it is
    one kernel doing all the math."""
    if fused:
        return kernel_time(steps * elems, chain_bytes(steps, True, elems), peak_flops)
    return steps * kernel_time(elems, chain_bytes(1, False, elems), peak_flops)


def steps_to_reach_ridge(flops_per_step: int = 1, elem_bytes: int = FP16_BYTES, peak_flops: float = A100_STEP_FLOPS) -> int:
    """Fewest chained steps for which the fused kernel stops waiting on memory: steps * flops_per_step / (2 * elem_bytes) >= ridge.
    The default is the rate of the add, multiply and max steps; pass A100_FP16_FLOPS / 2 for steps done in FP16 arithmetic."""
    need = ridge(peak_flops) * 2 * elem_bytes / flops_per_step
    return int(need) + (need != int(need))


def matmul_flops(side: int = SIDE) -> int:
    return 2 * side ** 3


def matmul_min_bytes(side: int = SIDE, elem_bytes: int = FP16_BYTES) -> int:
    """Read A once, read B once, write C once (the best case, from the roofline lesson)."""
    return 3 * side * side * elem_bytes


def matmul_intensity(side: int = SIDE) -> float:
    """FLOP per byte of the multiply in its best case; it equals side / 3 for 2-byte numbers."""
    return matmul_flops(side) / matmul_min_bytes(side)


def matmul_time(side: int = SIDE) -> float:
    return kernel_time(matmul_flops(side), matmul_min_bytes(side))


def matmul_then_chain_bytes(steps: int, fused: bool) -> int:
    """Traffic of the multiply plus the chain: the chain's passes are the only part fusion removes."""
    return matmul_min_bytes() + (0 if fused else chain_bytes(steps, False))


def matmul_then_chain_time(steps: int, fused: bool) -> float:
    """A big matrix multiply followed by the chain on its result. Fused, the steps run on each tile of C before its one write
    (the epilogue), so the multiply's own write is the only write and the chain adds no passes. The model takes the steps' arithmetic in
    the epilogue to overlap the multiply's own calculating, so it adds no time."""
    return matmul_time() + (0.0 if fused else chain_time(steps, False))


# --- executors that count traffic ---------------------------------------------------------

@dataclass
class Traffic:
    loads: int = 0    # elements read from main memory
    stores: int = 0   # elements written to main memory

    def nbytes(self, elem_bytes: int) -> int:
        return (self.loads + self.stores) * elem_bytes


OPS = {
    "add": lambda a, v: np.add(a, v, out=a),
    "sub": lambda a, v: np.subtract(a, v, out=a),
    "mul": lambda a, v: np.multiply(a, v, out=a),
    "relu": lambda a, v: np.maximum(a, 0, out=a),
}
Step = tuple[str, float]


def run_unfused(x: np.ndarray, steps: list[Step], t: Traffic) -> None:
    """Each step sweeps the whole array: read all of it, write all of it, before the next step starts. Works in place."""
    for op, v in steps:
        t.loads += x.size
        OPS[op](x, v)
        t.stores += x.size


def run_fused(x: np.ndarray, steps: list[Step], t: Traffic, chunk: int) -> None:
    """Take one chunk, run every step on it while it stays in fast memory, write it back, take the next. Works in place."""
    for i in range(0, x.size, chunk):
        blk = x[i:i + chunk]
        t.loads += blk.size
        for op, v in steps:
            OPS[op](blk, v)
        t.stores += blk.size


def reference(x: np.ndarray, steps: list[Step]) -> np.ndarray:
    """The same chain with no counting and no chunks, on a copy."""
    y = x.copy()
    for op, v in steps:
        OPS[op](y, v)
    return y


# --- timing on the CPU (numpy) ------------------------------------------------------------
# The CPU has no HBM, but it has the same two-level shape: main memory (slow) and the cache next to the core (fast). A chunk that fits
# in cache plays the part of the tile held in registers or shared memory on a GPU.

TIMING_STEPS: list[Step] = [("add", 0.5), ("mul", 1.25), ("sub", 0.125), ("add", 0.25), ("mul", 0.75), ("sub", 0.0625), ("add", 0.125), ("mul", 1.5)]
CPU_ELEMS = 2 ** 25      # float32: 128 MiB, far larger than any cache
CPU_CHUNK = 262144       # float32: 1 MiB
CPU_WORKERS = 4


def _slabs(x: np.ndarray, workers: int) -> list[np.ndarray]:
    size = x.size // workers
    return [x[i * size:(i + 1) * size] for i in range(workers)]


def time_cpu(steps: int, fused: bool, reps: int = 5, workers: int = CPU_WORKERS, chunk: int = CPU_CHUNK) -> float:
    """Best of `reps` seconds for the first `steps` of TIMING_STEPS on 2**25 float32, split across `workers` threads."""
    chain = TIMING_STEPS[:steps]
    base = np.random.default_rng(0).random(CPU_ELEMS, dtype=np.float32)
    best = float("inf")
    with ThreadPoolExecutor(workers) as pool:
        for _ in range(reps):
            x = base.copy()
            slabs = _slabs(x, workers)
            start = time.perf_counter()
            if fused:
                list(pool.map(lambda s: run_fused(s, chain, Traffic(), chunk), slabs))
            else:
                list(pool.map(lambda s: run_unfused(s, chain, Traffic()), slabs))
            best = min(best, time.perf_counter() - start)
    return best


def main() -> None:
    k = 3
    print(f"table: {SIDE} x {SIDE} = {ELEMS:,} numbers of {FP16_BYTES} bytes; one pass = {pass_bytes():,} bytes")
    print(f"A100 ridge (FLOP/byte): {ridge(A100_STEP_FLOPS):.1f} for the add, ReLU and scale steps, {ridge():.1f} for the tensor-core multiply")
    for fused in (False, True):
        name = "fused" if fused else "unfused"
        print(f"{k} steps {name}: {2 if fused else 2 * k} passes, {chain_bytes(k, fused):,} bytes, "
              f"{chain_time(k, fused) * 1e6:.1f} us, intensity {chain_intensity(k, fused):.3f} FLOP/byte")
    print(f"byte ratio {chain_bytes(k, False) / chain_bytes(k, True):.1f}x, time ratio {chain_time(k, False) / chain_time(k, True):.1f}x")
    print(f"one-FLOP steps needed for the fused kernel to reach the ridge: {steps_to_reach_ridge()}")
    print(f"matmul {SIDE}^3: {matmul_flops() / 1e9:.1f} GFLOP, calculation floor {matmul_flops() / A100_PEAK_FLOPS * 1e6:.1f} us, "
          f"memory floor {matmul_min_bytes() / A100_BANDWIDTH * 1e6:.1f} us, time {matmul_time() * 1e6:.1f} us, "
          f"intensity {matmul_intensity():,.1f} FLOP/byte")
    u, f = matmul_then_chain_time(k, False), matmul_then_chain_time(k, True)
    print(f"matmul then {k} steps: unfused {u * 1e6:.1f} us, fused into the epilogue {f * 1e6:.1f} us, "
          f"{u / f:.2f}x, {(u - f) / u * 100:.1f}% saved")


def main_time() -> None:
    print(f"numpy, float32, 2**25 numbers, {CPU_WORKERS} threads, chunk {CPU_CHUNK:,}; best of 5 runs, in place")
    for steps in (3, 8):
        a, b = time_cpu(steps, False), time_cpu(steps, True)
        print(f"{steps} steps: step by step {a * 1e3:.1f} ms, chunk by chunk {b * 1e3:.1f} ms, {a / b:.2f}x faster "
              f"(byte count predicts {steps:.0f}x)")


if __name__ == "__main__":
    main_time() if "--time" in sys.argv else main()
