"""
vector_unit.py -- a cycle-level multi-lane vector unit: lanes, vector registers, special-function units, reductions,
chaining and in-order issue (the block of Lab 2), plus vector programs for softmax, normalization, activations and
MX block quantization
====================================================================================================================

[Why we need it]
    A matrix unit computes GEMMs; everything else in a network -- softmax, layer/RMS normalization, activation
    functions, residual additions, quantization and dequantization, reductions -- runs on a VECTOR unit: a row of
    identical lanes that apply the same operation to many elements per cycle (SIMD, Lecture 3), with a few
    special-function lanes (SFUs, approx.py) for exp, 1/x, 1/sqrt(x) and tanh, and a reduction tree that combines
    the lanes into one number. Once the matrix unit is fast, these operations decide the speed (Amdahl's law), so
    the vector unit must be sized and programmed carefully. This module simulates one, with real numbers, clock by
    clock at the granularity of "element groups" (the elements one pipe processes in one cycle).

[The machine]
    - Vector registers of `vlen` elements (float32). An instruction operates on its first n elements (n <= vlen).
    - Five pipes, each accepting one element group per cycle:
        ld   : loads from the local vector memory, ld_bytes per cycle (elements per cycle depend on the array's
               element size: a bf16 array delivers ld_bytes / 2 elements)
        st   : stores, st_bytes per cycle
        alu  : `lanes` elements per cycle -- add, sub, mul, fma, max, min, abs, conversions, exponent operations;
               reductions also use these lanes, followed by a tree across lanes
        sfu  : `sfu_lanes` elements per cycle -- exp, recip, rsqrt, tanh
        scalar: one scalar operation per cycle (scalar arithmetic, loop counters, addresses)
    - Latencies: alu_lat, sfu_lat, mem_lat, scalar_lat cycles from issue to result.
    - Decoupled in-order issue: instructions are DISPATCHED in program order, up to issue_width per cycle
      (1 = a single-issue machine; > 1 = VLIW-style bundles), into a small queue in front of their pipe
      (`queue` entries). Each pipe starts its instructions in order, when the pipe is free and the operands are
      ready, so a load can run ahead of the arithmetic -- but a full queue stalls dispatch for everyone.
      queue = 0 gives a strict in-order machine: an instruction cannot start before its predecessor has started.
    - CHAINING (Cray-1, 1976): an instruction may start as soon as the FIRST elements it needs are ready, and each
      later element group waits only for its own operands. Without chaining it waits for the whole source vector.
    - Element group g of an instruction issues at
          t_g = max(t_{g-1} + 1, cycle when group g's operands are ready)
      and its results are ready at t_g + latency. A reduction's result is ready after the last group plus the
      levels of its adder tree. Registers track per-element ready times and last-read times (WAR/WAW hazards).

[Usage]
    import numpy as np, vector_unit as vu
    cfg = vu.VUConfig(lanes=16, sfu_lanes=4)
    x = np.random.default_rng(0).normal(size=(4, 256)).astype(np.float32)
    prog = vu.build("softmax", cfg, rows=4, n=256)
    res = vu.run(cfg, prog, {"x": x.ravel()})
    res.cycles, res.memory["y"].reshape(4, 256)            # compare with a numpy softmax

[Edge cases]
    - A row longer than vlen is processed in chunks of vlen elements and must be a multiple of vlen; a row of at
      most vlen elements is one (possibly short) chunk.
    - Programs that need more vector registers than n_vregs raise ValueError (lower the interleave or vlen).
    - Values are float32; reductions are computed in float64 and rounded once (an idealized adder tree).
    - The simulator steps per instruction, not per cycle: thousands of instructions run in well under a second.
"""

import math
from dataclasses import dataclass, field, replace

import numpy as np

import course_path

course_path.use("lecture01", "lecture04")

import numfmt as nf  # noqa: E402

F32 = np.float32

# Which pipe executes each operation. Reductions ("red") execute on the ALU lanes.
UNIT = {
    "vld": "ld", "vst": "st",
    "vadd": "alu", "vsub": "alu", "vmul": "alu", "vfma": "alu", "vmax": "alu", "vmin": "alu", "vabs": "alu",
    "vmov": "alu", "vcvt": "alu", "vexpand": "alu", "vexpo": "alu", "vscale2": "alu",
    "vexp": "sfu", "vrecip": "sfu", "vrsqrt": "sfu", "vtanh": "sfu",
    "vredsum": "alu", "vredmax": "alu", "vsegsum": "alu", "vsegmax": "alu",
    "sadd": "scalar", "smul": "scalar", "srecip": "scalar", "srsqrt": "scalar", "sop": "scalar",
}
REDUCTIONS = {"vredsum", "vredmax", "vsegsum", "vsegmax"}
SFU_FUNCS = {"vexp": "exp", "vrecip": "recip", "vrsqrt": "rsqrt", "vtanh": "tanh", "srecip": "recip",
             "srsqrt": "rsqrt"}


