"""
graph.py -- a tiny tensor-graph IR with a numpy interpreter, a fusion pass with legality rules, and a roofline cost
model of kernel-by-kernel execution
=====================================================================================================================

[Why we need it]
    Frameworks run a model as a GRAPH of operators. Executed one operator at a time ("eager" mode), every operator
    is a separate kernel that reads its inputs from DRAM and writes its output back -- even when the next operator
    immediately reads that output again. For the matrix multiplications that costs little (they do hundreds of
    FLOPs per byte), but the element-wise and normalization operators in between do ~1 FLOP per byte: they are
    pure memory traffic, plus a kernel-launch overhead each. FUSION merges operators into one kernel so that the
    intermediate tensors stay in registers or on-chip memory. This module makes that concrete:
    1. a graph IR (nodes with an op, inputs and an output shape) and builders for a Llama-style decoder block;
    2. a numpy interpreter -- fused and unfused execution must compute the same values;
    3. a fusion pass with explicit LEGALITY rules and several strategies (none, element-wise chains, matmul
       epilogues/prologues, the FlashAttention pattern);
    4. a cost model: each kernel moves its external inputs and outputs through DRAM and is timed by the roofline
       (Lecture 1) plus a launch overhead.

[Legality rules] (what may be fused into one kernel, as in PyTorch 2's TorchInductor at a coarse level)
    - element-wise ops fuse with element-wise neighbours (vertical fusion of chains);
    - row REDUCTIONS (RMSNorm, softmax over the last axis) fuse with element-wise neighbours, provided a whole row
      fits one kernel's working set (row_limit elements);
    - element-wise consumers of a matmul fuse into its EPILOGUE (bias, activation, residual add on the output tile);
      element-wise producers of a matmul's activation input fuse into its PROLOGUE;
    - matmuls that read the same activation can be concatenated into one wider matmul (HORIZONTAL fusion);
    - a reduction never fuses into a matmul prologue (the matmul tile would have to hold whole rows of K) and two
      matmuls never fuse -- EXCEPT the attention pattern matmul -> scale -> softmax -> matmul, which the
      FlashAttention algorithm (flash.py) can compute tile by tile.

[Edge cases]
    - Reshapes and transposes are free views here (layout changes that real kernels sometimes pay for).
    - Matmul kernels are charged compulsory traffic (each operand once), the Lecture 1 convention; Lecture 7 shows
      the extra traffic of finite buffers. Causal attention is charged its full T x T FLOPs (flash.py shows the
      2x a kernel saves by skipping fully masked tiles).
"""

import math
from dataclasses import dataclass, field

import numpy as np

import course_path

course_path.use("lecture01")

from hw_specs import H100  # noqa: E402

ELEMENTWISE = {"add", "mul", "silu", "gelu", "scale", "rope", "mask", "cast"}
REDUCTION = {"rmsnorm", "softmax"}
MATMUL = {"matmul", "bmm"}
SOURCES = {"input", "weight"}
FLOPS_PER_ELEM = {"add": 1, "mul": 1, "silu": 4, "gelu": 8, "scale": 1, "rope": 3, "mask": 1, "cast": 0,
                  "rmsnorm": 4, "softmax": 5}


@dataclass
class Node:
    """
    One operator.

    [Fields] name; op; inputs (names of producer nodes); shape (output shape); attrs (e.g. "scale", "eps")
    [Properties] elems (output elements)
    """
    name: str
    op: str
    inputs: tuple = ()
    shape: tuple = ()
    attrs: dict = field(default_factory=dict)

    @property
    def elems(self):
        return math.prod(self.shape)


