"""
pim.py -- processing in and near memory: the bandwidth and energy inside a DRAM stack vs at its pins, bulk bitwise
computation and bit-serial arithmetic inside DRAM rows (checked bit-exactly), bank-level processing units for GEMV and
reductions (time and energy vs a host GPU), and LLM decoding with attention or FC layers moved into the memory
====================================================================================================================

[Why we need it]
    Lectures 10-13 kept hitting the same wall: decoding an LLM reads every weight and the whole KV cache for each
    token, at ~1-4 FLOPs per byte, far below any accelerator's ridge point. Ma and Patterson (2026) put it plainly:
    for LLM inference, memory and interconnect, not compute, are the primary challenges. Memory-centric computing
    stops moving the data to the compute and moves (some of) the compute to the data:
        - IN the memory array: logic-in-memory cells (Kautz, 1969), or analog tricks inside DRAM rows -- activating
          three rows at once computes a bitwise MAJORITY (Ambit, MICRO 2017), from which AND, OR and, with NOT,
          bit-serial arithmetic follow (SIMDRAM, ASPLOS 2021);
        - NEAR the memory array: small processing units next to each bank (Samsung's HBM-PIM, 2021; UPMEM's DRAM-bank
          processors), which see the bank's full internal bandwidth instead of the narrow external interface.
    This module models both and asks the course's usual question: when does it pay?

[Main pieces]
    StackConfig, HBM3_STACK, HBM_PIM_PUBLISHED  : one DRAM stack: external vs internal bandwidth (assumptions labelled)
    ENERGY_PJ_PER_BIT, move_energy_pj            : energy of moving a bit from the array to the host vs to a bank unit
    Subarray                                     : a functional DRAM subarray with RowClone, triple-row activation (MAJ)
                                                   and NOT; bitwise ops and bit-serial addition, counted in AAPs
    bitwise_throughput                           : rows of results per second given banks, tFAW and row size
    PIMSystem, PIM_H100                          : an H100-like host with PIM-enabled HBM stacks
    host_time, pim_time, breakeven_intensity     : roofline times of a kernel on the host and on the PIM units
    gemv, reduction                              : GEMV (batched) and a large reduction on host vs PIM, time and energy
    decode_step                                  : one LLM decode step with FC and/or attention on PIM

[Sources and assumptions]
    Published: Samsung HBM-PIM (Aquabolt-XL, 2021): PIM units running FP16 at 300 MHz, one shared by two banks,
    1.2 TFLOPS per stack (press coverage of the ISSCC/ISCA 2021 papers); 16 lanes per unit is our reading of that
    arithmetic. UPMEM: one 64 MB DRAM bank, 64 KB scratchpad and 24 KB instruction memory per DPU, up to 2,560 DPUs in
    a 20-DIMM server, 32-bit integer multiplication emulated (Gomez-Luna et al., IEEE Access 2022). H100 numbers from
    Lecture 1. DRAM timings from Lecture 7's HBM2-like model.
    ASSUMED (no single published source; varied by the scripts): the internal-to-external bandwidth factor (4x), the
    split of a DRAM access's ~3.9 pJ/bit into array / on-die movement / I/O, the PIM MAC energy (3x a logic-process
    MAC), the PIM compute per byte, and launch / mode-switch overheads.

[Edge cases]
    - Roofline-level models: no refresh, no bank conflicts between host and PIM accesses, perfect data placement unless
      a function says otherwise.
"""

import math
from dataclasses import dataclass, replace

import numpy as np

import course_path

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

import energy_model as em  # noqa: E402
import memory as mem  # noqa: E402
import workloads as wl  # noqa: E402
from hw_specs import H100  # noqa: E402

# =====================================================================================================================
# 1. A DRAM stack: external vs internal bandwidth, and energy
# =====================================================================================================================


@dataclass(frozen=True)
class StackConfig:
    """
    One HBM stack seen from the host and from its banks.

    [Fields] ext_bw: bandwidth at the stack's pins (H100: 3.35 TB/s over 5 stacks = 670 GB/s each); internal_factor:
        how much more bandwidth all banks together can deliver to bank-level units (ASSUMED 4x; HBM-PIM's published
        compute rate implies about 4x, see HBM_PIM_PUBLISHED); capacity (bytes); channels and banks per channel.
    """
    name: str = "HBM3 stack (H100-like)"
    ext_bw: float = H100.mem_bw / 5
    internal_factor: float = 4.0
    capacity: float = H100.mem_capacity / 5
    channels: int = 16
    banks: int = 32

    @property
    def int_bw(self):
        return self.ext_bw * self.internal_factor