@dataclass
class VUConfig:
    """
    Parameters of the vector unit.

    [Fields]
        name        : label
        lanes       : ALU elements per cycle
        sfu_lanes   : special-function elements per cycle (GPUs have 16 SFU lanes per 128 FP32 lanes per SM)
        vlen        : elements per vector register; n_vregs: number of vector registers
        alu_lat, sfu_lat, mem_lat, scalar_lat : pipeline latencies in cycles
        ld_bytes, st_bytes : local-memory bytes per cycle for loads and for stores
        chaining    : start dependent instructions element group by element group (True) or only when the whole
                      source vector is ready (False)
        issue_width : instructions dispatched per cycle (1 = single issue; > 1 = VLIW-style bundles)
        queue       : instructions that may wait in front of each pipe (0 = strict in-order start)
        funcs       : optional {"exp": f, "recip": f, "rsqrt": f, "tanh": f} hardware approximations (approx.py);
                      a missing entry means "exact, rounded to float32"
    [Python tip] field(default_factory=dict) gives each config its own dict; dataclasses.replace(cfg, lanes=32)
        makes a modified copy.
    """
    name: str = "VU"
    lanes: int = 16
    sfu_lanes: int = 4
    vlen: int = 256
    n_vregs: int = 32
    alu_lat: int = 4
    sfu_lat: int = 19
    mem_lat: int = 2
    scalar_lat: int = 4
    ld_bytes: int = 64
    st_bytes: int = 64
    chaining: bool = True
    issue_width: int = 1
    queue: int = 8
    funcs: dict = field(default_factory=dict)

    def width(self, unit, elem_bytes=4):
        """Elements per cycle of a pipe (loads/stores depend on the element size of the array)."""
        if unit == "alu":
            return self.lanes
        if unit == "sfu":
            return self.sfu_lanes
        if unit == "ld":
            return max(1, int(self.ld_bytes / elem_bytes))
        if unit == "st":
            return max(1, int(self.st_bytes / elem_bytes))
        return 1

    def latency(self, op):
        """Latency of an operation (scalar reciprocal / rsqrt use a scalar special-function unit: sfu_lat)."""
        unit = UNIT[op]
        if op in ("srecip", "srsqrt"):
            return self.sfu_lat
        return {"alu": self.alu_lat, "sfu": self.sfu_lat, "ld": self.mem_lat, "st": self.mem_lat,
                "scalar": self.scalar_lat}[unit]


@dataclass
class Instr:
    """
    One instruction.

    [Fields]
        op   : operation name (a key of UNIT)
        dst  : destination register ("v..." vector, "s..." scalar) or None (stores, "sop")
        srcs : source registers or float immediates (a scalar register or immediate is broadcast to all elements)
        n    : number of elements processed (input elements for reductions); 1 for scalar operations
        mem  : (array name, element offset) for vld / vst
        arg  : extra argument -- segment size for vsegsum/vsegmax/vexpand, a numfmt format for vcvt
    """
    op: str
    dst: str = None
    srcs: tuple = ()
    n: int = 1
    mem: tuple = None
    arg: object = None


class Prog:
    """
    A list of instructions with small helper methods, so programs read like assembly:
        p = Prog(); p.vld("v0", "x", 0, 256); p.v("vexp", "v1", "v0", n=256); p.red("vredsum", "s0", "v1", 256)

    [Python tip] Each helper returns self, so calls can be chained: p.vld(...).v(...).
    """

    def __init__(self):
        self.instrs = []

    def vld(self, dst, array, off, n):
        self.instrs.append(Instr("vld", dst, (), n, (array, off)))
        return self

    def vst(self, src, array, off, n):
        self.instrs.append(Instr("vst", None, (src,), n, (array, off)))
        return self

    def v(self, op, dst, *srcs, n, arg=None):
        self.instrs.append(Instr(op, dst, tuple(srcs), n, None, arg))
        return self

    def red(self, op, dst, src, n, seg=None):
        self.instrs.append(Instr(op, dst, (src,), n, None, seg))
        return self

    def s(self, op, dst=None, *srcs):
        self.instrs.append(Instr(op, dst, tuple(srcs), 1))
        return self

    def __len__(self):
        return len(self.instrs)


@dataclass
class VURun:
    """
    Outcome of running a program.

    [Fields]
        cycles   : cycle at which the last result (store or register) is complete
        memory   : the memory after the run (dict array name -> float32 array)
        busy     : element groups issued per pipe (= cycles that pipe was busy)
        n_instr  : instructions executed
        sregs    : final scalar registers (handy for tests)
        trace    : per-instruction timing records (run(..., trace=True))
    [Methods] utilization(unit) = busy[unit] / cycles
    """
    cycles: int
    memory: dict
    busy: dict
    n_instr: int
    sregs: dict
    trace: list = field(default_factory=list)

    def utilization(self, unit):
        return self.busy.get(unit, 0) / self.cycles if self.cycles else 0.0


# =====================================================================================================================
# Functional semantics
# =====================================================================================================================

def _sfu(cfg, name, x):
    """A special function: the configured approximation, or the exact value rounded to float32."""
    f = cfg.funcs.get(name)
    if f is not None:
        return np.asarray(f(x), dtype=F32)
    x64 = np.asarray(x, dtype=np.float64)
    with np.errstate(divide="ignore", over="ignore", invalid="ignore"):
        exact = {"exp": np.exp, "recip": lambda v: 1 / v, "rsqrt": lambda v: 1 / np.sqrt(v), "tanh": np.tanh}
        return exact[name](x64).astype(F32)


def _exponent(a):
    """floor(log2 |a|) read from the exponent field (frexp is exact); zero -> -127 (MX convention for a zero block)."""
    _, E = np.frexp(np.abs(a.astype(np.float64)))
    return np.where(a == 0, -127.0, E - 1).astype(F32)


