"""
mapper.py -- mappings of a layer onto an accelerator: loop nests with tiling and spatial unrolling, an analytical model
of reuse, traffic, energy and latency (MAESTRO / Timeloop style), and mapspace search
=====================================================================================================================

[Why we need it]
    A convolution or a GEMM is a loop nest. The accelerator is a hierarchy: DRAM -> global buffer (GB) -> an array
    of PEs -> each PE's register file (RF) -> its MAC. A MAPPING decides
      - which loops run where (tiling: how big a tile each level holds),
      - in which order the loops at each level run (what stays put while what changes: the "stationarity"),
      - which loops are unrolled across the PEs (spatial mapping: who gets the same data, who reduces together).
    The same layer on the same hardware can differ 10-100x in energy between mappings. Weight-, output-, input- and
    row-stationary "dataflows" (Lectures 3 and 5) are just families of mappings. This module turns a mapping into
    numbers WITHOUT simulating: tile sizes, how often each tile is fetched, multicast and reduction across PEs,
    accesses at every level, energy, latency, buffer occupancy -- and searches the (huge) space of mappings.

[The layer] (a 7-dimensional loop nest, stride 1)
    for n, k, c, p, q, r, s:   O[n][k][p][q] += W[k][c][r][s] * I[n][c][p + r][q + s]
    Dimensions: N batch, K output channels, C input channels, P x Q output pixels, R x S filter.
    A GEMM C[M, Nout] = A[M, Kred] B[Kred, Nout] is the special case P = M, C = Kred, K = Nout (N = Q = R = S = 1).
    Relevance: W depends on (K, C, R, S); I on (N, C, P, Q, R, S) -- P and R together (sliding window); O on
    (N, K, P, Q). A loop over a dimension a tensor does not depend on REUSES that tensor.

[The mapping] (outer to inner)
    dram loops -> gb loops -> spatial loops (parallel over the PE array, x and y axes) -> rf loops -> one MAC.
    The product of a dimension's factors over all levels equals the dimension.
    keep_rf: which tensors the PE register file holds. A tensor not kept there occupies only the MAC's operand (or
    accumulator) register -- one element -- and is fetched from the GB (through the array network) whenever the
    loops change it; e.g. a systolic weight-stationary PE keeps only its weight.

[The reuse rule] (the heart of the model)
    Flatten all temporal loops ABOVE a level, outer to inner. A tensor's tile at that level stays resident while the
    innermost run of loops IRRELEVANT to it iterates, and must be fetched again whenever any other of those loops
    advances. So: fetches = product of the trip counts of those loops, minus the innermost irrelevant run.
    Across the PE array, spatial loops over dimensions irrelevant to a tensor MULTICAST it (one GB read serves all
    those PEs) or, for the output, REDUCE it (partial sums add up on the way back).

[Edge cases]
    - Factors must divide the dimensions exactly (choose layer shapes with many divisors, or pad them).
    - Input halos are counted per tile ((p + r - 1) x (q + s - 1)), but sliding-window reuse ACROSS consecutive tiles
      is not credited (the model is conservative for inputs, like the simplest analytical models).
    - Latency = max(compute cycles, GB bandwidth limit, DRAM bandwidth limit); pipeline fill and drain are ignored.
"""

import itertools
import math
import random
from dataclasses import dataclass, field

import course_path

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

from metrics import EYERISS_COSTS  # noqa: E402

DIMS = ("N", "K", "C", "P", "Q", "R", "S")
TENSORS = ("W", "I", "O")
RELEVANT = {"W": {"K", "C", "R", "S"}, "I": {"N", "C", "P", "Q", "R", "S"}, "O": {"N", "K", "P", "Q"}}


@dataclass(frozen=True)
class ConvLayer:
    """
    A layer as the 7-D loop nest (stride 1).

    [Fields] name; N, K, C, P, Q, R, S (see the module docstring)
    [Properties] macs; dims (dict); tensor sizes (elements): weights, inputs, outputs
    """
    name: str
    N: int = 1
    K: int = 1
    C: int = 1
    P: int = 1
    Q: int = 1
    R: int = 1
    S: int = 1

    @property
    def dims(self):
        return {d: getattr(self, d) for d in DIMS}

    @property
    def macs(self):
        return math.prod(self.dims.values())

    @property
    def weights(self):
        return self.K * self.C * self.R * self.S

    @property
    def inputs(self):
        return self.N * self.C * (self.P + self.R - 1) * (self.Q + self.S - 1)

    @property
    def outputs(self):
        return self.N * self.K * self.P * self.Q