HBM3_STACK = StackConfig()

# Samsung HBM-PIM (Aquabolt-XL, 2021), as published: FP16 units at 300 MHz, 1.2 TFLOPS per stack, a unit per two banks.
# 1.2e12 / (300e6 x 2 FLOP x 16 lanes) = 125 units: consistent with 4 PIM dies x 32 units. External HBM2: 1,024 bits at
# 2.4 Gb/s = 307 GB/s. Each unit consumes 16 FP16 values (32 B) per cycle -> 128 x 32 B x 300 MHz = 1.23 TB/s inside.
HBM_PIM_PUBLISHED = {"units": 128, "lanes": 16, "clock_hz": 300e6, "flops": 128 * 16 * 2 * 300e6,
                     "internal_bw": 128 * 32 * 300e6, "external_bw": 1024 * 2.4e9 / 8}

# Energy of one bit moved out of a DRAM stack, ~3.9 pJ/bit in total for HBM2-class memory (published estimates are of
# this order); the SPLIT is ASSUMED: activating and sensing the row (amortized per bit read), moving the bit across the
# die to the TSVs, and the I/O (TSVs, PHY, interposer) to the host. A bank-level unit pays the array and a short local
# hop only.
ENERGY_PJ_PER_BIT = {"array": 0.6, "on-die movement": 2.0, "I/O to host": 1.3, "bank-local hop": 0.3}
PIM_MAC_FACTOR = 3.0              # ASSUMED: a MAC built in a DRAM process costs 3x one in a logic process


def move_energy_pj(nbytes, to="host"):
    """
    Energy (pJ) to deliver nbytes from the DRAM array to the host's memory controller, or to a bank-level unit.

    [Edge cases] Host-side SRAM and register traffic after the controller is not included (it would only add to the
        host's cost).
    """
    e = ENERGY_PJ_PER_BIT
    per_bit = e["array"] + (e["on-die movement"] + e["I/O to host"] if to == "host" else e["bank-local hop"])
    return nbytes * 8 * per_bit


# =====================================================================================================================
# 2. Computing inside DRAM rows (Ambit / SIMDRAM style)
# =====================================================================================================================

class Subarray:
    """
    A functional model of one DRAM subarray that computes with its rows.

    [Idea] A DRAM row is thousands of bits wide. Three in-DRAM primitives (Ambit, Seshadri et al., MICRO 2017):
            RowClone   copy a whole row to another row in the same subarray: one ACTIVATE-ACTIVATE-PRECHARGE (AAP)
            TRA        activate THREE rows at once: the bit lines settle to the bitwise MAJORITY of the three, which
                       is written back into all three (destructive) -- AND = MAJ(a, b, 0), OR = MAJ(a, b, 1)
            NOT        through a "dual-contact cell" row that can be read inverted: two AAPs
        Every operation below is a sequence of these, counted in AAPs; one AAP lasts tRAS + tRP. Because TRA
        destroys its operands, they are first copied into three reserved temporary rows.
    [Args] cols: bits per row (L7's HBM2-like rows are 1 KB = 8,192 bits); rows: data rows
    [Edge cases] Rows are numpy bool arrays; the host's writes and reads of operands are not counted as AAPs.
    """
    T = ("T0", "T1", "T2")

    def __init__(self, cols=8192, rows=64, cfg=mem.HBM2_LIKE):
        self.cols = cols
        self.rows = {i: np.zeros(cols, dtype=bool) for i in range(rows)}
        self.rows.update({t: np.zeros(cols, dtype=bool) for t in self.T})
        self.rows["C0"] = np.zeros(cols, dtype=bool)
        self.rows["C1"] = np.ones(cols, dtype=bool)
        self.rows["DCC"] = np.zeros(cols, dtype=bool)
        self.aap = 0
        self.t_aap = cfg.tRAS + cfg.tRP              # ns

    def write(self, r, bits):
        self.rows[r] = np.asarray(bits, dtype=bool).copy()

    def read(self, r):
        return self.rows[r].copy()

    def clone(self, src, dst):
        """RowClone: dst <- src (1 AAP)."""
        self.rows[dst] = self.rows[src].copy()
        self.aap += 1

    def maj(self, a, b, c, dst):
        """dst <- MAJ(a, b, c): copy the operands into T0-T2, triple-row activate, copy the result out (4 AAPs)."""
        for s, t in zip((a, b, c), self.T):
            self.clone(s, t)
        m = (self.rows["T0"].astype(int) + self.rows["T1"] + self.rows["T2"]) >= 2
        for t in self.T:
            self.rows[t] = m.copy()
        self.rows[dst] = m.copy()
        self.aap += 1                                 # TRA, then activate dst before precharging: one more AAP (4 total)

    def not_(self, src, dst):
        """dst <- NOT src through the dual-contact row (2 AAPs)."""
        self.clone(src, "DCC")
        self.rows[dst] = ~self.rows["DCC"]
        self.aap += 1

    def and_(self, a, b, dst):
        self.maj(a, b, "C0", dst)

    def or_(self, a, b, dst):
        self.maj(a, b, "C1", dst)

    def xor_(self, a, b, dst, tmp=("X0", "X1", "X2")):
        """a XOR b = (a AND NOT b) OR (NOT a AND b)."""
        for t in tmp:
            self.rows.setdefault(t, np.zeros(self.cols, dtype=bool))
        self.not_(b, tmp[0])
        self.and_(a, tmp[0], tmp[1])
        self.not_(a, tmp[0])
        self.and_(tmp[0], b, tmp[2])
        self.or_(tmp[1], tmp[2], dst)

    def add(self, a_rows, b_rows, s_rows, tmp=("c", "nc", "co", "nco", "t")):
        """
        Bit-serial addition of `cols` integers stored VERTICALLY (row i holds bit i of every element), as in SIMDRAM:
            carry_out = MAJ(a, b, carry_in)
            sum       = MAJ(NOT carry_out, MAJ(a, b, NOT carry_in), carry_in)
        [Args] a_rows, b_rows, s_rows: row ids of the bits, least significant first (same length n)
        [Returns] None (results in s_rows; the final carry is dropped: modular n-bit addition)
        """
        for t in tmp:
            self.rows.setdefault(t, np.zeros(self.cols, dtype=bool))
        c, nc, co, nco, t = tmp
        self.clone("C0", c)
        for a, b, s in zip(a_rows, b_rows, s_rows):
            self.maj(a, b, c, co)
            self.not_(c, nc)
            self.maj(a, b, nc, t)
            self.not_(co, nco)
            self.maj(nco, t, c, s)
            self.clone(co, c)

    def seconds(self):
        return self.aap * self.t_aap * 1e-9