def _compute(cfg, ins, ops):
    """
    The result of one instruction, given its operand values (float32 arrays of length n, or scalars).

    [Returns] float32 array (vector results) or a float32 scalar (scalar results and full reductions)
    """
    op = ins.op
    a = ops[0] if ops else None
    if op in ("vadd", "sadd"):
        return (a + ops[1]).astype(F32)
    if op == "vsub":
        return (a - ops[1]).astype(F32)
    if op in ("vmul", "smul"):
        return (a * ops[1]).astype(F32)
    if op == "vfma":                                          # fused: one rounding
        return (a.astype(np.float64) * ops[1] + ops[2]).astype(F32)
    if op == "vmax":
        return np.maximum(a, ops[1]).astype(F32)
    if op == "vmin":
        return np.minimum(a, ops[1]).astype(F32)
    if op == "vabs":
        return np.abs(a).astype(F32)
    if op == "vmov":
        return np.asarray(a, dtype=F32).copy()
    if op == "vcvt":                                          # round to a narrower format (saturating)
        return nf.quantize(a, ins.arg, saturate=True).astype(F32)
    if op == "vexpo":
        return _exponent(a)
    if op == "vscale2":                                       # a * 2^b with integer b: an exponent addition
        return np.ldexp(a.astype(np.float64), np.asarray(ops[1], dtype=np.float64).astype(np.int64)).astype(F32)
    if op == "vexpand":                                       # repeat each element `arg` times
        return np.repeat(a, ins.arg)[:ins.n].astype(F32)
    if op in SFU_FUNCS:
        return _sfu(cfg, SFU_FUNCS[op], a)
    if op == "vredsum":
        return F32(a.astype(np.float64).sum())
    if op == "vredmax":
        return F32(a.max())
    if op in ("vsegsum", "vsegmax"):
        seg = a.reshape(-1, ins.arg)
        return (seg.astype(np.float64).sum(1) if op == "vsegsum" else seg.max(1)).astype(F32)
    if op == "sop":
        return None
    raise ValueError(f"unknown operation {op!r}")


# =====================================================================================================================
# The simulator
# =====================================================================================================================

def _out_len(ins):
    """Elements written by an instruction (segmented reductions shrink the vector; expansions grow it)."""
    if ins.op in ("vsegsum", "vsegmax"):
        return ins.n // ins.arg
    return ins.n


def _src_index(ins, n):
    """For each processed element, which element of the (first) source it reads (vexpand reads e // seg)."""
    idx = np.arange(n)
    return idx // ins.arg if ins.op == "vexpand" else idx


def run(cfg, prog, memory, elem_bytes=None, max_instr=None, trace=False):
    """
    Execute a program on the vector unit and time it.

    [Args]
        cfg        : VUConfig
        prog       : Prog (or a list of Instr)
        memory     : dict array name -> 1-D array of inputs (copied; outputs are created by stores on demand)
        elem_bytes : dict array name -> bytes per element in memory (sets load/store throughput); default 4
        max_instr  : optional safety limit on the number of instructions
        trace      : record, per instruction, its dispatch cycle, first and last group issue, and completion
    [Returns] VURun (with .trace = list of dicts when trace=True)
    [Edge cases] A program reading a register it never wrote reads zeros (and a warning-free result) -- a bug in
        the program, not in the machine; the kernels below never do it. Unknown operations raise ValueError.
    """
    instrs = prog.instrs if isinstance(prog, Prog) else list(prog)
    if max_instr and len(instrs) > max_instr:
        raise ValueError("program too long")
    elem_bytes = elem_bytes or {}
    mem = {k: np.asarray(v, dtype=F32).copy() for k, v in memory.items()}
    vregs, sregs = {}, {}
    vready, vread, sready = {}, {}, {}
    fu_free = {u: 0 for u in ("ld", "st", "alu", "sfu", "scalar")}
    busy = {u: 0 for u in fu_free}
    mem_ready = {}
    dispatched = {}                                   # cycle -> instructions dispatched in that cycle
    last_dispatch = last_start = 0
    pipe_starts = {u: [] for u in fu_free}            # start cycle of every instruction, per pipe, in order
    records = []
    end = 0
    names = {d for ins in instrs for d in [ins.dst] + list(ins.srcs) if isinstance(d, str) and d.startswith("v")}
    if len(names) > cfg.n_vregs:
        raise ValueError(f"program uses {len(names)} vector registers, the unit has {cfg.n_vregs}")

    def vreg_ready(r):
        if r not in vready:
            vready[r] = np.zeros(cfg.vlen)
            vread[r] = np.zeros(cfg.vlen)
            vregs[r] = np.zeros(cfg.vlen, dtype=F32)
        return vready[r]

    def finish(cycle):
        """Note an instruction's completion cycle (for the program's end and the trace)."""
        nonlocal end
        end = max(end, cycle)
        if trace:
            records[-1]["done"] = max(records[-1].get("done", 0), cycle)

    for ins in instrs:
        op, unit = ins.op, UNIT[ins.op]
        lat = cfg.latency(op)
        n = ins.n
        if n > cfg.vlen and unit != "scalar":
            raise ValueError(f"{op}: {n} elements exceed vlen = {cfg.vlen}")
        eb = elem_bytes.get(ins.mem[0], 4) if ins.mem else 4
        w = cfg.width(unit, eb)
        G = math.ceil(n / w)
        # ---- when is each element group's input ready? -----------------------------------------------------------
        elem_need = np.zeros(n)
        for k, s in enumerate(ins.srcs):
            if isinstance(s, str) and s.startswith("v"):
                r = vreg_ready(s)
                idx = _src_index(ins, n) if k == 0 else np.arange(n)
                need = r[idx]
                elem_need = np.maximum(elem_need, need if cfg.chaining else need.max(initial=0))
            elif isinstance(s, str):
                elem_need = np.maximum(elem_need, sready.get(s, 0))
        if op == "vld":
            elem_need = np.maximum(elem_need, mem_ready.get(ins.mem[0], 0))
        pad = np.full(G * w, -np.inf)
        pad[:n] = elem_need
        need = pad.reshape(G, w).max(axis=1)
        # ---- structural, ordering and hazard constraints on the first group --------------------------------------
        # dispatch: in program order, issue_width per cycle, only when the pipe's queue has room
        d = last_dispatch
        if cfg.queue == 0:
            d = max(d, last_start)
        elif len(pipe_starts[unit]) >= cfg.queue:
            d = max(d, pipe_starts[unit][-cfg.queue])
        while dispatched.get(d, 0) >= cfg.issue_width:
            d += 1
        dispatched[d] = dispatched.get(d, 0) + 1
        last_dispatch = d
        lb = max(d, fu_free[unit])
        out_n = _out_len(ins)
        if ins.dst and ins.dst.startswith("v"):
            vreg_ready(ins.dst)
            lb = max(lb, vread[ins.dst][:out_n].max(initial=0) - lat + 1,           # WAR: old readers first
                     vready[ins.dst][:out_n].max(initial=0) - lat + 1)              # WAW: writes in order
        need[0] = max(need[0], lb)
        ar = np.arange(G)
        t = np.maximum.accumulate(need - ar) + ar                                     # t_g >= t_{g-1} + 1
        t = t.astype(np.int64)
        pipe_starts[unit].append(int(t[0]))
        last_start = int(t[0])
        fu_free[unit] = int(t[-1]) + 1
        busy[unit] += G
        elem_t = np.repeat(t, w)[:n]                                                  # issue cycle of each element
        if trace:
            records.append({"op": op, "dst": ins.dst or (ins.srcs[0] if ins.srcs else ""), "unit": unit,
                            "dispatch": d, "start": int(t[0]), "last": int(t[-1])})
        # ---- record reads ----------------------------------------------------------------------------------------
        for k, s in enumerate(ins.srcs):
            if isinstance(s, str) and s.startswith("v"):
                idx = _src_index(ins, n) if k == 0 else np.arange(n)
                np.maximum.at(vread[s], idx, elem_t)
        # ---- compute values --------------------------------------------------------------------------------------
        def val(s):
            if isinstance(s, str) and s.startswith("v"):
                return vregs[s][:n] if ins.op != "vexpand" else vregs[s][:math.ceil(n / ins.arg)]
            if isinstance(s, str):
                return sregs.get(s, F32(0))
            return F32(s)

        if op == "vld":
            arr, off = ins.mem
            src = mem[arr][off:off + n]
            if len(src) < n:
                raise ValueError(f"vld past the end of array {arr!r}")
            vregs[ins.dst][:n] = src
            vready[ins.dst][:n] = elem_t + lat
            finish(int(elem_t[-1]) + lat)
            continue
        if op == "vst":
            arr, off = ins.mem
            if arr not in mem:
                mem[arr] = np.zeros(off + n, dtype=F32)
            if len(mem[arr]) < off + n:
                mem[arr] = np.concatenate([mem[arr], np.zeros(off + n - len(mem[arr]), dtype=F32)])
            mem[arr][off:off + n] = val(ins.srcs[0])
            done = int(t[-1]) + lat
            mem_ready[arr] = max(mem_ready.get(arr, 0), done)
            finish(done)
            continue
        result = _compute(cfg, ins, [val(s) for s in ins.srcs])
        if op in REDUCTIONS:
            span = min(n, cfg.lanes) if op in ("vredsum", "vredmax") else min(ins.arg, cfg.lanes)
            per_set = G if op in ("vredsum", "vredmax") else math.ceil(ins.arg / cfg.lanes)
            levels = math.ceil(math.log2(max(span, 1))) + math.ceil(math.log2(max(min(per_set, lat), 1)))
            if op in ("vredsum", "vredmax"):
                sregs[ins.dst] = result
                sready[ins.dst] = int(t[-1]) + lat * (1 + levels)
                finish(sready[ins.dst])
            else:
                seg = ins.arg
                last_elem_t = elem_t[seg - 1::seg]                                    # group of each segment's end
                vregs[ins.dst][:out_n] = result
                vready[ins.dst][:out_n] = last_elem_t + lat * (1 + levels)
                finish(int(vready[ins.dst][:out_n].max()))
            continue
        if unit == "scalar":
            if ins.dst:
                sregs[ins.dst] = F32(result)
                sready[ins.dst] = int(t[0]) + lat
                finish(sready[ins.dst])
            continue
        vregs[ins.dst][:n] = result
        vready[ins.dst][:n] = elem_t + lat
        finish(int(elem_t[-1]) + lat)
    return VURun(end, mem, busy, len(instrs), sregs, records)