def gemm(name, M, N, K):
    """A GEMM C[M, N] = A[M, K] @ B[K, N] as a ConvLayer: P = M rows, C = K (reduction), K = N (output columns)."""
    return ConvLayer(name, P=M, C=K, K=N)


@dataclass(frozen=True)
class Arch:
    """
    The hierarchy the layer is mapped onto.

    [Fields]
        name; pe_x, pe_y: PE array; rf_bytes: register file per PE; gb_bytes: global buffer
        elem: bytes per element (2 = 16-bit); gb_bw: GB elements per cycle (reads + writes); dram_bw: DRAM bytes/cycle
        costs: energy per access in units of one MAC (Eyeriss's normalized costs, Lecture 3): MAC, RF, array (one
            delivery over the PE network), buffer (GB), DRAM
    """
    name: str = "Eyeriss-like"
    pe_x: int = 16
    pe_y: int = 16
    rf_bytes: int = 512
    gb_bytes: int = 128 * 1024
    elem: int = 2
    gb_bw: float = 64.0
    dram_bw: float = 32.0
    costs: dict = field(default_factory=lambda: dict(EYERISS_COSTS))

    @property
    def pes(self):
        return self.pe_x * self.pe_y


@dataclass
class Mapping:
    """
    A mapping: loops per level, outer to inner, as (dim, bound) pairs; spatial loops as (dim, bound, axis).

    [Fields] dram, gb, rf: temporal loops; spatial: parallel loops over the PE array ("x" or "y");
        keep_rf: tensors the PE register file holds (the others are fetched per MAC)
    [Methods] factors(level) -> dict dim -> product of that level's bounds
    """
    dram: list = field(default_factory=list)
    gb: list = field(default_factory=list)
    spatial: list = field(default_factory=list)
    rf: list = field(default_factory=list)
    keep_rf: tuple = TENSORS
    name: str = ""

    def factors(self, level):
        f = {d: 1 for d in DIMS}
        for item in getattr(self, level):
            f[item[0]] *= item[1]
        return f


@dataclass
class Cost:
    """
    Model output for one mapping.

    [Fields]
        valid, reason       : whether the mapping fits (dimensions, array, RF, GB) and why not
        macs, pes_used, utilization
        compute_cycles, latency (cycles), bound ("compute" / "GB bandwidth" / "DRAM bandwidth")
        dram, gb, array, rf : accesses (elements) per level, dict per tensor for dram and gb (gb = accesses by the
                              array + transfers to/from DRAM; gb_array = the array's part only)
        energy              : dict level -> energy in MAC units; energy_per_mac
        rf_tile, gb_tile    : tile sizes (elements) per tensor
    """
    valid: bool
    reason: str = ""
    macs: int = 0
    pes_used: int = 0
    utilization: float = 0.0
    compute_cycles: int = 0
    latency: float = 0.0
    bound: str = ""
    dram: dict = field(default_factory=dict)
    gb: dict = field(default_factory=dict)
    gb_array: dict = field(default_factory=dict)
    array: float = 0.0
    rf: float = 0.0
    energy: dict = field(default_factory=dict)
    energy_per_mac: float = 0.0
    rf_tile: dict = field(default_factory=dict)
    gb_tile: dict = field(default_factory=dict)


def tile_size(tensor, f):
    """Elements of a tensor's tile for per-dimension tile extents f (dict dim -> extent); inputs include halos."""
    if tensor == "W":
        return f["K"] * f["C"] * f["R"] * f["S"]
    if tensor == "O":
        return f["N"] * f["K"] * f["P"] * f["Q"]
    return f["N"] * f["C"] * (f["P"] + f["R"] - 1) * (f["Q"] + f["S"] - 1)


def fetch_count(loops, tensor):
    """
    How many times a tile of `tensor` is (re)loaded, given the flattened loops above it (outer to inner).

    [Idea] The reuse rule: drop the innermost run of loops irrelevant to the tensor (the tile stays resident while
        they iterate); every remaining loop iteration requires a new tile.
    """
    loops = [(d, b) for d, b in loops if b > 1]
    i = len(loops)
    while i > 0 and loops[i - 1][0] not in RELEVANT[tensor]:
        i -= 1
    return math.prod(b for _, b in loops[:i])