def to_vertical(values, bits):
    """Integers (one per column) -> list of `bits` rows, least significant bit first."""
    v = np.asarray(values, dtype=np.int64)
    return [((v >> i) & 1).astype(bool) for i in range(bits)]


def from_vertical(rows):
    return sum(r.astype(np.int64) << i for i, r in enumerate(rows))


def bitwise_throughput(aaps_per_op, row_bits=8192, cfg=mem.HBM2_LIKE, channels=None, banks=None, faw_limited=True,
                       subarrays_per_bank=1):
    """
    Result bits per second of an in-DRAM operation that takes `aaps_per_op` AAPs per row of results.

    [Idea] Each bank (or each of its subarrays, with subarray-level parallelism) works on its own rows concurrently.
        Activations draw current, so DRAM allows at most 4 ACTIVATEs per tFAW window per channel; an AAP has two
        activations, so a channel can start at most 2 AAPs per tFAW: concurrent AAPs per channel <= tAAP / (tFAW / 2).
    [Returns] bits per second
    [Edge cases] faw_limited=False shows what the array could do without the power limit.
    """
    channels = channels or cfg.channels
    banks = banks or cfg.banks
    t_aap = (cfg.tRAS + cfg.tRP) * 1e-9
    units = banks * subarrays_per_bank
    if faw_limited:
        units = min(units, t_aap / (cfg.tFAW * 1e-9 / 2))
    return channels * units * row_bits / (aaps_per_op * t_aap)


# =====================================================================================================================
# 3. Bank-level PIM units next to the host
# =====================================================================================================================

@dataclass(frozen=True)
class PIMSystem:
    """
    A host accelerator (an H100-like GPU) whose HBM stacks contain bank-level PIM units.

    [Fields] host (hw_specs Machine); stacks; stack (StackConfig); pim_flops_per_byte: PIM compute provisioned per byte
        of INTERNAL bandwidth (ASSUMED 1.0: enough for a GEMV in fp16, 2 FLOP per 2-byte weight); pim_launch_s and
        mode_switch_s: ASSUMED overheads of starting PIM work and switching the banks between host and PIM mode
    [Properties] ext_bw, int_bw, pim_flops
    """
    host: object = H100
    stacks: int = 5
    stack: StackConfig = HBM3_STACK
    pim_flops_per_byte: float = 1.0
    pim_launch_s: float = 2e-6
    mode_switch_s: float = 1e-6

    @property
    def ext_bw(self):
        return self.stacks * self.stack.ext_bw

    @property
    def int_bw(self):
        return self.stacks * self.stack.int_bw

    @property
    def pim_flops(self):
        return self.int_bw * self.pim_flops_per_byte