def bound(cfg, prog, elem_bytes=None):
    """
    Throughput lower bound on the cycles of a program: the busiest pipe, or the issue rate.

    [Idea] Each pipe accepts one element group per cycle, so cycles >= groups on the busiest pipe; and at most
        issue_width instructions are dispatched per cycle. The simulator adds latencies, dependences and stalls.
    [Returns] (cycles, name of the binding resource)
    """
    elem_bytes = elem_bytes or {}
    groups = {u: 0 for u in ("ld", "st", "alu", "sfu", "scalar")}
    for ins in (prog.instrs if isinstance(prog, Prog) else prog):
        unit = UNIT[ins.op]
        eb = elem_bytes.get(ins.mem[0], 4) if ins.mem else 4
        groups[unit] += math.ceil(ins.n / cfg.width(unit, eb))
    groups["issue"] = math.ceil(len(prog) / cfg.issue_width)
    key = max(groups, key=groups.get)
    return groups[key], key


# =====================================================================================================================
# Vector programs (kernels)
# =====================================================================================================================
# Every kernel processes `rows` rows of n elements stored row after row in 1-D arrays. A kernel generator returns,
# for one row, a list of PHASES (lists of instructions). build() emits the phases of `interleave` rows phase by
# phase (row a's phase 1, row b's phase 1, row a's phase 2, ...): a software-pipelining trick that lets one row's
# latencies overlap other rows' work on an in-order machine. Rows of one interleave group use different
# registers: vector registers are named "vr<slot>_<name>", scalar registers "sr<slot>_<name>" (the first letter
# tells the simulator which register file a name belongs to).

