"""
tiling.py -- how much off-chip traffic a tiled GEMM or convolution needs for a given on-chip buffer, the I/O lower
bound (the sqrt(S) law), and double-buffered transfer/compute pipelines
=================================================================================================================

[Why we need it]
    An accelerator's global buffer holds a few MB; a layer's operands are often larger. The compiler therefore
    cuts the computation into TILES that fit the buffer and orders the tile loops. Every time a tile has to be
    fetched again, it costs DRAM traffic -- the most expensive data movement of all (Lecture 1: ~200x a MAC).
    How much traffic is unavoidable? Hong and Kung (1981) showed that a matrix multiplication with a fast memory of
    S words must move at least ~2 M N K / sqrt(S) words: traffic falls only with the SQUARE ROOT of the buffer.
    This module counts the traffic of any tiling and loop order exactly, finds the best one for a buffer size, and
    models the time of a double-buffered pipeline that overlaps the transfers of the next tile with the
    computation of the current one.

[Main pieces]
    LOOPS, ORDERS                 : the tile loops m, n, k and their 6 orders
    gemm_traffic(...)             : bytes moved for one tiling + loop order (operands re-fetched when evicted)
    gemm_buffer_bytes(...)        : buffer needed by a tiling (optionally double-buffered)
    best_gemm_tiling(...)         : the minimum-traffic tiling and order that fits a buffer
    io_lower_bound(...)           : max(compulsory, 2 M N K / sqrt(S)) elements
    conv_traffic(...), best_conv_tiling(...) : the same for a direct convolution with input halos
    pipeline_time(...)            : time of a tile pipeline with or without double buffering

[The reuse rule] (read this once)
    The buffer holds ONE tile of each operand (two with double buffering). With loop order (outer -> inner), an
    operand stays in the buffer while the loops it does not depend on run INSIDE its innermost dependent loop, and
    is fetched again otherwise. So an operand is fetched once per iteration of every loop at or outside its
    innermost dependent loop: A[m, k] in order (m, n, k) is fetched (M/Tm)(N/Tn)(K/Tk) times -- k is innermost --
    while C[m, n] is fetched (M/Tm)(N/Tn) times and stays put during the k loop (output-stationary).
    C needs care: when the k loop is NOT inside C's residency, the partial sums leave the buffer and come back:
    written once per visit, read back on every visit but the first, in the accumulator precision.

[Edge cases]
    Dimensions not divisible by the tile are handled with ceil(): the last tile is partial (and its transfers
    count only the real elements). Tile sizes are searched over powers of two (and the full dimension).
"""

import itertools
import math
from dataclasses import dataclass

LOOPS = ("m", "n", "k")
ORDERS = ["".join(p) for p in itertools.permutations(LOOPS)]
DEPENDS = {"A": ("m", "k"), "B": ("k", "n"), "C": ("m", "n")}


def _trips(M, N, K, Tm, Tn, Tk):
    return {"m": math.ceil(M / Tm), "n": math.ceil(N / Tn), "k": math.ceil(K / Tk)}


def fetches(order, operand, trips):
    """
    How many times a tile of `operand` is brought into the buffer for a loop order.

    [Args] order: e.g. "mnk" (outermost first); operand: "A", "B" or "C"; trips: dict loop -> trip count
    [Returns] int: product of the trip counts of all loops at or outside the operand's innermost dependent loop
    """
    deps = DEPENDS[operand]
    innermost = max(order.index(d) for d in deps)
    return math.prod(trips[order[i]] for i in range(innermost + 1))