PIM_H100 = PIMSystem()


def host_time(flops, nbytes, system=PIM_H100, launch_s=4e-6):
    """Roofline time of a kernel on the host: max(FLOPs / peak, bytes / external bandwidth) + a launch."""
    return max(flops / system.host.peak("bf16"), nbytes / system.ext_bw) + launch_s


def pim_time(flops, nbytes, system=PIM_H100, extra_bytes=0.0):
    """
    Roofline time on the PIM units: max(FLOPs / PIM peak, bytes / internal bandwidth), plus extra_bytes that must cross
    the external interface (broadcast inputs, gathered outputs), a launch and a mode switch in and out.
    """
    return (max(flops / system.pim_flops, nbytes / system.int_bw) + extra_bytes / system.ext_bw +
            system.pim_launch_s + 2 * system.mode_switch_s)


def breakeven_intensity(system=PIM_H100):
    """
    The arithmetic intensity (FLOP per byte of operands) below which the PIM units are faster than the host.

    [Idea] At low intensity the host is bound by external bandwidth (time = D / B_ext) and the PIM units by internal
        bandwidth (D / B_int): PIM wins by B_int / B_ext. As intensity I grows, PIM becomes compute-bound
        (time = I D / P_pim) while the host stays memory-bound until its ridge. They meet where I D / P_pim = D / B_ext:
            I* = P_pim / B_ext
    """
    return system.pim_flops / system.ext_bw


def gemv(M, K, batch=1, system=PIM_H100, elem=2):
    """
    y = W x for `batch` vectors, W (M x K) in fp16/bf16 stored in the stacks.

    [Idea] Host: stream W through the pins (and reuse it across the batch). PIM: every bank-level unit streams its
        slice of W's rows at internal bandwidth and multiplies them by the broadcast x; partial y values return to the
        host. Energy: data movement (move_energy_pj) + MACs (Lecture 1's fp16 MAC; x PIM_MAC_FACTOR in the DRAM).
    [Returns] dict(host_s, pim_s, speedup, host_pj, pim_pj, energy_ratio, intensity)
    """
    wbytes = M * K * elem
    flops = 2 * M * K * batch
    io = (K + M) * batch * elem                                   # x in, y out
    th = host_time(flops, wbytes + io, system)
    tp = pim_time(flops, wbytes, system, extra_bytes=io)
    mac = em.mac_energy_pj("fp16")
    eh = move_energy_pj(wbytes + io, "host") + (flops / 2) * mac
    ep = move_energy_pj(wbytes, "pim") + move_energy_pj(io, "host") + (flops / 2) * mac * PIM_MAC_FACTOR
    return {"host_s": th, "pim_s": tp, "speedup": th / tp, "host_pj": eh, "pim_pj": ep, "energy_ratio": eh / ep,
            "intensity": flops / wbytes}


def reduction(n, system=PIM_H100, elem=4, units=None):
    """
    Sum of n elements stored in the stacks: the host streams them all; PIM units sum their banks' share and send one
    partial sum each to the host (units partials cross the pins).
    """
    units = units or system.stacks * system.stack.channels * system.stack.banks // 2
    nbytes = n * elem
    th = host_time(n, nbytes, system)
    tp = pim_time(n, nbytes, system, extra_bytes=units * elem)
    return {"host_s": th, "pim_s": tp, "speedup": th / tp, "units": units}


# =====================================================================================================================
# 4. LLM decode with PIM
# =====================================================================================================================

PLACEMENTS = ("GPU only", "attention on PIM", "FC on PIM", "FC and attention on PIM")