def distinct_tiles(loops, tensor):
    """Distinct tiles visited = product of the trip counts of the RELEVANT loops above."""
    return math.prod(b for d, b in loops if d in RELEVANT[tensor])


def evaluate(layer, arch, m):
    """
    The analytical model: is the mapping valid, and what does it cost?

    [Idea] For every tensor:
        RF level (per PE): if kept, its RF tile is the extent of the rf loops; it is (re)filled per the reuse rule
            over the dram + gb loops. If not kept, each PE fetches one element per MAC: the "tile" is 1 and the rf
            loops count as loops above it.
        Array: a fill of P_used PEs costs P_used deliveries over the PE network but only P_used / multicast GB
            reads, where multicast = product of spatial bounds over dimensions IRRELEVANT to the tensor. For the
            output, those spatial loops are a REDUCTION: partial sums add up in the network, and only
            P_used / reduction values are written to the GB.
        GB level: the GB tile is the extent of gb + spatial + rf loops; it is (re)filled from DRAM per the reuse
            rule over the dram loops.
        Outputs: every "fetch" of an output tile is a WRITE of partial sums; all but the first visit of each
            distinct tile also READ the partial sums back (the L7 rule).
        Energy = MACs x MAC + RF accesses + array deliveries + GB accesses + DRAM accesses, each x its cost.
        Latency = max(compute cycles = product of all temporal bounds, GB accesses / gb_bw,
                      DRAM bytes / dram_bw).
    [Returns] Cost (valid=False with a reason if the mapping does not fit)
    """
    dims = layer.dims
    fd, fg, fs, fr = m.factors("dram"), m.factors("gb"), m.factors("spatial"), m.factors("rf")
    for d in DIMS:
        if fd[d] * fg[d] * fs[d] * fr[d] != dims[d]:
            return Cost(False, f"factors of {d} multiply to {fd[d] * fg[d] * fs[d] * fr[d]}, not {dims[d]}")
    sx = math.prod(b for d, b, ax in m.spatial if ax == "x")
    sy = math.prod(b for d, b, ax in m.spatial if ax == "y")
    if sx > arch.pe_x or sy > arch.pe_y:
        return Cost(False, f"spatial {sx} x {sy} exceeds the {arch.pe_x} x {arch.pe_y} array")
    pes = sx * sy
    rf_tile = {t: tile_size(t, fr) if t in m.keep_rf else 0 for t in TENSORS}
    rf_bytes = sum(rf_tile.values()) * arch.elem
    if rf_bytes > arch.rf_bytes:
        return Cost(False, f"RF tiles need {rf_bytes} B > {arch.rf_bytes} B")
    gbf = {d: fg[d] * fs[d] * fr[d] for d in DIMS}
    gb_tile = {t: tile_size(t, gbf) for t in TENSORS}
    gb_bytes = sum(gb_tile.values()) * arch.elem
    if gb_bytes > arch.gb_bytes:
        return Cost(False, f"GB tiles need {gb_bytes:,} B > {arch.gb_bytes:,} B")

    above_rf = [(d, b) for d, b in m.dram + m.gb]
    rf_loops = [(d, b) for d, b in m.rf]
    spatial_irrel = {t: math.prod(b for d, b, _ in m.spatial if d not in RELEVANT[t]) for t in TENSORS}
    gb_acc, dram_acc = {}, {}
    array = 0.0
    for t in TENSORS:
        if t in m.keep_rf:
            fetches = fetch_count(above_rf, t)
            distinct = distinct_tiles(above_rf, t)
            per_pe = rf_tile[t]
        else:
            loops = above_rf + rf_loops
            fetches = fetch_count(loops, t)
            distinct = distinct_tiles(loops, t)
            per_pe = 1
        deliveries = fetches * per_pe * pes
        share = spatial_irrel[t]                        # multicast (W, I) or reduction (O) factor
        if t == "O":
            writes = deliveries / share
            reads = writes * (1 - distinct / fetches) if fetches else 0.0
            gb_acc[t] = writes + reads
            array += deliveries + reads * share       # partial sums travel to the GB, and back for later visits
        else:
            gb_acc[t] = deliveries / share
            array += deliveries
    gb_array = dict(gb_acc)
    for t in TENSORS:
        f = fetch_count(m.dram, t)
        dist = distinct_tiles(m.dram, t)
        if t == "O":
            writes = f * gb_tile[t]
            dram_acc[t] = writes + writes * (1 - dist / f) if f else 0.0
        else:
            dram_acc[t] = f * gb_tile[t]
        gb_acc[t] = gb_acc[t] + dram_acc[t]           # data from DRAM is written into the GB
    macs = layer.macs
    rf_acc = macs * (len(m.keep_rf) + ("O" in m.keep_rf))   # operand reads (+ the partial-sum write) per MAC
    c = arch.costs
    energy = {"MAC": macs * c["MAC"], "RF": rf_acc * c["RF"], "array": array * c["array"],
              "buffer": sum(gb_acc.values()) * c["buffer"], "DRAM": sum(dram_acc.values()) * c["DRAM"]}
    compute = math.prod(b for d, b in m.dram + m.gb + m.rf)
    t_gb = sum(gb_acc.values()) / arch.gb_bw
    t_dram = sum(dram_acc.values()) * arch.elem / arch.dram_bw
    latency = max(compute, t_gb, t_dram)
    bound = "compute" if latency == compute else ("GB bandwidth" if latency == t_gb else "DRAM bandwidth")
    total = sum(energy.values())
    return Cost(True, "", macs, pes, macs / (latency * arch.pes), compute, latency, bound, dram_acc, gb_acc, gb_array,
                array, rf_acc, energy, total / macs, rf_tile, gb_tile)