class Graph:
    """
    A DAG of nodes in topological order (nodes are added after their inputs).

    [Methods] add(...), consumers(name), flops(node), outputs() (nodes nobody consumes)
    """

    def __init__(self, elem_bytes=2):
        self.nodes = {}
        self.order = []
        self.elem_bytes = elem_bytes

    def add(self, name, op, inputs=(), shape=(), **attrs):
        for i in inputs:
            if i not in self.nodes:
                raise ValueError(f"{name}: unknown input {i!r} (add producers first)")
        self.nodes[name] = Node(name, op, tuple(inputs), tuple(shape), attrs)
        self.order.append(name)
        return name

    def consumers(self, name):
        return [n for n in self.order if name in self.nodes[n].inputs]

    def outputs(self):
        return [n for n in self.order if not self.consumers(n) and self.nodes[n].op not in SOURCES]

    def flops(self, n):
        """FLOPs of one node: 2 x M x N x K for matmuls, a per-element constant otherwise."""
        node = self.nodes[n]
        if node.op in MATMUL:
            a = self.nodes[node.inputs[0]].shape
            red = a[-1] // node.attrs["heads"] if node.attrs.get("transpose_b") else a[-1]   # QK^T reduces over hd
            return 2 * node.elems * red
        return FLOPS_PER_ELEM.get(node.op, 0) * node.elems

    def nbytes(self, n):
        return self.nodes[n].elems * self.elem_bytes


# =====================================================================================================================
# A Llama-style decoder block
# =====================================================================================================================

def decoder_block(T, d, H, hd, F, causal=True, elem_bytes=2):
    """
    The graph of one pre-norm decoder block for T tokens (prefill of one sequence; T = batch for decode with no
    context is NOT modeled here -- attention is over the T tokens themselves).

    [Idea] x -> RMSNorm -> Q, K, V projections -> RoPE(Q, K) -> scores = Q K^T -> scale -> causal mask -> softmax
        -> P V -> output projection -> + x (residual) -> RMSNorm -> gate, up projections -> SiLU(gate) * up ->
        down projection -> + residual. Heads are a batch dimension of the attention matmuls (H query heads of
        size hd; multi-head, no grouped-query sharing, to keep shapes simple).
    [Returns] Graph
    """
    g = Graph(elem_bytes)
    g.add("x", "input", shape=(T, d))
    for w, shp in (("w_norm1", (d,)), ("wq", (d, H * hd)), ("wk", (d, H * hd)), ("wv", (d, H * hd)),
                   ("wo", (H * hd, d)), ("w_norm2", (d,)), ("wg", (d, F)), ("wu", (d, F)), ("wd", (F, d))):
        g.add(w, "weight", shape=shp)
    g.add("h1", "rmsnorm", ("x", "w_norm1"), (T, d), eps=1e-5)
    g.add("q", "matmul", ("h1", "wq"), (T, H * hd))
    g.add("k", "matmul", ("h1", "wk"), (T, H * hd))
    g.add("v", "matmul", ("h1", "wv"), (T, H * hd))
    g.add("q_r", "rope", ("q",), (T, H * hd), heads=H)
    g.add("k_r", "rope", ("k",), (T, H * hd), heads=H)
    g.add("s", "bmm", ("q_r", "k_r"), (H, T, T), heads=H, transpose_b=True)
    g.add("s_scaled", "scale", ("s",), (H, T, T), scale=1 / math.sqrt(hd))
    g.add("s_masked", "mask", ("s_scaled",), (H, T, T), causal=causal)
    g.add("p", "softmax", ("s_masked",), (H, T, T))
    g.add("attn", "bmm", ("p", "v"), (T, H * hd), heads=H)
    g.add("o", "matmul", ("attn", "wo"), (T, d))
    g.add("x1", "add", ("x", "o"), (T, d))
    g.add("h2", "rmsnorm", ("x1", "w_norm2"), (T, d), eps=1e-5)
    g.add("gate", "matmul", ("h2", "wg"), (T, F))
    g.add("up", "matmul", ("h2", "wu"), (T, F))
    g.add("act", "silu", ("gate",), (T, F))
    g.add("prod", "mul", ("act", "up"), (T, F))
    g.add("down", "matmul", ("prod", "wd"), (T, d))
    g.add("y", "add", ("x1", "down"), (T, d))
    return g


# =====================================================================================================================
# The interpreter
# =====================================================================================================================

