"""
memory.py -- banked SRAM (bank conflicts, address mappings, ports vs banks) and a DRAM/HBM timing model (rows, banks,
channels, scheduling, refresh), plus 2-D tile fetches through it
==================================================================================================================

[Why we need it]
    The arithmetic of Lectures 5 and 6 only runs at full speed if memory delivers operands fast enough. Two very
    different memories do the delivering:
    1. On-chip SRAM buffers. One SRAM array delivers one word per port per cycle. To serve many lanes at once, a
       buffer is split into BANKS, each with its own port. Banks are cheap -- but two lanes asking the same bank for
       different words in the same cycle CONFLICT and one must wait. Which bank holds which word (the address
       mapping) decides how often that happens.
    2. Off-chip DRAM (DDR, GDDR, HBM). DRAM is organized in channels > banks > rows. A bank must ACTIVATE a row
       (copy it into its row buffer, ~tens of ns) before reading any part of it, and PRECHARGE (close) it before
       opening another. Reads from the open row are fast; switching rows is slow. Peak bandwidth needs (a) all
       channels busy, (b) many reads per activated row, and (c) other banks activating while one bank transfers.
       Every few microseconds the DRAM must also stop to REFRESH its cells.
    This module models both well enough to see these effects with real address streams.

[Main pieces]
    bank_of(words, banks, scheme)       : which bank holds each word ("low", "xor", "prime" interleaving)
    vector_access_cycles(...)            : cycles for one vector access of many lanes (conflicts, broadcast merging)
    strided_addresses, matrix_addresses  : address generators (strided vectors, rows/columns of padded matrices)
    sram_area_um2, sram_access_pj        : cost of one buffer organized as banks x ports
    DRAMConfig, HBM2_LIKE                : timing parameters of a DRAM (illustrative HBM2-like values)
    simulate_dram(cfg, addresses, ...)   : request-by-request timing with open/closed pages, FCFS or FR-FCFS, refresh
    tile_addresses                       : byte addresses of a 2-D tile in a row-major or a blocked (tiled) layout

[Edge cases]
    - Addresses are integers (words for the SRAM functions, bytes for the DRAM functions).
    - The DRAM model schedules requests one at a time per channel (each takes the earliest time all its
      constraints allow). It is a teaching model, not a JEDEC-compliant controller: no write-to-read turnaround,
      no bank groups, refresh closes all banks of a channel at fixed intervals.
"""

import math
from collections import deque
from dataclasses import dataclass, field, replace

import numpy as np

import course_path

course_path.use("lecture01")

from energy_model import sram_pj_per_byte  # noqa: E402

# Area assumptions of Lecture 2 (hls.py), restated: SRAM cell + amortized periphery, fixed periphery per bank, and the
# extra area of each port beyond the first.
SRAM_UM2_PER_BIT = 0.7
BANK_OVERHEAD_UM2 = 2500.0
EXTRA_PORT_FACTOR = 0.5


# =====================================================================================================================
# Banked SRAM
# =====================================================================================================================