def decode_step(cfg, batch, ctx, placement="GPU only", system=PIM_H100, kv_heads=None):
    """
    One decode step (one new token for each of `batch` sequences) of a model on one PIM-enabled GPU.

    [Idea] Per step: FC layers (all weight matrices) are a batched GEMV -- their intensity grows with the batch;
        attention reads each sequence's KV cache -- its intensity is the GQA group size G = heads / KV heads at any
        batch (Lecture 10). Each part runs on the GPU or on the PIM units; the two run one after the other (the banks
        are either in host mode or in PIM mode), and every layer that uses PIM pays its mode switches.
    [Args] cfg: workloads.TransformerConfig; kv_heads overrides cfg.n_kv_heads (e.g. = heads for an MHA variant)
    [Returns] dict(seconds, fc_s, attn_s, tokens_per_s (all sequences), fits, energy_j)
    [Edge cases] fits = False when weights + KV caches exceed the GPU's 80 GB.
    """
    kvh = kv_heads or cfg.n_kv_heads
    G = cfg.n_heads / kvh
    w = cfg.params() * 2
    kv = batch * 2 * cfg.n_layers * kvh * cfg.head_dim * 2 * ctx
    fc_flops = 2 * cfg.params() * batch
    at_flops = kv * G                                      # 2 FLOPs per KV element per query head sharing it, /2 B
    L = cfg.n_layers
    if placement in ("FC on PIM", "FC and attention on PIM"):
        fc = max(fc_flops / system.pim_flops, w / system.int_bw) + L * (system.pim_launch_s + 2 * system.mode_switch_s)
    else:
        fc = max(fc_flops / system.host.peak("bf16"), w / system.ext_bw)
    if placement in ("attention on PIM", "FC and attention on PIM"):
        at = max(at_flops / system.pim_flops, kv / system.int_bw) + L * (system.pim_launch_s + 2 * system.mode_switch_s)
    else:
        at = max(at_flops / system.host.peak("bf16"), kv / system.ext_bw)
    t = fc + at
    mac = em.mac_energy_pj("fp16")
    e = 0.0
    e += (move_energy_pj(w, "pim") + fc_flops / 2 * mac * PIM_MAC_FACTOR) if "FC" in placement and "on PIM" in placement \
        else (move_energy_pj(w, "host") + fc_flops / 2 * mac)
    e += (move_energy_pj(kv, "pim") + at_flops / 2 * mac * PIM_MAC_FACTOR) if "attention" in placement \
        else (move_energy_pj(kv, "host") + at_flops / 2 * mac)
    fits = w + kv <= system.host.mem_capacity
    return {"seconds": t, "fc_s": fc, "attn_s": at, "tokens_per_s": batch / t, "fits": fits, "energy_j": e * 1e-12,
            "G": G}


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

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    sa = Subarray(cols=4096)
    a, b = rng.random(4096) < 0.5, rng.random(4096) < 0.5
    sa.write(0, a)
    sa.write(1, b)
    sa.and_(0, 1, 2)
    assert np.array_equal(sa.read(2), a & b) and sa.aap == 4
    sa.or_(0, 1, 3)
    assert np.array_equal(sa.read(3), a | b)
    sa.xor_(0, 1, 4)
    assert np.array_equal(sa.read(4), a ^ b)
    # bit-serial 8-bit addition of 4,096 pairs, checked against numpy (mod 256)
    x, y = rng.integers(0, 256, 4096), rng.integers(0, 256, 4096)
    sa2 = Subarray(cols=4096)
    for i, r in enumerate(to_vertical(x, 8)):
        sa2.write(10 + i, r)
    for i, r in enumerate(to_vertical(y, 8)):
        sa2.write(20 + i, r)
    sa2.add(list(range(10, 18)), list(range(20, 28)), list(range(30, 38)))
    assert np.array_equal(from_vertical([sa2.read(30 + i) for i in range(8)]), (x + y) % 256)
    # published HBM-PIM arithmetic: ~1.2 TFLOPS, ~4x internal bandwidth
    assert abs(HBM_PIM_PUBLISHED["flops"] - 1.23e12) < 0.01e12
    assert abs(HBM_PIM_PUBLISHED["internal_bw"] / HBM_PIM_PUBLISHED["external_bw"] - 4.0) < 0.01
    # break-even: a GEMV (1 FLOP/byte) is faster on PIM; batch 64 is faster on the host
    assert gemv(4096, 4096)["speedup"] > 1 and gemv(4096, 4096, 64)["speedup"] < 1
    assert abs(breakeven_intensity() - 4.0) < 1e-9
    d = decode_step(wl.LLAMA3_8B, 1, 4096)
    assert d["fits"]
    print("pim.py self-test passed")
    print(f"  in-DRAM AND: 4 AAPs per row; 8-bit add: {sa2.aap // 1} AAPs for 4,096 additions ({sa2.seconds() * 1e6:.1f} us);"
          f" GEMV 4096x4096 on PIM {gemv(4096, 4096)['speedup']:.2f}x faster, {gemv(4096, 4096)['energy_ratio']:.1f}x less "
          f"energy; break-even intensity {breakeven_intensity():.0f} FLOP/byte")
