"""
flash.py -- FlashAttention from scratch: tiled attention with an online softmax (forward), the recomputing backward
pass, DRAM-traffic accounting vs on-chip memory size, causal tile skipping, and split-KV decoding
==================================================================================================================

[Why we need it]
    Standard attention for one head computes S = Q K^T (N x N), P = softmax(S), O = P V. Written as three kernels,
    it stores S and P in DRAM: Theta(N^2) bytes for every head, every layer -- which dominates the traffic of long
    sequences (Lecture 7 found attention's QK^T capped at ~114 FLOP/byte by writing its scores). FlashAttention
    (Dao et al., NeurIPS 2022) computes attention TILE BY TILE in on-chip memory and never writes S or P: for each
    block of queries it streams blocks of keys and values, and keeps a running ("online") softmax -- the row
    maximum m, the row sum l and an unnormalized output accumulator -- rescaling them whenever a new block raises
    the maximum. The result is EXACT (not an approximation): the same numbers as standard attention up to floating-
    point rounding. The backward pass does not store P either: it RECOMPUTES it from Q, K and the saved row
    statistics -- more FLOPs, far less traffic.

[Main pieces]
    attention_ref           : standard attention in float64 (O and the log-sum-exp L of every row)
    flash_forward           : the tiled forward pass; returns O, L and counters (elements read/written, FLOPs,
                              tiles computed / skipped)
    flash_backward          : the tiled backward pass with recomputation; returns dQ, dK, dV and counters
    attention_grads_ref     : reference gradients from the full matrices
    blocks_for_sram         : the block sizes FlashAttention picks for an on-chip memory of M elements
    standard_traffic, flash_traffic : DRAM elements moved, by formula (checked against the counters)
    split_kv_decode         : one query against a long KV cache split into chunks combined exactly
                              (the Flash-Decoding idea), for parallelism at batch 1

[Edge cases]
    - One head at a time: Q, K, V are N x d (Nk x d for keys/values). Multi-head = loop over heads.
    - Causal masking: query i sees keys 0..i (with Nq == Nk). Tiles entirely above the diagonal are skipped.
    - Rows whose keys are all masked cannot occur with causal masking (every query sees itself).
"""

import math
from dataclasses import dataclass, field

import numpy as np


# =====================================================================================================================
# Reference attention
# =====================================================================================================================

def attention_ref(Q, K, V, causal=False, scale=None):
    """
    Standard attention in float64: S = scale Q K^T, P = softmax(S), O = P V.

    [Returns] (O, L) with L[i] = log sum_j exp(S[i, j]) (the row log-sum-exp, needed by the backward pass)
    """
    Q, K, V = (np.asarray(a, dtype=np.float64) for a in (Q, K, V))
    scale = 1 / math.sqrt(Q.shape[1]) if scale is None else scale
    S = scale * Q @ K.T
    if causal:
        S[np.triu(np.ones(S.shape, dtype=bool), 1)] = -np.inf
    m = S.max(1, keepdims=True)
    E = np.exp(S - m)
    lsum = E.sum(1, keepdims=True)
    return (E / lsum) @ V, (m + np.log(lsum)).ravel()


def attention_grads_ref(Q, K, V, dO, causal=False, scale=None):
    """
    Gradients of O = softmax(scale Q K^T) V with respect to Q, K, V for an upstream gradient dO (float64).

    [Idea] dV = P^T dO; dP = dO V^T; dS = P * (dP - rowsum(dP * P)); dQ = scale dS K; dK = scale dS^T Q.
    """
    Q, K, V, dO = (np.asarray(a, dtype=np.float64) for a in (Q, K, V, dO))
    scale = 1 / math.sqrt(Q.shape[1]) if scale is None else scale
    S = scale * Q @ K.T
    if causal:
        S[np.triu(np.ones(S.shape, dtype=bool), 1)] = -np.inf
    P = np.exp(S - S.max(1, keepdims=True))
    P /= P.sum(1, keepdims=True)
    dV = P.T @ dO
    dP = dO @ V.T
    dS = P * (dP - (dP * P).sum(1, keepdims=True))
    return scale * dS @ K, scale * dS.T @ Q, dV


# =====================================================================================================================
# The tiled algorithm
# =====================================================================================================================