def bank_of(words, banks, scheme="low"):
    """
    Bank holding each word address.

    [Idea] Interleaving schemes:
        "low"   : bank = word mod banks. Consecutive words go to consecutive banks -- perfect for unit stride, but a
                  stride that shares a factor with the bank count hits fewer banks (stride = banks: all in one).
        "xor"   : bank = (word XOR (word // banks)) mod banks -- the low bits are scrambled with the next bits, so
                  power-of-two strides spread over all banks (a common hardware hash: a few XOR gates).
        "prime" : bank = word mod banks with a PRIME number of banks (e.g. 17): only strides that are multiples of
                  the prime conflict. The price: a modulo by a non-power of two in the address path.
    [Args] words: int or integer array; banks: number of banks; scheme: "low", "xor" or "prime"
    [Returns] integer array of bank indices
    [Edge cases] "xor" assumes banks is a power of two (it raises ValueError otherwise); "prime" assumes it is prime.
    """
    w = np.asarray(words, dtype=np.int64)
    if scheme == "low" or scheme == "prime":
        return w % banks
    if scheme == "xor":
        if banks & (banks - 1):
            raise ValueError("xor mapping needs a power-of-two number of banks")
        return (w ^ (w // banks)) % banks
    raise ValueError(f"unknown scheme {scheme!r}")


def vector_access_cycles(words, banks, scheme="low", ports=1):
    """
    Cycles to serve ONE vector access: every lane requests one word, all in the same cycle.

    [Idea] Each bank delivers `ports` words per cycle. Requests for the SAME word are merged (one read, broadcast to
        all lanes that asked). So the access takes max over banks of ceil(distinct words in that bank / ports).
    [Args] words: word address per lane; banks, scheme, ports
    [Returns] int cycles (1 = conflict-free)
    [Python tip] np.unique removes duplicates; np.bincount counts how many entries fall in each bank.
    """
    uniq = np.unique(np.asarray(words, dtype=np.int64))
    counts = np.bincount(bank_of(uniq, banks, scheme), minlength=banks)
    return int(math.ceil(counts.max() / ports))


def strided_addresses(lanes, stride, base=0):
    """Word addresses of a strided vector access: base, base + stride, ..., one per lane."""
    return base + stride * np.arange(lanes)


def matrix_addresses(rows, cols, pitch, which="column", index=0):
    """
    Word addresses of one column (or row) of a row-major matrix stored with a row PITCH (words per stored row).

    [Idea] Padding each row with a few unused words (pitch = cols + 1) is the classic software fix for column
        conflicts: column c of row r sits at r * pitch + c, so consecutive rows of a column move one bank further.
    [Args] rows, cols: matrix shape; pitch: stored row length (>= cols); which: "column" or "row"; index: which one
    [Returns] integer array of word addresses
    """
    if pitch < cols:
        raise ValueError("pitch must be at least the number of columns")
    if which == "column":
        return np.arange(rows) * pitch + index
    return index * pitch + np.arange(cols)


def sram_area_um2(total_bytes, banks=1, ports=1):
    """
    Area of a buffer of total_bytes split into `banks` banks with `ports` ports each (45 nm, Lecture 2 assumptions).

    [Idea] Bits cost SRAM_UM2_PER_BIT; every bank pays a fixed periphery (decoders, sense amplifiers); every extra
        port adds EXTRA_PORT_FACTOR of the bank's area (bigger cells, duplicated periphery).
    """
    base = total_bytes * 8 * SRAM_UM2_PER_BIT + banks * BANK_OVERHEAD_UM2
    return base * (1 + EXTRA_PORT_FACTOR * (ports - 1))


def sram_access_pj(total_bytes, banks, access_bytes):
    """Energy of one access of access_bytes to a bank of total_bytes / banks (smaller banks: shorter wires)."""
    return access_bytes * sram_pj_per_byte(total_bytes / banks)


# =====================================================================================================================
# DRAM / HBM
# =====================================================================================================================

@dataclass(frozen=True)
class DRAMConfig:
    """
    Timing of a DRAM device (all times in ns).

    [Fields]
        channels    : independent channels, each with its own data bus and banks
        banks       : banks per channel; row_bytes: row (page) size per bank; burst_bytes: bytes per column access
        t_burst     : ns the data bus is busy per burst (burst_bytes / channel bandwidth)
        tRCD        : activate -> column command;  tCL: column command -> data;  tRP: precharge -> activate
        tRAS        : minimum activate -> precharge;  tRRD: activate -> activate (same channel, different banks)
        tFAW        : at most 4 activates per tFAW window (power-delivery limit)
        tREFI, tRFC : refresh interval and refresh duration (all banks of a channel unavailable)
        page        : "open" (keep the row open after an access) or "closed" (precharge after every access)
        sched       : "frfcfs" (ready row hits first, then oldest ready) or "fcfs" (oldest first)
        queue       : requests a channel's controller can hold (and choose from); a full queue stalls the DMA
        mapping     : how byte addresses map to (channel, bank, row, column) -- see decode()
    [Properties] peak_bw (bytes/s)
    [Edge cases] The default values (HBM2_LIKE) are typical orders of magnitude for one HBM2 stack (8 channels of
        32 GB/s = 256 GB/s, 1 KB rows, ~14 ns core timings), NOT a datasheet.
    """
    name: str = "HBM2-like stack"
    channels: int = 8
    banks: int = 16
    row_bytes: int = 1024
    burst_bytes: int = 64
    t_burst: float = 2.0
    tRCD: float = 14.0
    tCL: float = 14.0
    tRP: float = 14.0
    tRAS: float = 33.0
    tRRD: float = 4.0
    tFAW: float = 16.0
    tREFI: float = 3900.0
    tRFC: float = 350.0
    page: str = "open"
    sched: str = "frfcfs"
    queue: int = 32
    mapping: str = "interleaved"

    @property
    def peak_bw(self):
        return self.channels * self.burst_bytes / self.t_burst * 1e9

    def decode(self, addr):
        """
        Byte address -> (channel, bank, row, column) for numpy arrays of addresses.

        [Idea] The low bits select the byte inside a burst. Then:
            "interleaved" : burst | channel | column | bank | row  -- consecutive bursts rotate over the channels,
                            and a channel then reads consecutive columns of one row (row hits): the usual choice;
            "row_major"   : burst | column | bank | channel | row  -- a whole row (1 KB) of one bank before moving
                            on: a sequential stream uses ONE channel at a time;
            "hashed"      : like "interleaved", but the channel and bank indices are XORed with higher address
                            bits (column, bank, row): strides that would hit one channel or one bank are spread
                            over all of them (the address hashing of GPU and server memory controllers).
        """
        a = np.asarray(addr, dtype=np.int64) // self.burst_bytes
        cols = self.row_bytes // self.burst_bytes
        if self.mapping in ("interleaved", "hashed"):
            ch = a % self.channels
            a = a // self.channels
            col = a % cols
            a = a // cols
            bank = a % self.banks
            row = a // self.banks
            if self.mapping == "hashed":                 # XOR the channel and bank with higher address bits
                x = (row * 2654435761 >> 8) & 0xFFFF     # a scrambled copy of the row number
                ch = (ch ^ col ^ bank ^ x) % self.channels
                bank = (bank ^ (x >> 3)) % self.banks
        elif self.mapping == "row_major":
            col = a % cols
            a = a // cols
            bank = a % self.banks
            a = a // self.banks
            ch = a % self.channels
            row = a // self.channels
        else:
            raise ValueError(f"unknown mapping {self.mapping!r}")
        return ch, bank, row, col


HBM2_LIKE = DRAMConfig()


@dataclass
class DRAMResult:
    """
    Outcome of a DRAM simulation.

    [Fields] seconds; bytes; bandwidth (bytes/s); fraction (of peak); row_hits, row_misses, row_empty (accesses by
        bank state); refreshes; mean_latency_ns (arrival of a request -> end of its data); per_channel bytes
    [Properties] hit_rate
    """
    seconds: float
    bytes: int
    bandwidth: float
    fraction: float
    row_hits: int
    row_misses: int
    row_empty: int
    refreshes: int
    mean_latency_ns: float
    per_channel: list = field(default_factory=list)

    @property
    def hit_rate(self):
        n = self.row_hits + self.row_misses + self.row_empty
        return self.row_hits / n if n else 0.0


class _Channel:
    """State of one DRAM channel: open rows, bank timing, activate history, data bus, refresh."""

    def __init__(self, cfg):
        self.cfg = cfg
        self.open_row = [None] * cfg.banks
        self.act_time = [-1e9] * cfg.banks          # last activate of each bank
        self.col_ready = [0.0] * cfg.banks          # earliest column command (activate + tRCD)
        self.bank_free = [0.0] * cfg.banks          # earliest next activate (after a precharge)
        self.acts = deque(maxlen=4)                 # last four activates (tFAW)
        self.last_act = -1e9
        self.bus = 0.0                              # data bus free from this time
        self.next_ref = cfg.tREFI
        self.refreshes = 0
        self.queue = deque()                        # (index, bank, row, arrival)
        self.last_dequeue = 0.0                     # when the last request left the queue (its first command)

    def refresh_until(self, t):
        """Apply every refresh due before time t: all rows close, nothing happens for tRFC."""
        cfg = self.cfg
        while t >= self.next_ref:
            self.refreshes += 1
            stop = self.next_ref + cfg.tRFC
            self.open_row = [None] * cfg.banks
            self.bank_free = [max(x, stop) for x in self.bank_free]
            self.col_ready = [max(x, stop) for x in self.col_ready]
            self.bus = max(self.bus, stop)
            self.next_ref += cfg.tREFI

    def activate_ready(self, b):
        """Earliest time bank b could activate a new row (after closing the open one, if any)."""
        if self.open_row[b] is None:
            return self.bank_free[b]
        return max(self.act_time[b] + self.cfg.tRAS, self.bank_free[b]) + self.cfg.tRP

    def plan(self, b, r, arr):
        """
        Earliest commands for a request to bank b, row r, arrived at arr, given the current state.

        [Returns] (kind, t_act, t_col): kind is "hit", "empty" or "miss"; t_act is None for a hit
        """
        cfg = self.cfg
        if self.open_row[b] == r:
            return "hit", None, max(self.col_ready[b], arr)
        kind = "empty" if self.open_row[b] is None else "miss"
        t_act = max(self.activate_ready(b), self.last_act + cfg.tRRD, arr,
                    (self.acts[0] + cfg.tFAW) if len(self.acts) == 4 else 0.0)
        return kind, t_act, t_act + cfg.tRCD

    def pick(self, now):
        """
        Index in the queue of the request to serve next, among the first `queue` that have arrived by `now`.

        [Idea] FCFS: the oldest. FR-FCFS: among the requests whose data could use the bus as soon as it is free
            ("ready"), row hits first, then the oldest; if none is ready, the one whose data can start earliest.
        """
        cfg = self.cfg
        cands = []
        for i, (_, b, r, arr) in enumerate(self.queue):
            if i >= cfg.queue:
                break
            if arr > now:
                continue
            if cfg.sched == "fcfs":
                return i
            kind, _, t_col = self.plan(b, r, arr)
            cands.append((t_col + cfg.tCL, kind != "hit", i))
        ready = [c for c in cands if c[0] <= self.bus]
        if ready:
            return min(ready, key=lambda c: (c[1], c[2]))[2]
        return min(cands)[2]

    def serve(self, i, counts):
        """Schedule queue entry i; returns (request index, arrival, completion time)."""
        cfg = self.cfg
        j, b, r, arr = self.queue[i]
        del self.queue[i]
        kind, t_act, t_col = self.plan(b, r, arr)
        counts[{"hit": 0, "miss": 1, "empty": 2}[kind]] += 1
        if t_act is not None:
            self.acts.append(t_act)
            self.last_act = t_act
            self.act_time[b] = t_act
            self.open_row[b] = r
            self.col_ready[b] = t_col
        t_data = max(t_col + cfg.tCL, self.bus)
        self.bus = t_data + cfg.t_burst
        self.last_dequeue = max(self.last_dequeue, t_act if t_act is not None else t_col)
        if cfg.page == "closed":
            self.bank_free[b] = max(self.act_time[b] + cfg.tRAS, t_data) + cfg.tRP
            self.open_row[b] = None
        return j, arr, self.bus


def simulate_dram(cfg, addresses, outstanding=256):
    """
    Time a stream of read requests (one burst each) through a DRAM.

    [Idea] A DMA engine issues the requests in order but can have at most `outstanding` requests in flight: request
        j may enter the memory controller only when request j - outstanding has completed. Each channel keeps the
        requests for it in a queue and serves one at a time (event-driven: the channel whose data bus frees first
        goes next). Its scheduler chooses among the first `queue` arrived requests:
        - FR-FCFS: among the requests that could use the data bus as soon as it frees, row hits first, then the
          oldest; if none can, the one that can start earliest -- a real controller keeps issuing commands to
          ready banks instead of waiting for a busy one;
        - FCFS: the oldest request, whatever its bank is doing.
        The chosen request is placed at the earliest time its constraints allow:
        - hit   : column command when the bank's row is open (>= activate + tRCD); data after tCL;
        - empty : activate (>= tRRD after the previous activate, at most 4 per tFAW), then as a hit;
        - miss  : precharge (>= activate + tRAS), activate tRP later, then as a hit;
        and its data burst must find the channel's data bus free. With a "closed" page policy every access
        precharges its row afterwards. Every tREFI ns a channel refreshes: all rows close for tRFC ns.
    [Args] cfg: DRAMConfig; addresses: byte addresses (one burst each), in issue order; outstanding: the DMA's limit
    [Returns] DRAMResult
    [Edge cases] Bandwidth counts burst_bytes per request. Little's law links the knobs: bandwidth <= outstanding x
        burst_bytes / latency, so too few outstanding requests cannot fill the channels whatever the DRAM does.
    """
    ch, bank, row, _ = cfg.decode(addresses)
    ch, bank, row = ch.tolist(), bank.tolist(), row.tolist()
    n = len(ch)
    chans = [_Channel(cfg) for _ in range(cfg.channels)]
    completion = [None] * n
    counts = [0, 0, 0]                                   # hits, misses, empty
    admitted = 0
    done = 0
    lat_sum = 0.0
    issue_clock = 0.0                                   # requests are issued in order: arrival times never decrease
    blocked = None
    while done < n:
        while admitted < n:
            j = admitted
            if j >= outstanding and completion[j - outstanding] is None:
                break                                   # too many requests in flight
            c = chans[ch[j]]
            if len(c.queue) >= cfg.queue:
                blocked = c                             # back-pressure: the head request waits, and all behind it
                break
            arr = max(issue_clock, completion[j - outstanding] if j >= outstanding else 0.0)
            if blocked is c:
                arr = max(arr, c.last_dequeue)          # it entered when a slot of the full queue freed
                blocked = None
            c.queue.append((j, bank[j], row[j], arr))
            issue_clock = arr
            admitted += 1
        # the channel that can serve something earliest
        best_c, best_t = None, None
        for c in chans:
            if not c.queue:
                continue
            t = max(c.bus, c.queue[0][3])          # arrivals never decrease, so the oldest request arrived first
            if best_c is None or t < best_t:
                best_c, best_t = c, t
        best_c.refresh_until(best_t)
        now = max(best_c.bus, best_c.queue[0][3])
        i = best_c.pick(now)
        j, arr, end = best_c.serve(i, counts)
        completion[j] = end
        lat_sum += end - arr
        done += 1
    t_end = max(c.bus for c in chans)
    total = n * cfg.burst_bytes
    seconds = t_end * 1e-9
    bw = total / seconds if seconds else 0.0
    per_channel = [sum(1 for x in ch if x == c) * cfg.burst_bytes for c in range(cfg.channels)]
    return DRAMResult(seconds, total, bw, bw / cfg.peak_bw, counts[0], counts[1], counts[2],
                      sum(c.refreshes for c in chans), lat_sum / n if n else 0.0, per_channel)


def tile_addresses(row0, col0, tile_rows, tile_cols, ld, elem_bytes=2, layout="row_major", block=None, base=0):
    """
    Byte addresses (one per burst-sized piece) of a 2-D tile of a matrix.

    [Idea] In a ROW-MAJOR layout, a tile is tile_rows separate pieces of tile_cols x elem_bytes bytes, one per
        matrix row, ld x elem_bytes apart: narrow tiles touch a new DRAM row for every tile row. In a BLOCKED
        (tiled) layout the matrix is stored tile by tile, so each tile is one contiguous range.
    [Args]
        row0, col0           : top-left element of the tile
        tile_rows, tile_cols : tile shape (elements)
        ld                   : leading dimension = elements per matrix row
        elem_bytes           : bytes per element
        layout               : "row_major" or "blocked"
        block                : (block_rows, block_cols) of the blocked layout (default: the tile shape)
        base                 : byte address of the matrix
    [Returns] integer array of byte addresses, one per 64-byte burst (the caller's DRAM burst size)
    [Edge cases] Pieces shorter than a burst still cost a whole burst (they are rounded up).
    """
    burst = 64
    if layout == "row_major":
        starts = base + ((row0 + np.arange(tile_rows)) * ld + col0) * elem_bytes
        nb = max(1, math.ceil(tile_cols * elem_bytes / burst))
        return (starts[:, None] + burst * np.arange(nb)[None, :]).ravel()
    br, bc = block or (tile_rows, tile_cols)
    blocks_per_row = ld // bc
    bi, bj = row0 // br, col0 // bc
    start = base + (bi * blocks_per_row + bj) * br * bc * elem_bytes
    nb = math.ceil(tile_rows * tile_cols * elem_bytes / burst)
    return start + burst * np.arange(nb)


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

if __name__ == "__main__":
    # bank conflicts: low-order interleaving with 16 banks: stride s costs gcd(s, 16) cycles
    for s in range(1, 40):
        assert vector_access_cycles(strided_addresses(16, s), 16, "low") == math.gcd(s, 16), s
    # a prime number of banks only conflicts on multiples of the prime; xor fixes power-of-two strides
    assert all(vector_access_cycles(strided_addresses(16, s), 17, "prime") == 1 for s in range(1, 17))
    assert vector_access_cycles(strided_addresses(16, 16), 16, "xor") == 1
    # broadcast: every lane reading the same word costs one cycle
    assert vector_access_cycles(np.zeros(16, dtype=int), 16) == 1
    # padding a 64-column matrix by one word makes column reads conflict-free
    assert vector_access_cycles(matrix_addresses(16, 64, 64), 16) == 16
    assert vector_access_cycles(matrix_addresses(16, 64, 65), 16) == 1
    # area: banks cost periphery, ports cost 50% each
    assert sram_area_um2(1 << 20, 16) > sram_area_um2(1 << 20, 1)
    assert abs(sram_area_um2(1 << 20, 1, 2) / sram_area_um2(1 << 20, 1, 1) - 1.5) < 1e-12
    # DRAM: a sequential stream reaches most of the peak; random single bursts do not; refresh costs ~tRFC/tREFI
    seq = np.arange(32768) * 64
    r_seq = simulate_dram(HBM2_LIKE, seq)
    rng = np.random.default_rng(0)
    rnd = rng.integers(0, 1 << 30, 32768) // 64 * 64
    r_rnd = simulate_dram(HBM2_LIKE, rnd)
    assert r_seq.fraction > 0.85 and r_rnd.fraction < 0.6 * r_seq.fraction, (r_seq.fraction, r_rnd.fraction)
    r_noref = simulate_dram(replace(HBM2_LIKE, tREFI=1e12), seq)
    assert 0.05 < 1 - r_seq.bandwidth / r_noref.bandwidth < 0.12
    assert r_seq.hit_rate > 0.9
    # FR-FCFS never loses to FCFS on a mixed stream
    mix = np.stack([seq[:8192], rnd[:8192]], 1).ravel()
    assert simulate_dram(HBM2_LIKE, mix).seconds <= simulate_dram(replace(HBM2_LIKE, sched="fcfs"), mix).seconds
    # tiles: a blocked tile is one contiguous range
    t = tile_addresses(0, 0, 64, 64, 4096, layout="blocked")
    assert np.all(np.diff(t) == 64) and len(t) == 64 * 64 * 2 // 64
    print("memory.py self-test passed")
    print(f"  {HBM2_LIKE.name}: peak {HBM2_LIKE.peak_bw / 1e9:.0f} GB/s; sequential {r_seq.bandwidth / 1e9:.0f} GB/s "
          f"(row hits {r_seq.hit_rate:.0%}, {r_seq.refreshes} refreshes); random 64 B {r_rnd.bandwidth / 1e9:.0f} GB/s "
          f"(row hits {r_rnd.hit_rate:.0%})")