def gemm_traffic(M, N, K, Tm, Tn, Tk, order="mnk", elem=2, acc=4, out=None):
    """
    Off-chip bytes of C[M, N] = A[M, K] @ B[K, N] with tiles Tm x Tn x Tk and a tile-loop order.

    [Idea] See the module docstring. A tile of A is Tm x Tk elements, of B Tk x Tn, of C Tm x Tn. Re-fetches scale
        the full matrix size (every tile of the matrix is fetched the same number of times). For C: if C stays
        resident during the whole k loop (k inside C's innermost dependent loop) it is written once, in the output
        precision; otherwise every visit writes partial sums (accumulator precision) and every visit but the
        first reads them back.
    [Args] M, N, K: GEMM shape; Tm, Tn, Tk: tile shape; order: tile-loop order; elem: bytes per input element;
        acc: bytes per partial sum; out: bytes per final output element (default elem)
    [Returns] dict with "A", "B", "C" and "total" bytes
    """
    out = elem if out is None else out
    t = _trips(M, N, K, Tm, Tn, Tk)
    fa = fetches(order, "A", t) / (t["m"] * t["k"])          # how many times the whole of A is read
    fb = fetches(order, "B", t) / (t["k"] * t["n"])
    a = M * K * elem * fa
    b = K * N * elem * fb
    visits = fetches(order, "C", t) / (t["m"] * t["n"])       # visits per C tile
    if visits == 1:
        c = M * N * out
    else:
        c = M * N * acc * visits + M * N * acc * (visits - 1)  # writes every visit, reads all but the first
    return {"A": a, "B": b, "C": c, "total": a + b + c}


def gemm_buffer_bytes(Tm, Tn, Tk, elem=2, acc=4, double_buffer=False):
    """
    On-chip bytes a tiling needs: one tile of A, B (inputs) and C (partial sums in accumulator precision).

    [Edge cases] double_buffer=True doubles the input tiles (the next A and B tiles arrive while the current ones
        are used); the C tile is double-buffered too (the finished tile drains while the next one accumulates).
    """
    copies = 2 if double_buffer else 1
    return copies * ((Tm * Tk + Tk * Tn) * elem + Tm * Tn * acc)


def _tile_choices(dim, minimum=1):
    """Powers of two from `minimum` up to dim, plus dim itself (for dims that are not powers of two)."""
    out, t = [], 1
    while t < dim:
        if t >= minimum:
            out.append(t)
        t *= 2
    out.append(dim)
    return sorted(set(out))


@dataclass
class Tiling:
    """A tiling: tile shape, loop order, traffic (bytes) and buffer (bytes)."""
    Tm: int
    Tn: int
    Tk: int
    order: str
    traffic: float
    buffer: float
    parts: dict

    def label(self):
        return f"{self.Tm}x{self.Tn}x{self.Tk} {self.order}"


def best_gemm_tiling(M, N, K, buffer_bytes, elem=2, acc=4, double_buffer=False, orders=ORDERS, min_tile=1):
    """
    The minimum-traffic tiling (powers of two) and loop order whose buffer fits buffer_bytes.

    [Args] M, N, K; buffer_bytes; elem, acc: bytes per input element / partial sum; double_buffer; orders: loop
        orders to try; min_tile: smallest tile edge considered (e.g. 32 so that every tile row is at least one
        64-byte DRAM burst of bf16 -- slivers of 1 element minimize traffic on paper but stream badly from DRAM)
    [Returns] Tiling, or None if not even the smallest tiles fit
    [Edge cases] Ties are broken by the smaller buffer. The search is exhaustive over ~log(M) log(N) log(K) x 6
        candidates: instant for layer-sized GEMMs.
    """
    best = None
    for Tm in _tile_choices(M, min_tile):
        for Tn in _tile_choices(N, min_tile):
            for Tk in _tile_choices(K, min_tile):
                buf = gemm_buffer_bytes(Tm, Tn, Tk, elem, acc, double_buffer)
                if buf > buffer_bytes:
                    continue
                for o in orders:
                    tr = gemm_traffic(M, N, K, Tm, Tn, Tk, o, elem, acc)
                    if best is None or (tr["total"], buf) < (best.traffic, best.buffer):
                        best = Tiling(Tm, Tn, Tk, o, tr["total"], buf, tr)
    return best