@dataclass
class Counters:
    """
    What a tiled kernel did.

    [Fields] reads, writes: DRAM elements; flops: multiply-adds x 2 in the tile matmuls; tiles, skipped: tiles
        computed and tiles skipped by causal masking; rescales: rows whose running max changed (online softmax)
    """
    reads: float = 0.0
    writes: float = 0.0
    flops: float = 0.0
    tiles: int = 0
    skipped: int = 0
    rescales: int = 0
    extra: dict = field(default_factory=dict)

    @property
    def traffic(self):
        return self.reads + self.writes


def flash_forward(Q, K, V, Br=64, Bc=64, causal=False, scale=None, dtype=np.float32):
    """
    FlashAttention's forward pass (the FlashAttention-2 loop order: query blocks outside, key blocks inside).

    [Idea] For a block Qi of Br queries (loaded once), keep per row: m (running max), l (running sum of exp), and
        acc (running sum of exp(s - m) v). For every block (Kj, Vj) of Bc keys:
            S  = scale Qi Kj^T                      (Br x Bc, in on-chip memory)
            m' = max(m, rowmax(S))
            P  = exp(S - m')
            l  = exp(m - m') l + rowsum(P)          (old terms rescaled to the new maximum)
            acc = exp(m - m') acc + P Vj
            m  = m'
        Finally Oi = acc / l and Li = m + log(l). Every term is computed exactly as in the standard algorithm;
        only the ORDER of additions changes -- the result equals softmax(S) V up to rounding.
    [Args] Q (Nq x d), K, V (Nk x d); Br, Bc: block sizes; causal; scale (default 1/sqrt(d)); dtype: arithmetic
        precision of the tiles (float32, as in real kernels' accumulators)
    [Returns] (O, L, Counters) -- Counters count DRAM elements: Qi read once, Kj and Vj once per (i, j) tile
        computed, O and L written once
    """
    Q, K, V = (np.asarray(a, dtype=dtype) for a in (Q, K, V))
    Nq, d = Q.shape
    Nk = K.shape[0]
    scale = dtype(1 / math.sqrt(d) if scale is None else scale)
    O = np.zeros((Nq, d), dtype=dtype)
    L = np.zeros(Nq, dtype=np.float64)
    c = Counters()
    for i0 in range(0, Nq, Br):
        Qi = Q[i0:i0 + Br]
        br = Qi.shape[0]
        c.reads += br * d
        m = np.full(br, -np.inf, dtype=dtype)
        lsum = np.zeros(br, dtype=dtype)
        acc = np.zeros((br, d), dtype=dtype)
        for j0 in range(0, Nk, Bc):
            if causal and j0 > i0 + br - 1:                 # the whole tile is above the diagonal
                c.skipped += 1
                continue
            Kj, Vj = K[j0:j0 + Bc], V[j0:j0 + Bc]
            bc = Kj.shape[0]
            c.reads += 2 * bc * d
            c.tiles += 1
            S = scale * (Qi @ Kj.T)
            if causal:
                rows = np.arange(i0, i0 + br)[:, None]
                cols = np.arange(j0, j0 + bc)[None, :]
                S = np.where(cols > rows, -np.inf, S)
            m_new = np.maximum(m, S.max(1))
            c.rescales += int(np.sum(m_new > m))
            alpha = np.exp(m - m_new)
            P = np.exp(S - m_new[:, None])
            lsum = alpha * lsum + P.sum(1)
            acc = alpha[:, None] * acc + P @ Vj
            m = m_new
            c.flops += 4 * br * bc * d
        O[i0:i0 + br] = acc / lsum[:, None]
        L[i0:i0 + br] = m.astype(np.float64) + np.log(lsum.astype(np.float64))
        c.writes += br * d + br
    return O, L, c