# =====================================================================================================================
# Describing mappings
# =====================================================================================================================

def loop_nest_text(m):
    """The mapping as an indented loop nest (outer to inner)."""
    lines, ind = [], 0
    for level, loops in (("DRAM", m.dram), ("GB", m.gb)):
        for d, b in loops:
            if b > 1:
                lines.append("  " * ind + f"for {d.lower()}_{level.lower()} in range({b}):")
                ind += 1
    sp = [f"{d.lower()}_s in range({b}) [{ax}]" for d, b, ax in m.spatial if b > 1]
    if sp:
        lines.append("  " * ind + "parallel_for " + ", ".join(sp) + ":")
        ind += 1
    for d, b in m.rf:
        if b > 1:
            lines.append("  " * ind + f"for {d.lower()}_rf in range({b}):")
            ind += 1
    lines.append("  " * ind + "O[n][k][p][q] += W[k][c][r][s] * I[n][c][p+r][q+s]   # RF keeps " + ",".join(m.keep_rf))
    return "\n".join(lines)


def maestro_text(layer, m):
    """
    MAESTRO-style data-centric directives for the mapping (Kwon et al., MICRO 2019), one line per directive:
    TemporalMap(size, offset) D -- each step covers `size` indices of D, advancing by `offset`; SpatialMap -- the same,
    but across PEs; Cluster(n) -- groups of n PEs below.

    [Edge cases] A simplified rendering: sizes are the extents below each loop; R/S sliding windows are written as
        size = filter, offset = 1 on the output dimension, as MAESTRO does for convolutions.
    """
    dims = layer.dims
    extent = {d: dims[d] for d in DIMS}
    out = []
    for level, loops in (("DRAM->GB", m.dram), ("GB->array", m.gb)):
        for d, b in loops:
            if b > 1:
                extent[d] //= b
                out.append(f"TemporalMap({extent[d]},{extent[d]}) {d}    // {level}")
    for d, b, ax in m.spatial:
        if b > 1:
            extent[d] //= b
            out.append(f"SpatialMap({extent[d]},{extent[d]}) {d}    // across PEs ({ax})")
    out.append(f"Cluster({math.prod(b for _, b, _ in m.spatial)})")
    for d, b in m.rf:
        if b > 1:
            out.append(f"TemporalMap(1,1) {d}    // inside a PE, {b} steps")
    return "\n".join(out)


# =====================================================================================================================
# Classic dataflows as mappings
# =====================================================================================================================

def _split(n, cap):
    """Largest divisor of n that is <= cap."""
    return max(d for d in range(1, min(n, cap) + 1) if n % d == 0)