def io_lower_bound(M, N, K, S_elems):
    """
    Lower bound on the elements moved by ANY schedule of a classical M x N x K matrix multiplication with a fast
    memory of S_elems elements: max(compulsory M K + K N + M N, 2 M N K / sqrt(S)).

    [Idea] (Hong & Kung 1981; tight constant: Smith et al. 2019) With S words on chip, any segment of the
        computation that moves S words in and out can perform at most ~(S)^(3/2) / ... multiply-adds -- the
        Loomis-Whitney inequality bounds how many (i, j, k) triples can be formed from the A, B, C entries
        present. Summing over segments gives traffic >= 2 M N K / sqrt(S).
    """
    return max(M * K + K * N + M * N, 2 * M * N * K / math.sqrt(S_elems))


# =====================================================================================================================
# Convolution
# =====================================================================================================================

def conv_traffic(H, W, C, Kc, R, S, Th, Tw, Tk, Tc, elem=2, acc=4):
    """
    Off-chip bytes of a direct convolution (stride 1, 'same' padding) tiled over output rows/cols/channels and input
    channels, with loop order (output tile outer: h, w, k; input channels c inner) -- output-stationary.

    [Idea] For each output tile Th x Tw x Tk, the input channels are streamed in chunks of Tc: each chunk needs an
        input tile WITH ITS HALO, (Th + R - 1) x (Tw + S - 1) x Tc, and the weights R x S x Tc x Tk. Neighbouring
        output tiles re-read the overlapping halo -- the price of tiling a convolution, which shrinks as tiles grow.
        Outputs are written once (they stay on chip during the c loop).
    [Args] H, W: output size (= input size); C, Kc: input / output channels; R, S: filter size; Th, Tw, Tk, Tc: tiles
    [Returns] dict with "input", "weight", "output", "total" bytes
    """
    nh, nw, nk = math.ceil(H / Th), math.ceil(W / Tw), math.ceil(Kc / Tk)
    inp = nh * nw * nk * (min(Th, H) + R - 1) * (min(Tw, W) + S - 1) * C * elem
    wgt = nh * nw * R * S * C * Kc * elem
    outp = H * W * Kc * elem
    return {"input": inp, "weight": wgt, "output": outp, "total": inp + wgt + outp}


def conv_buffer_bytes(R, S, Th, Tw, Tk, Tc, elem=2, acc=4, double_buffer=False):
    """Buffer for one input tile with halo, one weight tile and one output tile (partial sums)."""
    copies = 2 if double_buffer else 1
    return copies * (((Th + R - 1) * (Tw + S - 1) * Tc + R * S * Tc * Tk) * elem + Th * Tw * Tk * acc)


def best_conv_tiling(H, W, C, Kc, R, S, buffer_bytes, elem=2, acc=4, double_buffer=False):
    """Minimum-traffic (Th, Tw, Tk, Tc) over powers of two that fits; returns (tiling dict, traffic dict) or None."""
    best = None
    for Th in _tile_choices(H):
        for Tw in _tile_choices(W):
            for Tk in _tile_choices(Kc):
                for Tc in _tile_choices(C):
                    buf = conv_buffer_bytes(R, S, Th, Tw, Tk, Tc, elem, acc, double_buffer)
                    if buf > buffer_bytes:
                        continue
                    tr = conv_traffic(H, W, C, Kc, R, S, Th, Tw, Tk, Tc, elem, acc)
                    if best is None or (tr["total"], buf) < (best[1]["total"], best[0]["buffer"]):
                        best = ({"Th": Th, "Tw": Tw, "Tk": Tk, "Tc": Tc, "buffer": buf}, tr)
    return best


def im2col_traffic(H, W, C, Kc, R, S, elem=2):
    """Traffic if the convolution is first lowered to a GEMM in memory: the input is replicated R x S times."""
    return {"input": H * W * R * S * C * elem, "weight": R * S * C * Kc * elem, "output": H * W * Kc * elem}