def flash_backward(Q, K, V, O, dO, L, Br=64, Bc=64, causal=False, scale=None, dtype=np.float32):
    """
    FlashAttention's backward pass with recomputation (key blocks outside, as in FlashAttention-2).

    [Idea] Nothing of size N x N was stored. For every tile, recompute S = scale Qi Kj^T and P = exp(S - Li) from
        the saved row log-sum-exp L (no running max needed: L is final). Then, with D_i = rowsum(dO_i * O_i):
            dVj += P^T dOi;   dP = dOi Vj^T;   dS = P * (dP - D_i)
            dKj += scale dS^T Qi;   dQi += scale dS Kj
        Five tile matmuls per tile instead of the standard backward's four: ~25% more FLOPs, no N^2 traffic.
    [Returns] (dQ, dK, dV, Counters)
    """
    Q, K, V, O, dO = (np.asarray(a, dtype=dtype) for a in (Q, K, V, O, dO))
    Nq, d = Q.shape
    Nk = K.shape[0]
    scale = dtype(1 / math.sqrt(d) if scale is None else scale)
    Lf = np.asarray(L, dtype=dtype)
    D = (dO * O).sum(1)
    dQ = np.zeros_like(Q)
    dK = np.zeros_like(K)
    dV = np.zeros_like(V)
    c = Counters()
    for j0 in range(0, Nk, Bc):
        Kj, Vj = K[j0:j0 + Bc], V[j0:j0 + Bc]
        bc = Kj.shape[0]
        c.reads += 2 * bc * d
        dKj = np.zeros_like(Kj)
        dVj = np.zeros_like(Vj)
        for i0 in range(0, Nq, Br):
            if causal and j0 > i0 + Br - 1:
                c.skipped += 1
                continue
            Qi, dOi = Q[i0:i0 + Br], dO[i0:i0 + Br]
            br = Qi.shape[0]
            c.reads += 2 * br * d + 2 * br                      # Qi, dOi, Li, Di
            c.tiles += 1
            S = scale * (Qi @ Kj.T)
            if causal:
                rows = np.arange(i0, i0 + br)[:, None]
                cols = np.arange(j0, j0 + bc)[None, :]
                S = np.where(cols > rows, -np.inf, S)
            P = np.exp(S - Lf[i0:i0 + br, None])
            dVj += P.T @ dOi
            dP = dOi @ Vj.T
            dS = P * (dP - D[i0:i0 + br, None])
            dKj += scale * (dS.T @ Qi)
            dQ[i0:i0 + br] += scale * (dS @ Kj)
            c.reads += br * d                                    # dQi read-modify-write
            c.writes += br * d
            c.flops += 10 * br * bc * d
        dK[j0:j0 + bc], dV[j0:j0 + bc] = dKj, dVj
        c.writes += 2 * bc * d
    return dQ, dK, dV, c


# =====================================================================================================================
# Traffic by formula
# =====================================================================================================================

def blocks_for_sram(M, d):
    """
    Block sizes FlashAttention's paper chooses for an on-chip memory of M elements: Bc = ceil(M / 4d),
    Br = min(Bc, d) -- so that Qi, Kj, Vj and the Br x Bc tile fit together.
    """
    Bc = max(1, math.ceil(M / (4 * d)))
    return min(Bc, d), Bc


def standard_traffic(N, d, causal=False):
    """
    DRAM elements of three-kernel attention for one head: read Q, K, write S; read S, write P; read P, V, write O.
    (Causal masking does not shrink S and P in a standard kernel: they are dense N x N arrays.)
    """
    return (2 * N * d + N * N) + 2 * N * N + (N * N + N * d + N * d)