def dataflow(layer, arch, kind):
    """
    A classic dataflow as a mapping (hand-written, not optimized; the GB holds whole layers if it can).

    [Idea]
        WS (weight-stationary, NVDLA/TPU-like): unroll K across x and C across y; each PE keeps ONE weight and
            streams all output pixels past it (rf loops over P, Q, R, S... with only W kept).
        OS (output-stationary, ShiDianNao-like): unroll output pixels P across x and K across y; each PE keeps its
            outputs and streams C x R x S.
        IS (input-stationary): unroll C across x and P across y; each PE keeps an input row segment.
        RS (row-stationary, Eyeriss): unroll filter rows R and output rows P across the array (a PE convolves one
            filter row with one input row); the RF keeps a filter row, an input row and a row of partial sums.
    [Returns] Mapping (check it with evaluate(); it may not fit small RFs or GBs)
    """
    d = layer.dims
    if kind == "WS":
        kx, cy = _split(d["K"], arch.pe_x), _split(d["C"], arch.pe_y)
        return Mapping(dram=[], gb=[("N", d["N"]), ("K", d["K"] // kx), ("C", d["C"] // cy), ("R", d["R"]), ("S", d["S"])],
                       spatial=[("K", kx, "x"), ("C", cy, "y")], rf=[("P", d["P"]), ("Q", d["Q"])],
                       keep_rf=("W",), name="weight-stationary")
    if kind == "OS":
        px, ky = _split(d["P"], arch.pe_x), _split(d["K"], arch.pe_y)
        return Mapping(dram=[], gb=[("N", d["N"]), ("K", d["K"] // ky), ("P", d["P"] // px), ("Q", d["Q"])],
                       spatial=[("P", px, "x"), ("K", ky, "y")], rf=[("C", d["C"]), ("R", d["R"]), ("S", d["S"])],
                       keep_rf=("O",), name="output-stationary")
    if kind == "IS":
        cx, py = _split(d["C"], arch.pe_x), _split(d["P"], arch.pe_y)
        return Mapping(dram=[], gb=[("N", d["N"]), ("C", d["C"] // cx), ("P", d["P"] // py), ("Q", d["Q"]), ("R", d["R"]), ("S", d["S"])],
                       spatial=[("C", cx, "x"), ("P", py, "y")], rf=[("K", d["K"])],
                       keep_rf=("I",), name="input-stationary")
    if kind == "RS":
        ry = _split(d["R"], arch.pe_y)
        px = _split(d["P"], arch.pe_x)
        k_in = _split(d["K"], max(1, arch.pe_y // ry))
        return Mapping(dram=[], gb=[("N", d["N"]), ("K", d["K"] // k_in), ("C", d["C"]), ("P", d["P"] // px)],
                       spatial=[("P", px, "x"), ("R", ry, "y"), ("K", k_in, "y")],
                       rf=[("R", d["R"] // ry), ("Q", d["Q"]), ("S", d["S"])],
                       keep_rf=("W", "I", "O"), name="row-stationary")
    raise ValueError(kind)


# =====================================================================================================================
# The mapspace
# =====================================================================================================================

def fit_gb(layer, arch, m):
    """
    Make a mapping fit the global buffer: while its GB tiles are too large, take the largest loop below the DRAM
    level (GB or RF level), move its smallest prime factor up to the DRAM level (as a DRAM loop), and retry.

    [Returns] the adjusted Mapping (unchanged if it already fits or no factor can be moved)
    """
    import copy
    m = copy.deepcopy(m)
    for _ in range(64):
        c = evaluate(layer, arch, m)
        if c.valid or not c.reason.startswith("GB"):
            return m
        cands = [(b, lv, i) for lv in ("gb", "rf") for i, (_, b) in enumerate(getattr(m, lv)) if b > 1]
        if not cands:
            return m
        b, lv, i = max(cands)
        d = getattr(m, lv)[i][0]
        p = next(q for q in range(2, b + 1) if b % q == 0)
        getattr(m, lv)[i] = (d, b // p)
        for j, (e, v) in enumerate(m.dram):
            if e == d:
                m.dram[j] = (d, v * p)
                break
        else:
            m.dram.append((d, p))
    return m


def divisors(n):
    return [d for d in range(1, n + 1) if n % d == 0]


def ordered_factorizations(n, parts):
    """Number of ways to write n as an ordered product of `parts` positive integers."""
    count, m = 1, n
    p = 2
    while p * p <= m:
        a = 0
        while m % p == 0:
            m //= p
            a += 1
        if a:
            count *= math.comb(a + parts - 1, parts - 1)
        p += 1
    if m > 1:
        count *= parts
    return count


def mapspace_size(layer):
    """
    Size of a simple mapspace: every dimension split over 5 levels (DRAM, GB, spatial x, spatial y, RF) times the
    loop orders of the three temporal levels (7! each). An upper bound on the mappings a mapper might consider;
    most are invalid (too big for the array, RF or GB) or equivalent (orders of loops with bound 1).
    """
    f = math.prod(ordered_factorizations(v, 5) for v in layer.dims.values())
    return f * math.factorial(7) ** 3


def random_mapping(layer, arch, rng, keep=None):
    """
    A random mapping: random spatial dimensions and factors (biased toward filling the array), random splits of the
    rest over DRAM / GB / RF, random loop orders, and a random choice of what the RF keeps.
    """
    dims = layer.dims
    big = [d for d in DIMS if dims[d] > 1] or ["K"]
    dx, dy = rng.choice(big), rng.choice(big)
    rem = dict(dims)
    spatial = []
    for d, ax, cap in ((dx, "x", arch.pe_x), (dy, "y", arch.pe_y)):
        opts = [v for v in divisors(rem[d]) if v <= cap]
        v = max(opts) if rng.random() < 0.6 else rng.choice(opts)
        spatial.append((d, v, ax))
        rem[d] //= v
    levels = {"dram": {}, "gb": {}, "rf": {}}
    for d in DIMS:
        a = rng.choice(divisors(rem[d]))
        b = rng.choice(divisors(rem[d] // a))
        levels["dram"][d], levels["gb"][d], levels["rf"][d] = a, b, rem[d] // a // b

    def order(lv):
        ds = list(DIMS)
        rng.shuffle(ds)
        return [(d, levels[lv][d]) for d in ds]

    if keep is None:
        keep = tuple(t for t in TENSORS if rng.random() < 0.7) or ("O",)
    return Mapping(order("dram"), order("gb"), spatial, order("rf"), keep, "random")


def random_search(layer, arch, n, seed=0, objective="energy", keep=None):
    """
    Evaluate n random mappings; returns (best Mapping, best Cost, list of valid Costs).

    [Args] objective: "energy" (energy per MAC), "latency" or "edp" (energy x latency)
    """
    rng = random.Random(seed)
    best, best_c, valid = None, None, []
    for _ in range(n):
        m = random_mapping(layer, arch, rng, keep)
        c = evaluate(layer, arch, m)
        if not c.valid:
            continue
        valid.append(c)
        if best_c is None or score(c, objective) < score(best_c, objective):
            best, best_c = m, c
    return best, best_c, valid


def score(c, objective):
    """The number to minimize."""
    if objective == "energy":
        return c.energy_per_mac
    if objective == "latency":
        return c.latency
    return c.energy_per_mac * c.latency


def _neighbors(layer, arch, m, rng):
    """A random local move: move a prime factor between temporal levels, swap two loops, or change what RF keeps."""
    import copy
    n = copy.deepcopy(m)
    move = rng.random()
    if move < 0.6:
        src, dst = rng.sample(["dram", "gb", "rf"], 2)
        loops = getattr(n, src)
        cand = [i for i, (d, b) in enumerate(loops) if b > 1]
        if not cand:
            return n
        i = rng.choice(cand)
        d, b = loops[i]
        p = next(q for q in range(2, b + 1) if b % q == 0)
        loops[i] = (d, b // p)
        tgt = getattr(n, dst)
        j = next(j for j, (e, _) in enumerate(tgt) if e == d)
        tgt[j] = (d, tgt[j][1] * p)
    elif move < 0.9:
        lv = rng.choice(["dram", "gb", "rf"])
        loops = getattr(n, lv)
        i, j = rng.sample(range(len(loops)), 2)
        loops[i], loops[j] = loops[j], loops[i]
    else:
        t = rng.choice(TENSORS)
        keep = set(n.keep_rf) ^ {t}
        n.keep_rf = tuple(x for x in TENSORS if x in keep) or ("O",)
    return n


def local_search(layer, arch, budget, seed=0, objective="energy", restarts=4, keep=None, explore=0.3):
    """
    Sample, then climb: spend `explore` of the budget on random mappings, then hill-climb from the best `restarts`
    of them with the rest; returns (best Mapping, best Cost, evaluations used).

    [Idea] Mapspaces are huge and rugged at large scale (a poor start sits in a poor basin) but locally smooth: moving
        one prime factor between levels or swapping two loops changes the cost a little. Random sampling finds good
        basins; hill climbing (accept any local move that improves the objective) descends them.
    [Edge cases] With a tiny budget most of it is spent sampling; restarts are capped by the valid samples found.
    """
    rng = random.Random(seed)
    n_explore = max(1, int(budget * explore))
    pool = []
    used = 0
    for _ in range(n_explore):
        m = random_mapping(layer, arch, rng, keep)
        c = evaluate(layer, arch, m)
        used += 1
        if c.valid:
            pool.append((score(c, objective), m, c))
    pool.sort(key=lambda x: x[0])
    starts = pool[:restarts]
    if not starts:
        return None, None, used
    best_s, best, best_c = starts[0]
    per = (budget - used) // len(starts)
    for _, cur, cur_c in starts:
        for _ in range(per):
            n = _neighbors(layer, arch, cur, rng)
            c = evaluate(layer, arch, n)
            used += 1
            if c.valid and score(c, objective) < score(cur_c, objective):
                cur, cur_c = n, c
        if score(cur_c, objective) < best_s:
            best_s, best, best_c = score(cur_c, objective), cur, cur_c
    return best, best_c, used


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

if __name__ == "__main__":
    import sys
    course_path.use("lecture05", "lecture07")
    import systolic as sa
    import tiling as tl

    arch = Arch()
    # 1. a GEMM mapped like Lecture 5's weight-stationary systolic array reproduces its SRAM traffic exactly
    M, K, N, R, C = 96, 64, 48, 16, 16
    L = gemm("g", M, N, K)
    ws = Mapping(gb=[("K", N // C), ("C", K // R)], spatial=[("K", C, "x"), ("C", R, "y")], rf=[("P", M)],
                 keep_rf=("W",))
    big = Arch(gb_bytes=1 << 30, gb_bw=1e9, dram_bw=1e9)
    c = evaluate(L, big, ws)
    s = sa.estimate(M, K, N, R, C, "WS").traffic
    assert c.valid and c.gb_array["W"] == s["B"] and c.gb_array["I"] == s["A"], (c.gb_array, s)
    assert c.gb_array["O"] == s["C_read"] + s["C_write"], (c.gb_array["O"], s)
    # 2. DRAM traffic of a GB-level tiling equals Lecture 7's tiling.gemm_traffic (elements: elem = acc = 1)
    Mb, Nb, Kb, Tm, Tn, Tk = 256, 256, 256, 64, 32, 128
    Lb = gemm("t", Mb, Nb, Kb)
    for order in ("mnk", "mkn", "nkm"):
        name = {"m": "P", "n": "K", "k": "C"}
        size = {"m": Mb // Tm, "n": Nb // Tn, "k": Kb // Tk}
        mp = Mapping(dram=[(name[o], size[o]) for o in order], gb=[("P", Tm), ("K", Tn), ("C", Tk)], spatial=[], rf=[],
                     keep_rf=())
        cc = evaluate(Lb, big, mp)
        ref = tl.gemm_traffic(Mb, Nb, Kb, Tm, Tn, Tk, order, elem=1, acc=1)
        assert abs(sum(cc.dram.values()) - ref["total"]) < 1e-6, (order, cc.dram, ref)
    # 3. invalid mappings are rejected with a reason
    bad = Mapping(rf=[("K", 64)], spatial=[("C", 64, "x")])
    assert not evaluate(gemm("x", 1, 64, 64), arch, bad).valid
    # 4. classic dataflows are valid on a ResNet-like layer, and search finds better ones than random sampling
    conv = ConvLayer("conv", N=1, K=64, C=64, P=56, Q=56, R=3, S=3)
    for kind in ("WS", "OS", "IS", "RS"):
        cv = evaluate(conv, Arch(gb_bytes=1 << 22), dataflow(conv, Arch(gb_bytes=1 << 22), kind))
        assert cv.valid, (kind, cv.reason)
    _, rbest, _ = random_search(conv, arch, 3000, seed=1)
    _, lbest, _ = local_search(conv, arch, 3000, seed=1)
    assert lbest.energy_per_mac <= rbest.energy_per_mac * 1.05, (lbest.energy_per_mac, rbest.energy_per_mac)
    assert ordered_factorizations(12, 2) == 6 and ordered_factorizations(8, 3) == 10
    print("mapper.py self-test passed")
    print(f"  {conv.name}: random search best {rbest.energy_per_mac:.2f} MAC-units/MAC, local search {lbest.energy_per_mac:.2f}; "
          f"mapspace ~{mapspace_size(conv):.1e} points")