def _chunks(cfg, n):
    """(offset, length) of the vlen-sized chunks of a row; long rows must be multiples of vlen."""
    if n <= cfg.vlen:
        return [(0, n)]
    if n % cfg.vlen:
        raise ValueError(f"rows longer than vlen ({cfg.vlen}) must be a multiple of it, got {n}")
    return [(c * cfg.vlen, cfg.vlen) for c in range(n // cfg.vlen)]


def _combine(ph, op, acc, regs, m):
    """Element-wise combine of chunk registers into acc (acc = op(r0, r1), then op(acc, r_c)); returns acc's name."""
    if len(regs) == 1:
        return regs[0]
    ph.append(Instr(op, acc, (regs[0], regs[1]), m))
    for r in regs[2:]:
        ph.append(Instr(op, acc, (acc, r), m))
    return acc


def k_softmax(cfg, r, n, P):
    """softmax(x) row by row: max-reduce, subtract and exp, sum-reduce, one reciprocal, scale. Arrays x -> y."""
    ch = _chunks(cfg, n)
    m = ch[0][1]
    X = [f"v{P}x{c}" for c in range(len(ch))]
    E = [f"v{P}e{c}" for c in range(len(ch))]
    p1 = [Instr("vld", X[c], (), m, ("x", r * n + off)) for c, (off, _) in enumerate(ch)]
    p2 = []
    acc = _combine(p2, "vmax", f"v{P}t", X, m)
    p2.append(Instr("vredmax", f"s{P}max", (acc,), m))
    p3 = []
    for c in range(len(ch)):
        p3.append(Instr("vsub", X[c], (X[c], f"s{P}max"), m))
        p3.append(Instr("vexp", E[c], (X[c],), m))
    p4 = []                                        # a separate phase, so other rows' exps cover the SFU latency
    acc = _combine(p4, "vadd", f"v{P}t", E, m)
    p4.append(Instr("vredsum", f"s{P}sum", (acc,), m))
    p5 = [Instr("srecip", f"s{P}inv", (f"s{P}sum",), 1)]
    p6 = []
    for c, (off, _) in enumerate(ch):
        p6.append(Instr("vmul", X[c], (E[c], f"s{P}inv"), m))
        p6.append(Instr("vst", None, (X[c],), m, ("y", r * n + off)))
    return [p1, p2, p3, p4, p5, p6]


def k_rmsnorm(cfg, r, n, P, eps=1e-5):
    """RMSNorm: y = x / sqrt(mean(x^2) + eps) * g. The gain g is loaded once (shared registers "vg<c>")."""
    ch = _chunks(cfg, n)
    m = ch[0][1]
    X = [f"v{P}x{c}" for c in range(len(ch))]
    p1 = [Instr("vld", X[c], (), m, ("x", r * n + off)) for c, (off, _) in enumerate(ch)]
    p2 = [Instr("vmul", f"v{P}t", (X[0], X[0]), m)]
    for c in range(1, len(ch)):
        p2.append(Instr("vfma", f"v{P}t", (X[c], X[c], f"v{P}t"), m))
    p2.append(Instr("vredsum", f"s{P}ss", (f"v{P}t",), m))
    p3 = [Instr("smul", f"s{P}ss", (f"s{P}ss", 1.0 / n), 1), Instr("sadd", f"s{P}ss", (f"s{P}ss", eps), 1),
          Instr("srsqrt", f"s{P}r", (f"s{P}ss",), 1)]
    p4 = []
    for c, (off, _) in enumerate(ch):
        p4.append(Instr("vmul", X[c], (X[c], f"s{P}r"), m))
        p4.append(Instr("vmul", X[c], (X[c], f"vg{c}"), m))
        p4.append(Instr("vst", None, (X[c],), m, ("y", r * n + off)))
    return [p1, p2, p3, p4]


def k_layernorm(cfg, r, n, P, eps=1e-5):
    """LayerNorm: y = (x - mean) / sqrt(var + eps) * g + b (two reductions: the sum, then the sum of squares)."""
    ch = _chunks(cfg, n)
    m = ch[0][1]
    X = [f"v{P}x{c}" for c in range(len(ch))]
    p1 = [Instr("vld", X[c], (), m, ("x", r * n + off)) for c, (off, _) in enumerate(ch)]
    p2 = []
    acc = _combine(p2, "vadd", f"v{P}t", X, m)
    p2.append(Instr("vredsum", f"s{P}1", (acc,), m))
    p3 = [Instr("smul", f"s{P}mu", (f"s{P}1", 1.0 / n), 1)]
    p4 = []
    for c in range(len(ch)):
        p4.append(Instr("vsub", X[c], (X[c], f"s{P}mu"), m))
    p4.append(Instr("vmul", f"v{P}t", (X[0], X[0]), m))
    for c in range(1, len(ch)):
        p4.append(Instr("vfma", f"v{P}t", (X[c], X[c], f"v{P}t"), m))
    p4.append(Instr("vredsum", f"s{P}2", (f"v{P}t",), m))
    p5 = [Instr("smul", f"s{P}2", (f"s{P}2", 1.0 / n), 1), Instr("sadd", f"s{P}2", (f"s{P}2", eps), 1),
          Instr("srsqrt", f"s{P}r", (f"s{P}2",), 1)]
    p6 = []
    for c, (off, _) in enumerate(ch):
        p6.append(Instr("vmul", X[c], (X[c], f"s{P}r"), m))
        p6.append(Instr("vfma", X[c], (X[c], f"vg{c}", f"vb{c}"), m))
        p6.append(Instr("vst", None, (X[c],), m, ("y", r * n + off)))
    return [p1, p2, p3, p4, p5, p6]


def k_swiglu(cfg, r, n, P):
    """
    SwiGLU's element-wise part: y = silu(gate) * up, with silu(g) = g * (0.5 + 0.5 tanh(g / 2)). Arrays x (gate),
    u (up) -> y. Phases: loads | ALU before the SFU | tanh | ALU after the SFU + store, so that interleaving rows
    (or the chunks of a long row) fills the SFU's latency with other work.
    """
    p1, p2, p3, p4 = [], [], [], []
    for c, (off, m) in enumerate(_chunks(cfg, n)):
        G, U, T = f"v{P}g{c}", f"v{P}u{c}", f"v{P}t{c}"
        p1 += [Instr("vld", G, (), m, ("x", r * n + off)), Instr("vld", U, (), m, ("u", r * n + off))]
        p2 += [Instr("vmul", T, (G, 0.5), m)]
        p3 += [Instr("vtanh", T, (T,), m)]
        p4 += [Instr("vfma", T, (T, 0.5, 0.5), m), Instr("vmul", T, (T, G), m), Instr("vmul", T, (T, U), m),
               Instr("vst", None, (T,), m, ("y", r * n + off))]
    return [p1, p2, p3, p4]


def k_gelu(cfg, r, n, P):
    """GELU, tanh form: 0.5 x (1 + tanh(sqrt(2/pi) x (1 + 0.044715 x^2))). Arrays x -> y. Phases as in k_swiglu."""
    k = math.sqrt(2 / math.pi)
    p1, p2, p3, p4 = [], [], [], []
    for c, (off, m) in enumerate(_chunks(cfg, n)):
        X, T, A = f"v{P}x{c}", f"v{P}t{c}", f"v{P}a{c}"
        p1 += [Instr("vld", X, (), m, ("x", r * n + off))]
        p2 += [Instr("vmul", A, (X, X), m), Instr("vfma", A, (A, 0.044715, 1.0), m), Instr("vmul", T, (X, k), m),
               Instr("vmul", T, (T, A), m)]
        p3 += [Instr("vtanh", T, (T,), m)]
        p4 += [Instr("vfma", T, (T, 0.5, 0.5), m), Instr("vmul", T, (T, X), m),
               Instr("vst", None, (T,), m, ("y", r * n + off))]
    return [p1, p2, p3, p4]


def k_residual(cfg, r, n, P):
    """Residual addition y = x + u. Phases: loads | add + store."""
    p1, p2 = [], []
    for c, (off, m) in enumerate(_chunks(cfg, n)):
        X, U = f"v{P}x{c}", f"v{P}u{c}"
        p1 += [Instr("vld", X, (), m, ("x", r * n + off)), Instr("vld", U, (), m, ("u", r * n + off))]
        p2 += [Instr("vadd", X, (X, U), m), Instr("vst", None, (X,), m, ("y", r * n + off))]
    return [p1, p2]


def k_mx_quantize(cfg, r, n, P, fmt=nf.MXFP8_E4M3):
    """
    MX block quantization of activations (OCP MX v1.0): for each block of 32, X = floor(log2 max|x|) - emax_elem;
    element codes = convert(x / 2^X). Arrays x -> q (element values, i.e. decoded codes) and e (one exponent per
    block). q * 2^e reproduces numfmt.mx_quantize exactly. Phases: load | |x| and block max | the shared exponent
    (short vectors: one element per block -- per-block work costs 1/32 of an operation per element, so it is done
    BEFORE expanding the exponents back to full length) | scale, convert, store.
    """
    B = fmt.block
    p1, p2, p3, p4 = [], [], [], []
    for c, (off, m) in enumerate(_chunks(cfg, n)):
        if m % B:
            raise ValueError(f"chunk length {m} must be a multiple of the MX block size {B}")
        X, A, S, N, E = f"v{P}x{c}", f"v{P}a{c}", f"v{P}s{c}", f"v{P}n{c}", f"v{P}e{c}"
        p1 += [Instr("vld", X, (), m, ("x", r * n + off))]
        p2 += [Instr("vabs", A, (X,), m),
               Instr("vsegmax", S, (A,), m, None, B)]                      # one max per block
        p3 += [Instr("vexpo", S, (S,), m // B),                             # floor(log2(amax))
               Instr("vsub", S, (S, float(fmt.elem_emax)), m // B),        # shared exponent X
               Instr("vmax", S, (S, -127.0), m // B),                      # clamp to the E8M0 range
               Instr("vmin", S, (S, 127.0), m // B),
               Instr("vsub", N, (0.0, S), m // B)]                         # -X, still one element per block
        p4 += [Instr("vexpand", E, (N,), m, None, B),                      # broadcast to the block's elements
               Instr("vscale2", A, (X, E), m),                             # x * 2^-X (exponent subtraction)
               Instr("vcvt", A, (A,), m, None, fmt.elem),                  # round + saturate to the element format
               Instr("vst", None, (A,), m, ("q", r * n + off)),
               Instr("vst", None, (S,), m // B, ("e", (r * n + off) // B))]
    return [p1, p2, p3, p4]


def k_mx_dequantize(cfg, r, n, P, fmt=nf.MXFP4):
    """
    Dequantize MX weights to bf16-valued float32: y = decode(q) * 2^e. Arrays q (codes; here stored as their decoded
    element values), e (block exponents) -> y. The decode of the narrow code is counted as one ALU conversion.
    """
    B = fmt.block
    out = []
    for c, (off, m) in enumerate(_chunks(cfg, n)):
        Q, S, E = f"v{P}q{c}", f"v{P}s{c}", f"v{P}e{c}"
        out += [Instr("vld", Q, (), m, ("q", r * n + off)),
                Instr("vld", S, (), m // B, ("e", (r * n + off) // B)),
                Instr("vcvt", Q, (Q,), m, None, fmt.elem),                  # code -> value (exact here)
                Instr("vexpand", E, (S,), m, None, B),
                Instr("vscale2", Q, (Q, E), m),
                Instr("vst", None, (Q,), m, ("y", r * n + off))]
    return [out]


KERNELS = {"softmax": k_softmax, "rmsnorm": k_rmsnorm, "layernorm": k_layernorm, "swiglu": k_swiglu,
           "gelu": k_gelu, "residual": k_residual, "mx_quantize": k_mx_quantize, "mx_dequantize": k_mx_dequantize}

# Element sizes in memory used by the kernels: bf16 activations, MXFP8/MXFP4 codes, E8M0 exponents.
DEFAULT_ELEM_BYTES = {"x": 2, "u": 2, "y": 2, "g": 2, "b": 2, "q": 1, "e": 1}


def build(kernel, cfg, rows, n, interleave=1, order="row", loop_overhead=0, **kw):
    """
    The vector program of a kernel over `rows` rows of n elements.

    [Idea] Software pipelining for an in-order machine: with interleave = k, k rows are processed together, phase
        by phase, each row in its own registers, so that one row's reduction-tree or SFU latency is filled with
        the other rows' work, and the next row never waits for registers still being read by the previous one.
        (The pipes' dispatch queues let loads run ahead of the arithmetic; interleaving supplies independent work.)
        Inside a phase, two orders:
        - order="row": row a's instructions of the phase, then row b's (good when each instruction runs for many
          cycles: long vectors keep a pipe busy while the next row's operands arrive);
        - order="round_robin": row a's 1st instruction, row b's 1st, ..., then the 2nd of each (needed when each
          instruction takes ONE cycle -- short vectors or very wide units -- so consecutive instructions on a pipe
          must be independent to hide its latency).
    [Args]
        kernel        : a key of KERNELS
        cfg           : VUConfig (vlen sets the chunking)
        rows, n       : the data shape
        interleave    : rows processed together, phase by phase
        order         : "row" or "round_robin" (see above)
        loop_overhead : scalar bookkeeping instructions ("sop": address increment, loop counter, branch) emitted
                        after every load -- what a scalar core without hardware loops or address generators must
                        issue for each chunk of data
        kw            : kernel options (eps, fmt)
    [Returns] Prog
    [Edge cases] rmsnorm/layernorm load their gain (and bias) vectors once at the start, into registers vg<c>, vb<c>.
        run() raises ValueError if interleaved rows need more than n_vregs registers.
    """
    if order not in ("row", "round_robin"):
        raise ValueError("order must be 'row' or 'round_robin'")
    gen = KERNELS[kernel]
    p = Prog()
    if kernel in ("rmsnorm", "layernorm"):
        for c, (off, m) in enumerate(_chunks(cfg, n)):
            p.vld(f"vg{c}", "g", off, m)
            if kernel == "layernorm":
                p.vld(f"vb{c}", "b", off, m)
    for r0 in range(0, rows, interleave):
        group = [gen(cfg, r, n, f"r{r - r0}_", **kw) for r in range(r0, min(r0 + interleave, rows))]
        for k in range(len(group[0])):
            if order == "row":
                seq = [ins for ph in group for ins in ph[k]]
            else:
                seq = [ph[k][i] for i in range(max(len(ph[k]) for ph in group)) for ph in group if i < len(ph[k])]
            for ins in seq:
                p.instrs.append(ins)
                if loop_overhead and ins.op == "vld":
                    p.instrs.extend(Instr("sop") for _ in range(loop_overhead))
    return p


def reference(kernel, inputs, n, eps=1e-5, fmt=None):
    """
    numpy reference results of a kernel (float64), for checking the vector unit.

    [Args] kernel; inputs: dict of 1-D input arrays (as given to run); n: row length
    [Returns] dict output array name -> expected values
    """
    x = np.asarray(inputs["x"], dtype=np.float64).reshape(-1, n) if "x" in inputs else None
    if kernel == "softmax":
        e = np.exp(x - x.max(1, keepdims=True))
        return {"y": (e / e.sum(1, keepdims=True)).ravel()}
    if kernel == "rmsnorm":
        g = np.asarray(inputs["g"], dtype=np.float64)
        return {"y": (x / np.sqrt((x ** 2).mean(1, keepdims=True) + eps) * g).ravel()}
    if kernel == "layernorm":
        g, b = (np.asarray(inputs[k], dtype=np.float64) for k in "gb")
        mu = x.mean(1, keepdims=True)
        return {"y": ((x - mu) / np.sqrt(((x - mu) ** 2).mean(1, keepdims=True) + eps) * g + b).ravel()}
    if kernel == "swiglu":
        u = np.asarray(inputs["u"], dtype=np.float64).reshape(-1, n)
        return {"y": (x / (1 + np.exp(-x)) * u).ravel()}
    if kernel == "gelu":
        k = math.sqrt(2 / math.pi)
        return {"y": (0.5 * x * (1 + np.tanh(k * (x + 0.044715 * x ** 3)))).ravel()}
    if kernel == "residual":
        return {"y": (x + np.asarray(inputs["u"], dtype=np.float64).reshape(-1, n)).ravel()}
    if kernel == "mx_quantize":
        return {"y": nf.mx_quantize(x, fmt or nf.MXFP8_E4M3).ravel()}
    if kernel == "mx_dequantize":
        fmt = fmt or nf.MXFP4
        q = np.asarray(inputs["q"], dtype=np.float64).reshape(-1, fmt.block)
        e = np.asarray(inputs["e"], dtype=np.float64)
        return {"y": (q * np.ldexp(1.0, e.astype(int))[:, None]).ravel()}
    raise ValueError(kernel)


# =====================================================================================================================
# Work per element, and an accelerator around the vector unit
# =====================================================================================================================

def work_per_element(kernel, n=4096, vlen=256, **kw):
    """
    Average work per element of a kernel on long rows: ALU element-operations, SFU operations, bytes loaded and
    stored, and scalar operations -- counted from the kernel's own program.

    [Idea] A pipe with throughput w elements per cycle needs work / w cycles per element, so the steady-state
        cycles per element of any vector unit is max(alu / lanes, sfu / sfu_lanes, ld / ld_bytes, st / st_bytes).
        Amdahl calculations (script 01, 04) use these counts.
    [Returns] dict with keys "alu", "sfu", "ld_bytes", "st_bytes", "scalar"
    """
    cfg = VUConfig(vlen=vlen)
    p = build(kernel, cfg, rows=1, n=n, **kw)
    w = {"alu": 0.0, "sfu": 0.0, "ld_bytes": 0.0, "st_bytes": 0.0, "scalar": 0.0}
    for ins in p.instrs:
        if kernel in ("rmsnorm", "layernorm") and ins.mem and ins.mem[0] in ("g", "b"):
            continue                                       # gains are loaded once per tensor, not per row
        unit = UNIT[ins.op]
        if unit in ("ld", "st"):
            w[f"{unit}_bytes"] += ins.n * DEFAULT_ELEM_BYTES.get(ins.mem[0], 4)
        else:
            w[unit] += ins.n
    return {k: v / n for k, v in w.items()}


def cycles_per_element(work, lanes, sfu_lanes, ld_bytes=None, st_bytes=None):
    """Steady-state cycles per element on a vector unit: the busiest pipe (memory pipes ignored if None)."""
    c = [work["alu"] / lanes, work["sfu"] / sfu_lanes if work["sfu"] else 0.0]
    if ld_bytes:
        c.append(work["ld_bytes"] / ld_bytes)
    if st_bytes:
        c.append(work["st_bytes"] / st_bytes)
    return max(c)


@dataclass(frozen=True)
class Engine:
    """
    An accelerator core at the level Amdahl's law needs: a matrix unit and a vector unit sharing a clock.

    [Fields] name; macs: matrix-unit MACs per cycle; lanes, sfu_lanes: vector ALU and SFU elements per cycle;
        freq: clock (Hz); mem_bw: off-chip bytes per second
    [Edge cases] This is a model with stated assumptions, not a product: REFERENCE below has a TPU v4-core-sized
        matrix unit (4 x 128 x 128 MACs at 1.05 GHz, from the TPU v4 paper) and a vector unit whose size is OUR
        assumption (1,024 fp32 lanes, a 128 x 8 grid, and 1/8 as many SFU lanes, the ratio of a GPU SM).
    """
    name: str
    macs: int
    lanes: int
    sfu_lanes: int
    freq: float
    mem_bw: float


REFERENCE = Engine("reference core", macs=4 * 128 * 128, lanes=1024, sfu_lanes=128, freq=1.05e9, mem_bw=600e9)


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    cfg = VUConfig()
    # 1. every kernel computes what numpy computes
    for kern, n, rows in (("softmax", 256, 4), ("softmax", 512, 2), ("rmsnorm", 512, 3), ("layernorm", 256, 3),
                          ("swiglu", 256, 2), ("gelu", 256, 2), ("residual", 512, 2)):
        x = rng.normal(0, 2, rows * n).astype(F32)
        inp = {"x": x, "u": rng.normal(0, 1, rows * n).astype(F32), "g": rng.normal(1, .1, n).astype(F32),
               "b": rng.normal(0, .1, n).astype(F32)}
        for il in (1, 2):
            res = run(cfg, build(kern, cfg, rows, n, interleave=il), inp, DEFAULT_ELEM_BYTES)
            ref = reference(kern, inp, n)["y"]
            err = np.abs(res.memory["y"] - ref).max() / np.abs(ref).max()
            assert err < 2e-6, (kern, n, il, err)
            assert res.cycles >= bound(cfg, build(kern, cfg, rows, n, interleave=il), DEFAULT_ELEM_BYTES)[0]
    # 2. MX quantization on the vector unit is bit-exact with numfmt
    for fmt in (nf.MXFP8_E4M3, nf.MXFP4):
        x = (rng.normal(0, 1, 4 * 256) * np.exp(rng.normal(0, 2, 4 * 256))).astype(F32)
        res = run(cfg, build("mx_quantize", cfg, 4, 256, fmt=fmt), {"x": x}, DEFAULT_ELEM_BYTES)
        deq = res.memory["q"].astype(np.float64).reshape(-1, 32) * np.ldexp(1.0, res.memory["e"].astype(int))[:, None]
        assert np.array_equal(deq.ravel(), nf.mx_quantize(x.astype(np.float64), fmt)), fmt.name
        res2 = run(cfg, build("mx_dequantize", cfg, 4, 256, fmt=fmt), {"q": res.memory["q"], "e": res.memory["e"]},
                   DEFAULT_ELEM_BYTES)
        assert np.array_equal(res2.memory["y"].astype(np.float64), deq.ravel())
    # 3. an interleaved element-wise stream reaches its throughput bound; chaining matters
    cfg16 = replace(cfg, sfu_lanes=16)
    p = build("gelu", cfg16, 16, 256, interleave=2)
    b, why = bound(cfg16, p, DEFAULT_ELEM_BYTES)
    xin = {"x": rng.normal(size=16 * 256).astype(F32)}
    c = run(cfg16, p, xin, DEFAULT_ELEM_BYTES).cycles
    c_nochain = run(replace(cfg16, chaining=False), p, xin, DEFAULT_ELEM_BYTES).cycles
    c_strict = run(replace(cfg16, queue=0), p, xin, DEFAULT_ELEM_BYTES).cycles
    assert why == "alu" and c < 1.05 * b and c_nochain > 1.08 * c and c_strict > c, (b, c, c_nochain, c_strict)
    # 4. work counts
    w = work_per_element("softmax")
    assert abs(w["sfu"] - 1) < 1e-9 and 4 <= w["alu"] <= 4.2, w
    print("vector_unit.py self-test passed")
    print(f"  gelu, 16 x 256, 2 rows interleaved: {c} cycles (bound {b}, {why}); without chaining {c_nochain}; "
          f"strict in-order {c_strict}")
    for k in ("softmax", "rmsnorm", "layernorm", "swiglu", "gelu", "residual", "mx_quantize"):
        print(f"  {k:12s} work per element: " + ", ".join(f"{u} {v:.2f}" for u, v in work_per_element(k).items()))