def flash_traffic(N, d, Br, Bc, causal=False):
    """
    DRAM elements of the FlashAttention forward pass for one head: Q read once, K and V re-read for every query
    block (half the tiles when causal), O and L written once. Equals flash_forward's counters for full blocks.
    """
    tq, tk = math.ceil(N / Br), math.ceil(N / Bc)
    if causal:
        tiles = sum(min(tk, (i * Br + Br - 1) // Bc + 1) for i in range(tq))
    else:
        tiles = tq * tk
    return N * d + tiles * 2 * Bc * d + N * d + N


# =====================================================================================================================
# Split-KV decoding
# =====================================================================================================================

def split_kv_decode(q, K, V, splits, scale=None):
    """
    One query vector against Nk keys, split into `splits` chunks processed independently and combined exactly.

    [Idea] Each chunk c computes its own (m_c, l_c, acc_c) like one step of the online softmax. Combining:
        m = max_c m_c;  l = sum_c exp(m_c - m) l_c;  o = sum_c exp(m_c - m) acc_c / l.
        In decode (one new token per sequence) attention has only batch x heads independent rows -- often fewer
        than the GPU's streaming multiprocessors. Splitting the KV sequence creates more parallel work items
        (Flash-Decoding, Dao et al. 2023) at the cost of a small combine step.
    [Returns] (o, list of per-chunk (m, l)) -- o equals attention_ref on (q, K, V) up to rounding
    """
    q = np.asarray(q, dtype=np.float64)
    K, V = np.asarray(K, dtype=np.float64), np.asarray(V, dtype=np.float64)
    d = q.shape[0]
    scale = 1 / math.sqrt(d) if scale is None else scale
    parts = []
    for chunk in np.array_split(np.arange(K.shape[0]), splits):
        s = scale * K[chunk] @ q
        m = s.max()
        p = np.exp(s - m)
        parts.append((m, p.sum(), p @ V[chunk]))
    M = max(m for m, _, _ in parts)
    lsum = sum(math.exp(m - M) * l for m, l, _ in parts)
    o = sum(math.exp(m - M) * a for m, _, a in parts) / lsum
    return o, [(m, l) for m, l, _ in parts]


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    for N, d, causal in ((128, 32, False), (200, 16, True), (96, 64, True)):
        Q, K, V = (rng.normal(size=(N, d)) for _ in range(3))
        O_ref, L_ref = attention_ref(Q, K, V, causal)
        for Br, Bc in ((16, 16), (32, 64), (64, 32), (N, N)):
            O, L, c = flash_forward(Q, K, V, Br, Bc, causal, dtype=np.float64)
            assert np.allclose(O, O_ref, atol=1e-12) and np.allclose(L, L_ref, atol=1e-10), (N, d, Br, Bc)
            if N % Br == 0 and N % Bc == 0:
                assert c.traffic == flash_traffic(N, d, Br, Bc, causal), (c.traffic, flash_traffic(N, d, Br, Bc, causal))
        # float32 tiles: exact up to float32 rounding
        O32, _, _ = flash_forward(Q, K, V, 32, 32, causal)
        assert np.abs(O32 - O_ref).max() < 1e-5
        # backward with recomputation equals the reference gradients
        dO = rng.normal(size=(N, d))
        gref = attention_grads_ref(Q, K, V, dO, causal)
        O64, L64, _ = flash_forward(Q, K, V, 32, 32, causal, dtype=np.float64)
        g = flash_backward(Q, K, V, O64, dO, L64, 32, 32, causal, dtype=np.float64)
        assert all(np.allclose(a, b, atol=1e-10) for a, b in zip(g[:3], gref))
    # causal skipping halves the tiles (approximately) for long sequences
    Q, K, V = (rng.normal(size=(512, 16)) for _ in range(3))
    _, _, c_full = flash_forward(Q, K, V, 64, 64, False)
    _, _, c_causal = flash_forward(Q, K, V, 64, 64, True)
    assert c_causal.tiles == 36 and c_full.tiles == 64 and c_causal.skipped == 28
    # split-KV decoding is exact
    q, Kd, Vd = rng.normal(size=64), rng.normal(size=(1000, 64)), rng.normal(size=(1000, 64))
    o_ref, _ = attention_ref(q[None, :], Kd, Vd)
    for s in (1, 3, 8, 64):
        assert np.allclose(split_kv_decode(q, Kd, Vd, s)[0], o_ref[0], atol=1e-12)
    # flash traffic falls with SRAM size; standard is N^2-dominated
    assert flash_traffic(4096, 64, *blocks_for_sram(100_000, 64)) < flash_traffic(4096, 64, *blocks_for_sram(10_000, 64))
    assert standard_traffic(4096, 64) > 4 * 4096 * 4096
    print("flash.py self-test passed")
    N, d, M = 4096, 128, 48 * 1024
    Br, Bc = blocks_for_sram(M, d)
    print(f"  N = {N}, d = {d}, SRAM = {M:,} elements -> blocks {Br} x {Bc}: standard {standard_traffic(N, d) / 1e6:.1f} M "
          f"elements, flash {flash_traffic(N, d, Br, Bc) / 1e6:.1f} M per head")