# =====================================================================================================================
# Double-buffered pipelines
# =====================================================================================================================

def pipeline_time(n_tiles, t_load, t_compute, t_store=0.0, double_buffer=True, latency=0.0):
    """
    Time to process n_tiles tiles, each needing a load, a computation and a store.

    [Idea] Without double buffering the three steps of each tile run one after the other:
            T = n (latency + t_load + t_compute + t_store).
        With double buffering, the load of tile i + 1 and the store of tile i - 1 overlap the computation of
        tile i (the memory channel does loads and stores; the compute unit computes), so in steady state each tile
        costs max(t_compute, t_load + t_store), and only the first load (with its latency) and the last
        computation and store are exposed:
            T = latency + t_load + (n - 1) max(t_compute, t_load + t_store) + t_compute + t_store.
        Double buffering hides memory COMPLETELY when t_load + t_store <= t_compute, i.e. when the tile's
        arithmetic intensity is at least the machine's ridge point (Lecture 1).
    [Args] n_tiles; t_load, t_compute, t_store: seconds per tile; double_buffer; latency: memory latency per
        transfer (exposed once with double buffering, once per tile without)
    [Returns] seconds
    """
    if n_tiles <= 0:
        return 0.0
    if not double_buffer:
        return n_tiles * (latency + t_load + t_compute + t_store)
    return latency + t_load + (n_tiles - 1) * max(t_compute, t_load + t_store) + t_compute + t_store


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

if __name__ == "__main__":
    M = N = K = 1024
    # untiled (everything fits): compulsory traffic
    tr = gemm_traffic(M, N, K, M, N, K, "mnk")
    assert tr["total"] == (M * K + K * N + M * N) * 2
    # order mnk with square tiles: A read N/Tn times, B read M/Tm times, C written once
    tr = gemm_traffic(M, N, K, 128, 128, 64, "mnk")
    assert tr["A"] == M * K * 2 * 8 and tr["B"] == K * N * 2 * 8 and tr["C"] == M * N * 2
    # order mkn: A read once, C partial sums spilled K/Tk times
    tr = gemm_traffic(M, N, K, 128, 128, 64, "mkn")
    assert tr["A"] == M * K * 2 and tr["C"] == M * N * 4 * (16 + 15)
    # the best tiling approaches the lower bound within a small factor, and traffic ~ 1/sqrt(S)
    prev = None
    for S in (64 << 10, 256 << 10, 1 << 20):
        best = best_gemm_tiling(4096, 4096, 4096, S, elem=2, acc=2)
        lb = io_lower_bound(4096, 4096, 4096, S / 2) * 2
        assert lb <= best.traffic <= 2.5 * lb, (S, best.traffic / lb)
        if prev:
            assert 1.6 < prev / best.traffic < 2.4                 # 4x the buffer -> ~2x less traffic
        prev = best.traffic
    # double buffering: fully hidden when loads are shorter than compute
    assert pipeline_time(10, 1.0, 2.0) == 1.0 + 9 * 2.0 + 2.0
    assert pipeline_time(10, 1.0, 2.0, double_buffer=False) == 30.0
    # convolution: tiles with halos cost more input traffic than one big tile, im2col much more
    big = conv_traffic(56, 56, 64, 64, 3, 3, 56, 56, 64, 64)
    small = conv_traffic(56, 56, 64, 64, 3, 3, 8, 8, 64, 64)
    assert small["input"] > big["input"] and im2col_traffic(56, 56, 64, 64, 3, 3)["input"] > 8 * big["input"]
    print("tiling.py self-test passed")
    b = best_gemm_tiling(4096, 4096, 4096, 1 << 20)
    print(f"  4096^3 bf16 GEMM, 1 MiB buffer: best {b.label()}, {b.traffic / 1e6:.0f} MB "
          f"(lower bound {io_lower_bound(4096, 4096, 4096, (1 << 20) / 2) * 2 / 1e6:.0f} MB)")