def _rope(x, heads):
    """Rotary embedding on (T, heads * hd): rotate pairs (even, odd) of each head by position-dependent angles."""
    T, D = x.shape
    hd = D // heads
    pos = np.arange(T)[:, None]
    freq = 10000.0 ** (-np.arange(0, hd, 2) / hd)
    ang = np.tile(pos * freq[None, :], (1, heads))
    c, s = np.cos(ang), np.sin(ang)
    out = np.empty_like(x)
    out[:, 0::2] = x[:, 0::2] * c - x[:, 1::2] * s
    out[:, 1::2] = x[:, 0::2] * s + x[:, 1::2] * c
    return out


def run(g, feeds, attention=None):
    """
    Evaluate the graph in float64 numpy.

    [Args] feeds: dict name -> array for every input and weight; attention: optional function (q, k, v, heads,
        scale, causal) -> output used IN PLACE of the s -> scale -> mask -> softmax -> bmm chain (to check that a
        fused attention kernel computes the same thing)
    [Returns] dict name -> value of every computed node
    """
    val = dict(feeds)
    skip = set()
    if attention is not None:
        skip = {"s", "s_scaled", "s_masked", "p"}
    for n in g.order:
        node = g.nodes[n]
        if node.op in SOURCES or n in skip:
            continue
        a = [val[i] for i in node.inputs if i in val]
        op = node.op
        if op == "rmsnorm":
            x, w = a
            out = x / np.sqrt((x ** 2).mean(-1, keepdims=True) + node.attrs["eps"]) * w
        elif op == "matmul":
            out = a[0] @ a[1]
        elif op == "bmm" and n == "attn" and attention is not None:
            q, k, v = val["q_r"], val["k_r"], val["v"]
            out = attention(q, k, v, g.nodes["s"].attrs["heads"], g.nodes["s_scaled"].attrs["scale"],
                            g.nodes["s_masked"].attrs["causal"])
        elif op == "bmm":
            H = node.attrs["heads"]
            if node.attrs.get("transpose_b"):
                q, k = a
                T = q.shape[0]
                out = np.einsum("thd,shd->hts", q.reshape(T, H, -1), k.reshape(T, H, -1))
            else:
                p, v = a
                T = v.shape[0]
                out = np.einsum("hts,shd->thd", p, v.reshape(T, H, -1)).reshape(T, -1)
        elif op == "rope":
            out = _rope(a[0], node.attrs["heads"])
        elif op == "scale":
            out = a[0] * node.attrs["scale"]
        elif op == "mask":
            out = a[0].copy()
            if node.attrs.get("causal"):
                T = out.shape[-1]
                out[:, np.triu(np.ones((T, T), dtype=bool), 1)] = -np.inf
        elif op == "softmax":
            e = np.exp(a[0] - a[0].max(-1, keepdims=True))
            out = e / e.sum(-1, keepdims=True)
        elif op == "add":
            out = a[0] + a[1]
        elif op == "mul":
            out = a[0] * a[1]
        elif op == "silu":
            out = a[0] / (1 + np.exp(-a[0]))
        elif op == "gelu":
            out = 0.5 * a[0] * (1 + np.tanh(math.sqrt(2 / math.pi) * (a[0] + 0.044715 * a[0] ** 3)))
        else:
            raise ValueError(f"no interpreter for {op!r}")
        val[n] = out
    return val


def random_feeds(g, seed=0):
    """Random inputs and weights (scaled so that activations stay O(1))."""
    rng = np.random.default_rng(seed)
    feeds = {}
    for n in g.order:
        node = g.nodes[n]
        if node.op == "input":
            feeds[n] = rng.normal(size=node.shape)
        elif node.op == "weight":
            feeds[n] = (1.0 + 0.1 * rng.normal(size=node.shape)) if len(node.shape) == 1 else \
                rng.normal(size=node.shape) / math.sqrt(node.shape[0])
    return feeds


# =====================================================================================================================
# Fusion
# =====================================================================================================================

STRATEGIES = ("none", "elementwise", "epilogue", "horizontal", "flash")


def _kind(op):
    if op in ELEMENTWISE:
        return "ew"
    if op in REDUCTION:
        return "red"
    if op in MATMUL:
        return "mm"
    return op


def fuse(g, strategy="epilogue", row_limit=16384):
    """
    Partition the graph's compute nodes into kernels (groups), following the legality rules of the docstring.

    [Idea] Greedy, in topological order: each node joins the group of one of its producers if the strategy allows
        that pair of kinds, or starts a new group.
            none        : every node is its own kernel
            elementwise : element-wise and row-reduction ops join element-wise/reduction producers
            epilogue    : + element-wise ops join a matmul producer (epilogue), and a matmul joins the group of
                          its element-wise activation producer (prologue) -- never a reduction producer
            horizontal  : + matmuls that read the SAME activation (Q, K, V; gate and up) become one wider matmul,
                          so the activation is read once and their epilogues can combine (SiLU(gate) * up)
            flash       : + the attention chain (bmm QK^T, scale, mask, softmax, bmm PV) becomes ONE kernel
        A node joins at most one group; a group never contains two matmuls (except horizontally concatenated ones
        and the flash pattern); and a node
        may join a group only if all its other inputs are produced by EARLIER kernels (kernels run in order).
    [Args] row_limit: largest row (last-axis length) a fused reduction may span
    [Returns] list of groups (lists of node names) in execution order
    """
    if strategy not in STRATEGIES:
        raise ValueError(f"strategy must be one of {STRATEGIES}")
    group_of, groups = {}, []
    attn_chain = ["s", "s_scaled", "s_masked", "p", "attn"]
    for n in g.order:
        node = g.nodes[n]
        if node.op in SOURCES:
            continue
        if strategy == "flash" and n in attn_chain and n != "s":
            gi = group_of["s"]
            groups[gi].append(n)
            group_of[n] = gi
            continue
        joined = None
        if strategy in ("horizontal", "flash") and node.op == "matmul":
            for gi, grp in enumerate(groups):                       # horizontal: same activation input
                if any(g.nodes[m].op == "matmul" and g.nodes[m].inputs[0] == node.inputs[0] for m in grp) and \
                        all(group_of.get(i, -1) <= gi for i in node.inputs):
                    joined = gi
                    break
        if strategy != "none" and joined is None:
            k = _kind(node.op)
            for p in node.inputs:
                if p not in group_of:
                    continue
                pg = groups[group_of[p]]
                pkinds = {_kind(g.nodes[m].op) for m in pg}
                pk = _kind(g.nodes[p].op)
                ok = False
                if k in ("ew", "red") and pk in ("ew", "red"):
                    ok = k != "red" or node.shape[-1] <= row_limit
                    ok = ok and "mm" not in pkinds or (strategy in ("epilogue", "horizontal", "flash") and k == "ew")
                if strategy in ("epilogue", "horizontal", "flash"):
                    if k == "ew" and pk == "mm":
                        ok = True                                    # epilogue
                    if k == "mm" and pk == "ew" and "mm" not in pkinds and "red" not in pkinds and \
                            p == node.inputs[0]:
                        ok = True                                    # prologue on the activation operand
                # every other input must already exist when this group runs (groups run in creation order)
                if ok and all(group_of.get(i, -1) <= group_of[p] for i in node.inputs):
                    joined = group_of[p]
                    break
        if joined is None:
            groups.append([n])
            group_of[n] = len(groups) - 1
        else:
            groups[joined].append(n)
            group_of[n] = joined
    return groups


@dataclass
class Kernel:
    """One kernel: its nodes, FLOPs, DRAM bytes (external inputs + outputs), and roofline time."""
    nodes: list
    flops: float
    bytes: float
    seconds: float
    bound: str


def kernel_costs(g, groups, machine=H100, dtype="bf16", launch_s=4e-6, flash_tile_reads=None):
    """
    Price each kernel: DRAM bytes = tensors it reads that come from outside it + tensors it produces that are used
    outside it (or are graph outputs); time = max(FLOPs / peak, bytes / bandwidth) + a launch overhead.

    [Args] machine: a hw_specs.Machine; launch_s: per-kernel overhead (a few microseconds on GPUs without CUDA
        graphs); flash_tile_reads: optional function (graph) -> extra K/V bytes a FlashAttention kernel re-reads
        (flash.py computes them; default: K and V read once)
    [Returns] list of Kernel
    """
    peak, bw = machine.peak(dtype), machine.mem_bw
    outs = set(g.outputs())
    res = []
    for grp in groups:
        members = set(grp)
        ext_in = {i for n in grp for i in g.nodes[n].inputs if i not in members}
        ext_out = {n for n in grp if n in outs or any(c not in members for c in g.consumers(n))}
        nbytes = sum(g.nbytes(i) for i in ext_in) + sum(g.nbytes(o) for o in ext_out)
        if flash_tile_reads and "attn" in members and "s" in members:
            nbytes += flash_tile_reads(g)
        flops = sum(g.flops(n) for n in grp)
        t_c, t_m = flops / peak, nbytes / bw
        res.append(Kernel(grp, flops, nbytes, max(t_c, t_m) + launch_s, "compute" if t_c >= t_m else "memory"))
    return res


def summarize(kernels):
    """(number of kernels, total FLOPs, total DRAM bytes, total seconds)."""
    return len(kernels), sum(k.flops for k in kernels), sum(k.bytes for k in kernels), sum(k.seconds for k in kernels)


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

if __name__ == "__main__":
    g = decoder_block(T=16, d=32, H=4, hd=8, F=64)
    feeds = random_feeds(g)
    val = run(g, feeds)
    # reference attention written independently
    q, k, v = val["q_r"].reshape(16, 4, 8), val["k_r"].reshape(16, 4, 8), val["v"].reshape(16, 4, 8)
    s = np.einsum("thd,shd->hts", q, k) / math.sqrt(8)
    s[:, np.triu(np.ones((16, 16), dtype=bool), 1)] = -np.inf
    p = np.exp(s - s.max(-1, keepdims=True))
    p /= p.sum(-1, keepdims=True)
    assert np.allclose(val["attn"], np.einsum("hts,shd->thd", p, v).reshape(16, 32))
    # fusion: every compute node in exactly one kernel; more fusion -> fewer kernels and fewer bytes
    prev = None
    for st in STRATEGIES:
        grp = fuse(g, st)
        flat = [n for gr in grp for n in gr]
        assert sorted(flat) == sorted(n for n in g.order if g.nodes[n].op not in SOURCES)
        nk, fl, by, _ = summarize(kernel_costs(g, grp))
        if prev:
            assert nk <= prev[0] and by <= prev[2] + 1e-9, (st, nk, by, prev)
        prev = (nk, fl, by)
    # no kernel holds two matmuls except the flash attention kernel; every kernel's inputs exist before it runs
    for st in STRATEGIES:
        grp = fuse(g, st)
        where = {n: i for i, gr_ in enumerate(grp) for n in gr_}
        for i, gr_ in enumerate(grp):
            mms = [n for n in gr_ if g.nodes[n].op in MATMUL]
            assert len(mms) <= 1 or set(gr_) >= {"s", "attn"} or \
                len({g.nodes[m].inputs[0] for m in mms}) == 1, (st, gr_)
            for n in gr_:
                assert all(where.get(p, -1) <= i for p in g.nodes[n].inputs), (st, n)
    assert ["down", "y"] in fuse(g, "epilogue")                      # the residual add rides in the down projection
    big = decoder_block(T=2048, d=4096, H=32, hd=128, F=14336)
    k0 = summarize(kernel_costs(big, fuse(big, "none")))
    k3 = summarize(kernel_costs(big, fuse(big, "flash")))
    assert k3[2] < 0.5 * k0[2] and k3[3] < k0[3]
    print("graph.py self-test passed")
    print(f"  Llama-8B-like block, 2,048 tokens: {k0[0]} kernels / {k0[2] / 1e9:.2f} GB / {k0[3] * 1e3:.2f} ms unfused -> "
          f"{k3[0]} kernels / {k3[2] / 1e9:.2f} GB / {k3[3] * 1e3:.2f} ms fused (H100 roofline)")
