"""
imc.py -- computing IN memory arrays: an analog crossbar that multiplies a matrix by a vector with Ohm's and
Kirchhoff's laws (bit-serial or pulse-width inputs, bit-sliced or analog weights, device variation, read noise, drift
and ADC quantization), a digital in-memory baseline that is exact, an energy model in which every term is labelled,
and a small network run on the crossbar
====================================================================================================================

[Why we need it]
    Lecture 14 moved logic NEXT to the DRAM banks. This lecture goes one step further: the memory array itself does
    the multiply-accumulate. Store a weight as a conductance G (a resistive device: RRAM, PCM, flash) or as a bit in
    an SRAM cell, apply the input as a voltage V on the row, and the current on each column is
        I_j = sum_i V_i * G_ij                                    (Ohm: I = V G, Kirchhoff: currents add on a wire)
    -- a whole matrix-vector product in one step, without moving a single weight. Two things are saved:
        - weight movement: the weights never leave the array (Lectures 1, 7: moving a byte costs far more than a MAC);
        - access amortization (Verma et al., 2019): N rows share ONE bit-line evaluation instead of N reads.
    And three things are paid:
        - the result is analog: a column's value must be converted by an ADC, whose energy grows 2-4x per bit;
        - the result is noisy: devices vary, drift and fluctuate, so a MAC is accurate to a few bits, not exactly;
        - multi-bit numbers must be split (bit-serial inputs, bit-sliced weights), multiplying the number of
          conversions.
    This module models all of it so that the scripts can ask where the saving comes from and where it goes.

[Main pieces]
    PUBLISHED, PCM_PUBLISHED             : published chips and device numbers (with sources), for comparison only
    Crossbar, PCM_LIKE, SRAM_LIKE         : an array's precision and non-ideality parameters (presets ASSUMED)
    quantize_weights, quantize_inputs     : the integer grids the crossbar computes on
    CrossbarArray                         : weights programmed into conductances; .mvm() computes X W^T in analog
                                            (tiles of `rows`, slices, input pulses, ADC, drift, compensation)
    lossless_adc_bits, adc_lsb_units      : ADC resolution needed for an exact column sum; the ADC's LSB
    dcim_mvm, adder_tree_full_adders      : digital in-memory computing (AND + adder tree), exact
    adc_energy_pj, adc_thermal_limit_pj   : ADC energy per conversion (Walden / Schreier regimes; 8kT*SNR bound)
    IMCEnergy, PCM_ENERGY, SRAM_ENERGY    : per-event energies of an analog macro (ASSUMED, 22/28-nm class)
    analog_energy, dcim_energy, digital_energy : energy per MAC of the three ways to compute, with breakdowns
    glyph_prototypes, glyph_dataset, train_mlp, mlp_forward, analog_mlp_forward : a toy task and a 3-layer MLP

[Sources and assumptions]
    Published (used for comparison and to set ASSUMED defaults, never as results of these notes):
        - IBM HERMES (Le Gallo et al., Nature Electronics 2023, arXiv:2212.02872): 64 cores of 256 x 256 PCM unit
          cells (4 devices each), 14 nm, 144 mm^2, 8-bit PWM inputs; MVM peak 63.1 TOPS, 9.76 TOPS/W, 1.55 TOPS/mm^2
          (1-phase, Table 1); ResNet-9 on CIFAR-10 92.81% vs 93.67% in software; weights equivalent to 3-4 bits.
        - PCM devices (Joshi et al., Nature Communications 2020): G_max 25 uS, programming error < 1.2 uS (median
          0.94 uS), drift G(t) = G(t0) (t/t0)^-nu with nu ~ 0.06; without compensation a ResNet-32 fell to 10% within
          ~1000 s, with global drift compensation it stayed above 92.6% after a day.
        - TSMC all-digital SRAM CIM (Chih et al., ISSCC 2021): 22 nm, 89 TOPS/W and 16.3 TOPS/mm^2; 256 inputs,
          4-bit weight nibbles, bit-serial inputs, an adder tree.
        - ADC energy: the thermal-noise bound E >= 8 kT SNR and the Schreier figure of merit (Murmann, "Energy
          limits in A/D converters", 2012/2013).
    ASSUMED (varied by the scripts): the ADC figures of merit (Walden 2 fJ/step, Schreier 180 dB), cell / row / column
    energies, the logic-energy scaling from 45 nm to a 22/28-nm-class node (x0.4), the read and ADC noise levels, the
    spread of the drift exponent, the input activity factor.

[Conventions]
    Conductances are normalized: g = 1 is G_max. Weights are stored differentially (a G+ and a G- device per weight)
    and the two column currents are subtracted in analog before ONE conversion. Weights use one scale per output
    (crossbar column); inputs one scale per tensor.

[Edge cases]
    - IR drop on long wires, sneak paths, ADC non-linearity, temperature and endurance are not modeled (the notes
      discuss them).
    - Drift is applied for t >= T0_S (25 s, the first read in Joshi et al.); earlier times raise ValueError.
"""

import math
from dataclasses import dataclass, replace

import numpy as np

import course_path

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

import energy_model as em  # noqa: E402
from quant import sqnr_db  # noqa: E402

K_BOLTZMANN = 1.380649e-23      # J/K
T_KELVIN = 300.0
T0_S = 25.0                     # first read after programming (s); drift is measured from here (Joshi et al. 2020)

# =====================================================================================================================
# 0. Published numbers (for comparison only)
# =====================================================================================================================

PUBLISHED = {
    "IBM HERMES (PCM, 14 nm)": dict(
        year=2023, cores=64, rows=256, cols=256, devices_per_weight=4, area_mm2=144.0, input_bits=8,
        mvm_latency_s=133e-9, tops=63.1, tops_per_w=9.76, tops_per_mm2=1.55, weights=64 * 256 * 256,
        accuracy="ResNet-9 CIFAR-10: 92.81% (software 93.67%)", weight_bits_equiv="3-4",
        source="Le Gallo et al., Nature Electronics 2023 (arXiv:2212.02872), Table 1, MVM 1-phase"),
    "TSMC digital SRAM CIM (22 nm)": dict(
        year=2021, inputs=256, weight_bits=4, tops_per_w=89.0, tops_per_mm2=16.3,
        source="Chih et al., ISSCC 2021, paper 16.4 (title figures)"),
}

PCM_PUBLISHED = dict(g_max_us=25.0, prog_sigma_median_us=0.94, prog_sigma_max_us=1.2, drift_nu=0.06,
                     source="Joshi et al., Nature Communications 11, 2473 (2020)")

# =====================================================================================================================
# 1. The crossbar: configuration and the integer grids it computes on
# =====================================================================================================================


@dataclass(frozen=True)
class Crossbar:
    """
    Precision and non-idealities of one analog in-memory array.

    [Fields]
        rows        : rows activated together = terms summed by one column before one ADC conversion. A matrix with
                      more inputs K is split into ceil(K / rows) row tiles whose digital partial sums are added.
        weight_bits : signed weight precision (sign + magnitude bits), one scale per output column
        cell_bits   : magnitude bits one device (pair) stores. If cell_bits >= weight_bits - 1 the whole magnitude is
                      one analog level ("analog weights", PCM/RRAM style); cell_bits = 1 is a binary SRAM cell and the
                      weight is BIT-SLICED over weight_bits - 1 column pairs combined digitally by shift-and-add.
        input_bits  : input precision. Unsigned when the inputs are >= 0 (after ReLU); otherwise sign + magnitude in two
                      passes (positive part, negative part).
        input_mode  : "bit-serial" (one 0/1 pulse per input bit, one conversion per bit) or "pwm" (the whole
                      magnitude as one pulse of proportional length, one conversion)
        adc_bits    : ADC resolution (None = ideal, infinitely fine ADC)
        adc_range   : full scale as a fraction of the largest signal a column can produce (rows x full levels);
                      1.0 never clips, smaller values clip rare large sums but give a finer LSB (see calibrate)
        sigma_static: static error per device, fraction of G_max: programming error (NVM) or capacitor mismatch (SRAM)
        sigma_read  : read noise per device per conversion, fraction of G_max
        sigma_adc   : input-referred noise of the column readout and ADC, fraction of the ADC full scale
        drift_nu, drift_nu_sigma : drift exponent of G(t) = G(T0) (t/T0)^-nu, mean and spread across devices
    """
    name: str = "crossbar"
    rows: int = 256
    weight_bits: int = 8
    cell_bits: int = 7
    input_bits: int = 8
    input_mode: str = "bit-serial"
    adc_bits: object = 8
    adc_range: float = 1.0
    sigma_static: float = 0.0
    sigma_read: float = 0.0
    sigma_adc: float = 0.0
    drift_nu: float = 0.0
    drift_nu_sigma: float = 0.0


# Presets. [Hardware link] PCM_LIKE follows HERMES's choices (analog weights, pulse-width inputs, 256 rows) with the
# device numbers of Joshi et al.: programming error 0.94 uS / 25 uS = 3.8% of G_max, nu = 0.06. The read noise (1%),
# the ADC noise (0.1% of full scale) and the drift spread (0.02) are ASSUMED. SRAM_LIKE stores exact bits (binary
# cells, bit-sliced weights) and computes in the charge domain with capacitors whose mismatch is ASSUMED to be 0.5%.
PCM_LIKE = Crossbar(name="PCM-like (analog weights, PWM inputs)", rows=256, weight_bits=8, cell_bits=7, input_bits=8,
                    input_mode="pwm", adc_bits=8, sigma_static=0.038, sigma_read=0.01, sigma_adc=1e-3,
                    drift_nu=0.06, drift_nu_sigma=0.02)
SRAM_LIKE = Crossbar(name="SRAM-like (binary cells, bit-serial)", rows=256, weight_bits=8, cell_bits=1, input_bits=8,
                     input_mode="bit-serial", adc_bits=8, sigma_static=0.005, sigma_read=0.0, sigma_adc=1e-3)


def quantize_weights(W, bits):
    """
    Symmetric integer weights, one scale per output row of W (= per crossbar column).

    [Idea] q = round(W / s) with s = max|W_row| / (2^(bits-1) - 1), so each column uses its devices' full range.
    [Args] W: (M, K) float; bits: signed precision (>= 2)
    [Returns] (q, scale): q int64 (M, K) in [-(2^(bits-1)-1), 2^(bits-1)-1], scale (M, 1) float
    [Edge cases] An all-zero row gets scale 1 (its q is all zero anyway).
    [Python tip] keepdims=True keeps the reduced axis with length 1, so W / scale broadcasts row by row.
    """
    qmax = 2 ** (bits - 1) - 1
    scale = np.max(np.abs(W), axis=1, keepdims=True) / qmax
    scale[scale == 0] = 1.0
    return np.clip(np.round(W / scale), -qmax, qmax).astype(np.int64), scale


def quantize_inputs(X, bits, x_max=None, signed=None):
    """
    Integer inputs with one scale for the whole tensor.

    [Args] X: (B, K) float; bits: precision; x_max: clipping value (default max|X|); signed: force the sign handling
        (default: signed iff X has negative entries)
    [Returns] (q int64 (B, K), scale float, signed bool). Unsigned inputs use all `bits` for the magnitude
        (0 .. 2^bits - 1); signed ones use sign + (bits - 1) magnitude bits.
    [Edge cases] Values beyond x_max are clipped (this is how a calibrated input range behaves in hardware).
    """
    if signed is None:
        signed = bool(np.any(X < 0))
    levels = 2 ** (bits - 1) - 1 if signed else 2 ** bits - 1
    if x_max is None:
        x_max = float(np.max(np.abs(X))) or 1.0
    scale = x_max / levels
    lo = -levels if signed else 0
    return np.clip(np.round(X / scale), lo, levels).astype(np.int64), scale, signed


def lossless_adc_bits(n_rows, cell_levels, input_levels=1):
    """
    ADC bits needed to convert a signed column sum EXACTLY.

    [Idea] A column adds n_rows products of an input level (0 .. input_levels) and a weight digit (-cell_levels ..
        cell_levels); the sum takes 2 n L P + 1 integer values. 1-bit inputs on binary cells: 256 rows need 10 bits.
    [Args] n_rows; cell_levels L = 2^cell_bits - 1; input_levels P = 1 for bit-serial, 2^bits - 1 for PWM inputs
    [Returns] int bits
    """
    return math.ceil(math.log2(2 * n_rows * cell_levels * input_levels + 1))


def adc_lsb_units(n_rows, cell_levels, adc_bits, adc_range=1.0):
    """
    The ADC's step, in units of one cell's full-level current at a full input pulse ("unit currents").

    [Idea] The ADC must cover +- adc_range x (largest possible column signal). Its step is chosen as a power of two
        of the unit current, so that the digital shift-and-add that follows is a shift: the smallest 2^k with
        2^(adc_bits-1) * 2^k >= adc_range * n_rows * cell_levels. Bit-serial column signals are whole numbers of unit
        currents and PWM signals multiples of 2^-b (b input bits), so a step that fine converts them exactly (only
        clipping can remain).
    [Returns] float, step in unit currents (may be < 1)
    [Edge cases] k may be negative (a finer step than one unit): useful when adc_range is small.
    """
    need = adc_range * n_rows * cell_levels
    return 2.0 ** math.ceil(math.log2(need / 2 ** (adc_bits - 1)))


def adc_convert(I_units, lsb, bits):
    """
    Uniform signed ADC: round to the nearest step and clip to [-2^(bits-1), 2^(bits-1) - 1] steps.

    [Args] I_units: column signals in unit currents; lsb: step (unit currents); bits: resolution (None = ideal)
    [Returns] converted values in unit currents
    """
    if bits is None:
        return I_units
    half = 2 ** (bits - 1)
    return np.clip(np.round(I_units / lsb), -half, half - 1) * lsb


# =====================================================================================================================
# 2. A programmed array
# =====================================================================================================================

class CrossbarArray:
    """
    A weight matrix programmed into crossbar devices, and analog matrix-vector products with it.

    [Idea] Programming (once): quantize W to integers q; split |q| into digits of slice_bits bits (one digit per
        column pair = slice); store digit / L as a normalized conductance on the G+ device if q > 0 or on the G- device
        if q < 0; add the static error; draw each device's drift exponent.
        Computing (every call): quantize the inputs; for each row tile, slice, sign pass and input pulse, the column
        signal is sum_i v_i (g+_ij - g-_ij) (analog subtraction); add read and ADC noise; convert; and accumulate
        digitally with the right power-of-two weight. With ideal devices and a lossless ADC this reproduces the
        integer product xq @ q^T EXACTLY (checked in the self-test).
    [Args] W: (M, K) float weights; xbar: Crossbar; rng: numpy Generator for the programming randomness
    [Edge cases] K > rows is tiled; the last tile may be shorter. Drift exponents are clipped at 0 (no growth).
        The programming generator must be INDEPENDENT of the one that produced W: with the same seed, the "random"
        device errors would be the weights' own random draws, i.e. perfectly correlated with W (a bias, not noise).
        The default seed (15015) is not used anywhere else in the course.
    """

    def __init__(self, W, xbar=PCM_LIKE, rng=None):
        rng = np.random.default_rng(15015) if rng is None else rng
        self.xbar = xbar
        self.M, self.K = W.shape
        self.q, self.w_scale = quantize_weights(W, xbar.weight_bits)
        mag_bits = xbar.weight_bits - 1
        self.slice_bits = min(xbar.cell_bits, mag_bits)
        self.n_slices = math.ceil(mag_bits / self.slice_bits)
        self.L = 2 ** self.slice_bits - 1
        mag, pos, neg = np.abs(self.q), self.q > 0, self.q < 0
        g = np.zeros((self.n_slices, 2, self.M, self.K))
        for s in range(self.n_slices):
            digit = (mag >> (self.slice_bits * s)) & self.L        # [Python tip] >> and & pick bits of an integer
            g[s, 0] = np.where(pos, digit, 0) / self.L
            g[s, 1] = np.where(neg, digit, 0) / self.L
        self.g_ideal = g
        if xbar.sigma_static > 0:
            g = np.clip(g + rng.normal(0.0, xbar.sigma_static, g.shape), 0.0, 1.0)
        self.g_prog = g
        self.nu = None
        if xbar.drift_nu > 0:
            self.nu = np.maximum(rng.normal(xbar.drift_nu, xbar.drift_nu_sigma, g.shape), 0.0)
        self.tiles = [(a, min(a + xbar.rows, self.K)) for a in range(0, self.K, xbar.rows)]
        self.adc_range = xbar.adc_range

    def conductances(self, t_s=None):
        """Normalized conductances at time t_s after programming (None = no drift); see the module's drift model."""
        if t_s is None or self.nu is None:
            return self.g_prog
        if t_s < T0_S:
            raise ValueError(f"drift is defined from T0 = {T0_S} s on")
        return self.g_prog * (t_s / T0_S) ** (-self.nu)

    def _pulses(self, signed):
        """
        Input pulses: list of (digital weight, function int levels -> analog amplitudes in [0, 1]).

        [Idea] Bit-serial: pulse b carries bit b of every input (amplitude 0 or 1) and is weighted 2^b digitally.
            PWM: one pulse whose length is v / 2^b of the full pulse (b magnitude bits), weighted 2^b.
        """
        xb = self.xbar
        mag_bits = xb.input_bits - 1 if signed else xb.input_bits
        if xb.input_mode == "bit-serial":
            return [(2 ** b, (lambda v, b=b: ((v >> b) & 1).astype(np.float64))) for b in range(mag_bits)]
        if xb.input_mode == "pwm":
            full = 2 ** mag_bits
            return [(full, lambda v, full=full: v / full)]
        raise ValueError(f"unknown input_mode {xb.input_mode!r}")

    def mvm(self, X, x_max=None, t_s=None, compensate=False, rng=None, signed=None, column_signals=None):
        """
        Analog Y = X W^T.

        [Args] X: (B, K) inputs; x_max: input clipping value (default max|X|); t_s: seconds since programming (drift);
            compensate: global drift compensation -- divide the outputs by alpha = sum G(t) / sum G(T0), the factor a
            calibration read of the array measures (Joshi et al. 2020); rng: noise generator; signed: force input sign
            handling; column_signals: a list to which the ideal column signals (unit currents) are appended, for
            calibrating the ADC range.
        [Returns] dict: y (B, M) float, conversions per input vector, pulses, passes
        [Edge cases] With adc_bits None the ADC is ideal. Read noise std per conversion is sigma_read x
            sqrt(2 sum_i v_i^2) (two independent devices per weight).
        """
        xb = self.xbar
        rng = np.random.default_rng(15016) if rng is None else rng
        xq, x_scale, signed = quantize_inputs(X, xb.input_bits, x_max, signed)
        pulses = self._pulses(signed)
        passes = [(1, np.maximum(xq, 0))] + ([(-1, np.maximum(-xq, 0))] if signed else [])
        g = self.conductances(t_s)
        gdiff = g[:, 0] - g[:, 1]                               # (S, M, K): analog differential sensing
        y = np.zeros((X.shape[0], self.M))
        conversions = 0
        for a, b in self.tiles:
            n = b - a
            lsb = None if xb.adc_bits is None else adc_lsb_units(n, self.L, xb.adc_bits, self.adc_range)
            fs = None if lsb is None else lsb * 2 ** (xb.adc_bits - 1)
            for s in range(self.n_slices):
                Gt = gdiff[s][:, a:b].T * self.L                # in unit currents per unit input
                w_slice = 2 ** (self.slice_bits * s)
                for sign, v in passes:
                    vt = v[:, a:b]
                    for w_pulse, amp in pulses:
                        vin = amp(vt)
                        I = vin @ Gt                            # (B, M): Kirchhoff's sum on every column
                        if column_signals is not None:
                            column_signals.append(np.abs(I).ravel())
                        if xb.sigma_read > 0:
                            I = I + rng.standard_normal(I.shape) * (xb.sigma_read * self.L) * \
                                np.sqrt(2 * np.sum(vin ** 2, axis=1, keepdims=True))
                        if xb.sigma_adc > 0 and fs is not None:
                            I = I + rng.standard_normal(I.shape) * (xb.sigma_adc * fs)
                        I = adc_convert(I, lsb, xb.adc_bits)
                        y += (sign * w_slice * w_pulse) * I
                        conversions += self.M
        if compensate and t_s is not None and self.nu is not None:
            y /= np.sum(g) / np.sum(self.g_prog)
        return {"y": y * x_scale * self.w_scale.T, "conversions": conversions, "pulses": len(pulses),
                "passes": len(passes)}

    def calibrate(self, X_cal, x_max=None, percentile=99.9, signed=None):
        """
        Set the ADC range from data: the full scale covers `percentile` % of the ideal column signals.

        [Idea] A column CAN produce +- rows x L unit currents, but for real data the sum of many products with mixed
            signs is ~ sqrt(rows) times one product. Covering only what occurs gives a much finer step for the same
            bits; the rare larger sums are clipped.
        [Returns] the new adc_range (fraction of the largest possible signal)
        """
        sig = []
        # run once with ideal devices and an ideal ADC, collecting the column signals; then restore the array
        saved = (self.xbar, self.g_prog)
        self.xbar = replace(self.xbar, adc_bits=None, sigma_read=0.0, sigma_adc=0.0)
        self.g_prog = self.g_ideal
        try:
            self.mvm(X_cal, x_max=x_max, signed=signed, column_signals=sig)
        finally:                                    # [Python tip] finally runs even if mvm raises
            self.xbar, self.g_prog = saved
        top = float(np.percentile(np.concatenate(sig), percentile))
        n = max(b - a for a, b in self.tiles)
        self.adc_range = max(top / (n * self.L), 1e-6)
        return self.adc_range


def digital_reference(W, X, weight_bits, input_bits, x_max=None, signed=None):
    """Exact integer product of the quantized operands (what a digital accelerator at these precisions computes)."""
    q, ws = quantize_weights(W, weight_bits)
    xq, xs, _ = quantize_inputs(X, input_bits, x_max, signed)
    return (xq @ q.T) * xs * ws.T


def effective_bits(snr_db):
    """Bits of an ideal uniform quantizer with the same SNR: (SNR - 1.76) / 6.02."""
    return (snr_db - 1.76) / 6.02


# =====================================================================================================================
# 3. Digital in-memory computing (exact)
# =====================================================================================================================

def adder_tree_full_adders(n):
    """
    Full adders in a tree that sums n one-bit values: level l has n / 2^l adders of l bits.

    [Returns] int; ~2 n for large n (sum of l / 2^l = 2): 256 inputs -> 502 full adders
    [Edge cases] n is rounded up to a power of two.
    """
    levels = math.ceil(math.log2(n))
    n2 = 2 ** levels
    return sum((n2 >> l) * l for l in range(1, levels + 1))


def dcim_mvm(W, X, weight_bits=8, input_bits=8, rows=256, x_max=None):
    """
    Digital in-memory MVM: every weight bit ANDed with every input bit, column sums by an adder tree, shift-and-add.

    [Idea] TSMC-style DCIM (Chih et al. 2021): the input arrives one bit per cycle; each SRAM column holds one bit of
        each weight; a NOR/AND gate per cell forms the 1-bit products and an adder tree sums the rows. Exact by
        construction -- this function checks that against the integer product.
    [Returns] dict: y (float), y_int, bit_products per input vector, adder-tree full adders per vector
    """
    q, ws = quantize_weights(W, weight_bits)
    xq, xs, signed = quantize_inputs(X, input_bits, x_max)
    in_bits = input_bits - 1 if signed else input_bits
    sx, mx = np.sign(xq), np.abs(xq)
    sw, mw = np.sign(q), np.abs(q)
    y = np.zeros((X.shape[0], W.shape[0]), dtype=np.int64)
    for bi in range(in_bits):
        xb = ((mx >> bi) & 1) * sx                          # sign applied per input (two's-complement detail aside)
        for bj in range(weight_bits - 1):
            wb = ((mw >> bj) & 1) * sw
            y += (xb @ wb.T) << (bi + bj)                   # one adder-tree pass per (input bit, weight bit)
    tiles = math.ceil(W.shape[1] / rows)
    return {"y": y * xs * ws.T, "y_int": y, "bit_products": W.shape[0] * W.shape[1] * in_bits * (weight_bits - 1),
            "full_adders": tiles * W.shape[0] * in_bits * (weight_bits - 1) * adder_tree_full_adders(min(rows, W.shape[1]))}


# =====================================================================================================================
# 4. Energy
# =====================================================================================================================

NODE_SCALE = 0.4        # ASSUMED: logic/SRAM energy at a 22/28-nm-class node relative to Horowitz's 45 nm (Lecture 1)
ADC_FOM_W_FJ = 2.0      # ASSUMED Walden FOM, fJ per conversion step (energy / 2^ENOB); good low-power SAR ADCs
ADC_FOM_S_DB = 180.0    # ASSUMED Schreier FOM, dB (SNDR + 10 log10(f/2 / P)); the thermal-noise-limited regime


def adc_energy_pj(bits, fom_w_fj=ADC_FOM_W_FJ, fom_s_db=ADC_FOM_S_DB):
    """
    Energy of one ADC conversion (pJ): the larger of the two survey regimes.

    [Idea] At low resolution, ADC energy is set by circuits that switch per decision: ~FOM_W x 2^bits (x2 per bit).
        At high resolution it is set by thermal noise: to halve the noise voltage the capacitors must be 4x larger,
        so energy ~ SNR (x4 per bit), expressed with the Schreier FOM: E = 0.5 x 10^((SNDR - FOM_S) / 10).
        With the defaults the two cross near 11 bits.
    [Args] bits: ENOB; fom_w_fj, fom_s_db: figures of merit (ASSUMED defaults)
    [Returns] pJ per conversion
    """
    walden = fom_w_fj * 1e-3 * 2.0 ** bits
    sndr = 6.02 * bits + 1.76
    thermal = 0.5 * 10 ** ((sndr - fom_s_db) / 10) * 1e12
    return max(walden, thermal)


def adc_thermal_limit_pj(bits):
    """The fundamental bound E >= 8 kT SNR (Murmann), pJ: what physics allows, typically ~100x below real ADCs."""
    snr = 10 ** ((6.02 * bits + 1.76) / 10)
    return 8 * K_BOLTZMANN * T_KELVIN * snr * 1e12


def ktc_min_cap_f(n_rows, v_swing, bits):
    """
    Smallest unit capacitor (F) of a charge-sharing column whose kT/C noise stays below half an LSB.

    [Idea] n cells of capacitance C share charge: the column voltage is the AVERAGE of the cell voltages and its
        noise is sqrt(kT / (n C)). A `bits`-bit conversion of that voltage has a step of v_swing / 2^bits.
        Require sqrt(kT / (n C)) <= step / 2.
    [Returns] farads
    """
    lsb = v_swing / 2 ** bits
    return K_BOLTZMANN * T_KELVIN / (n_rows * (lsb / 2) ** 2)


@dataclass(frozen=True)
class IMCEnergy:
    """
    Per-event energies of an analog in-memory macro (ASSUMED, 22/28-nm class; the scripts sweep them).

    [Fields]
        e_cell_fj : one device conducting (or one capacitor switching) for one full input pulse, fJ
        e_row_fj  : driving one row line (DAC / word-line driver) for one pulse, fJ (shared by all columns)
        e_col_fj  : precharging and sensing one column for one conversion, fJ (excluding the ADC)
        e_digital_fj : one digital shift-and-add of a converted partial sum (~24-bit add), fJ
        activity  : mean input amplitude per pulse (fraction of a full pulse); bit-serial bits and PWM lengths
                    of ReLU-like activations are mostly small
        fom_w_fj, fom_s_db : ADC figures of merit
        e_out_pj  : everything per OUTPUT outside the array (scaling, activation, buffering, on-chip network);
                    0 by default -- the scripts add it to compare with whole-chip numbers
        pwm_ref_bits : e_cell_fj of a PWM input is for a full pulse of this many bits; with a fixed time per input
                    LSB, a b-bit pulse lasts 2^(b - pwm_ref_bits) as long (and costs that fraction)
    [Hardware link] PCM: V^2 G t = (0.2 V)^2 x (0.3 x 25 uS) x 128 ns = 38 fJ at a full pulse (0.2 V is the read
        voltage HERMES uses; the average conductance and pulse length are ASSUMED). SRAM charge domain: C V^2 =
        1 fF x (0.8 V)^2 = 0.64 fJ.
    """
    name: str = "analog macro"
    e_cell_fj: float = 38.0
    e_row_fj: float = 30.0
    e_col_fj: float = 20.0
    e_digital_fj: float = em.op_energy_pj("int", "add", 32) * 0.75 * NODE_SCALE * 1e3
    activity: float = 0.25
    fom_w_fj: float = ADC_FOM_W_FJ
    fom_s_db: float = ADC_FOM_S_DB
    e_out_pj: float = 0.0
    pwm_ref_bits: int = 8


PCM_ENERGY = IMCEnergy(name="PCM-like", e_cell_fj=38.0)
SRAM_ENERGY = IMCEnergy(name="SRAM charge-domain", e_cell_fj=0.64)


def analog_energy(xbar, energy, M, K, signed_inputs=False, adc_bits=None):
    """
    Energy of one analog MVM (one input vector) on a K x M weight matrix, with a breakdown.

    [Idea] Count events: pulses x passes x slices x tiles conversions per output column; each conversion pays the
        column and the ADC and one digital shift-add; each pulse drives K rows; each pulse makes every device on the
        active rows conduct (2 devices per weight digit, scaled by the activity).
    [Args] xbar: Crossbar (precision, mode); energy: IMCEnergy; adc_bits: override (default xbar.adc_bits)
    [Returns] dict: per-component pJ per MAC ("cells", "rows", "columns", "ADC", "digital", "outputs"), "total",
        "conversions_per_mac", "tops_per_w"
    """
    bits = xbar.adc_bits if adc_bits is None else adc_bits
    mag_w = xbar.weight_bits - 1
    slices = math.ceil(mag_w / min(xbar.cell_bits, mag_w))
    in_mag = xbar.input_bits - 1 if signed_inputs else xbar.input_bits
    pulses = in_mag if xbar.input_mode == "bit-serial" else 1
    passes = 2 if signed_inputs else 1
    tiles = math.ceil(K / xbar.rows)
    conv = tiles * slices * passes * pulses * M
    macs = M * K
    pulse_len = 2.0 ** (in_mag - energy.pwm_ref_bits) if xbar.input_mode == "pwm" else 1.0
    e = {
        "cells": 2 * macs * slices * passes * pulses * energy.activity * pulse_len * energy.e_cell_fj * 1e-3,
        "rows": K * passes * pulses * energy.e_row_fj * 1e-3,
        "columns": conv * energy.e_col_fj * 1e-3,
        "ADC": conv * adc_energy_pj(bits, energy.fom_w_fj, energy.fom_s_db),
        "digital": conv * energy.e_digital_fj * 1e-3,
        "outputs": M * energy.e_out_pj,
    }
    per_mac = {k: v / macs for k, v in e.items()}
    per_mac["total"] = sum(per_mac.values())
    per_mac["conversions_per_mac"] = conv / macs
    per_mac["tops_per_w"] = 2 / per_mac["total"]          # 2 ops per MAC, pJ -> TOPS/W
    return per_mac


def full_adder_fj():
    """One full adder (fJ) at the assumed node: Horowitz's 8-bit add / 8 bits x NODE_SCALE (3.75 fJ x 0.4 = 1.5 fJ)."""
    return em.op_energy_pj("int", "add", 8) / 8 * NODE_SCALE * 1e3


def dcim_energy(weight_bits, input_bits, rows=256, signed_inputs=False, e_bitcell_fj=0.5):
    """
    Energy per MAC of digital in-memory computing (pJ), with a breakdown.

    [Idea] Per MAC: (weight bits x input bits) one-bit products; each costs a bit-cell read + a gate (e_bitcell_fj,
        ASSUMED) and ~2 full adders of the tree; per column and bit pair one shift-and-add of the tree's output,
        amortized over the rows.
    [Returns] dict: "bit cells + gates", "adder tree", "accumulate", "total" (pJ per MAC), "tops_per_w"
    """
    in_mag = input_bits - 1 if signed_inputs else input_bits
    products = (weight_bits - 1) * in_mag
    fa = adder_tree_full_adders(rows) / rows
    acc_bits = math.ceil(math.log2(rows)) + weight_bits + input_bits
    e = {"bit cells + gates": products * e_bitcell_fj * 1e-3,
         "adder tree": products * fa * full_adder_fj() * 1e-3,
         "accumulate": products * acc_bits * full_adder_fj() * 1e-3 / rows}
    e["total"] = sum(e.values())
    e["tops_per_w"] = 2 / e["total"]
    return e


def digital_energy(bits, weight_source="registers", sram_bank_bytes=32 * 1024, terms=256):
    """
    Energy per MAC of a conventional digital datapath at the same assumed node (pJ), with a breakdown.

    [Args] bits: integer precision of weights and inputs; weight_source: "registers" (weight-stationary, reused
        across a large batch: no weight traffic), "SRAM" (every weight read once per use from a bank of
        sram_bank_bytes: a GEMV without reuse), or "HBM" (every weight from off-chip DRAM, Lecture 14's 31 pJ/B);
        terms: length of the dot products (sets the accumulator width 2 bits + log2(terms))
    [Returns] dict: "multiply", "accumulate", "weight access", "total", "tops_per_w"
    [Edge cases] The DRAM energy is not scaled with NODE_SCALE: DRAM and I/O energies scale far more slowly.
    """
    acc_bits = 2 * bits + math.ceil(math.log2(terms))
    e = {"multiply": em.op_energy_pj("int", "mult", bits) * NODE_SCALE,
         "accumulate": em.op_energy_pj("int", "add", acc_bits) * NODE_SCALE}
    nbytes = bits / 8
    if weight_source == "registers":
        e["weight access"] = 0.0
    elif weight_source == "SRAM":
        e["weight access"] = em.sram_pj_per_byte(sram_bank_bytes) * NODE_SCALE * nbytes
    elif weight_source == "HBM":
        e["weight access"] = 31.2 * nbytes
    else:
        raise ValueError(weight_source)
    e["total"] = sum(e.values())
    e["tops_per_w"] = 2 / e["total"]
    return e


# =====================================================================================================================
# 5. A toy task and a small network
# =====================================================================================================================

def glyph_prototypes(rng, classes=10, size=16, strokes=3):
    """
    Ten random 'glyphs': each class is a few straight strokes on a size x size canvas (stroke endpoints).

    [Returns] array (classes, strokes, 4) of endpoints (r0, c0, r1, c1) inside a margin of 3 pixels
    """
    return rng.uniform(3, size - 4, size=(classes, strokes, 4))


def _draw(endpoints, size, width):
    """Render strokes with a soft profile exp(-d^2 / (2 width^2)) of the distance to each segment; max over strokes."""
    rr, cc = np.mgrid[0:size, 0:size].astype(np.float64)
    img = np.zeros((size, size))
    for r0, c0, r1, c1 in endpoints:
        dr, dc = r1 - r0, c1 - c0
        t = np.clip(((rr - r0) * dr + (cc - c0) * dc) / (dr * dr + dc * dc + 1e-9), 0, 1)
        d2 = (rr - r0 - t * dr) ** 2 + (cc - c0 - t * dc) ** 2
        img = np.maximum(img, np.exp(-d2 / (2 * width ** 2)))
    return img


def glyph_dataset(n, rng, protos, size=16, jitter=0.5, shift=1, noise=0.4):
    """
    n noisy images of the glyph classes: endpoints jittered, the glyph shifted, stroke width and contrast varied,
    Gaussian pixel noise added; flattened to (n, size^2), zero mean per pixel set later by the caller if wanted.

    [Returns] (X float (n, size^2), y int (n,))
    [Edge cases] Deterministic for a given rng state.
    """
    classes = protos.shape[0]
    y = rng.integers(0, classes, n)
    X = np.empty((n, size * size))
    for i in range(n):
        e = protos[y[i]] + rng.normal(0, jitter, protos.shape[1:])
        e[:, [0, 2]] += rng.integers(-shift, shift + 1)
        e[:, [1, 3]] += rng.integers(-shift, shift + 1)
        img = _draw(e, size, rng.uniform(0.6, 1.1)) * rng.uniform(0.7, 1.3)
        X[i] = (img + rng.normal(0, noise, img.shape)).ravel()
    return X, y


def mlp_forward(params, X, matmul=None):
    """
    Forward pass of a ReLU MLP; returns the logits.

    [Args] params: list of (W (out, in), b (out,)); matmul(i, H, W): optional replacement for H @ W.T of layer i
        (used to run a layer on the crossbar)
    """
    H = X
    for i, (W, b) in enumerate(params):
        Z = (H @ W.T if matmul is None else matmul(i, H, W)) + b
        H = np.maximum(Z, 0.0) if i < len(params) - 1 else Z
    return H


def train_mlp(X, y, sizes, rng, epochs=12, lr=0.05, batch=64, weight_noise=0.0):
    """
    Train a ReLU MLP with softmax cross-entropy, SGD with momentum 0.9.

    [Idea] weight_noise > 0 is HARDWARE-AWARE training (IBM's approach): every forward pass uses W + N(0, (eta x
        max|W_row|)^2), so the network learns weights whose function survives the programming error of a crossbar.
        The gradient is applied to the clean weights.
    [Args] sizes: e.g. [256, 256, 128, 10]; weight_noise: eta, relative to each row's max |W|
    [Returns] params list of (W, b)
    """
    params = [(rng.normal(0, math.sqrt(2.0 / a), (b_, a)), np.zeros(b_)) for a, b_ in zip(sizes[:-1], sizes[1:])]
    vel = [(np.zeros_like(W), np.zeros_like(b)) for W, b in params]
    n = X.shape[0]
    for _ in range(epochs):
        order = rng.permutation(n)
        for k in range(0, n, batch):
            idx = order[k:k + batch]
            hs, zs = [X[idx]], []
            noisy = []
            for i, (W, b) in enumerate(params):
                Wn = W
                if weight_noise > 0:
                    Wn = W + rng.normal(0, 1, W.shape) * weight_noise * np.max(np.abs(W), axis=1, keepdims=True)
                noisy.append(Wn)
                z = hs[-1] @ Wn.T + b
                zs.append(z)
                hs.append(np.maximum(z, 0) if i < len(params) - 1 else z)
            p = np.exp(hs[-1] - hs[-1].max(axis=1, keepdims=True))
            p /= p.sum(axis=1, keepdims=True)
            p[np.arange(len(idx)), y[idx]] -= 1.0
            grad = p / len(idx)
            for i in range(len(params) - 1, -1, -1):
                W, b = params[i]
                gW, gb = grad.T @ hs[i], grad.sum(axis=0)
                if i > 0:
                    grad = (grad @ noisy[i]) * (zs[i - 1] > 0)
                vW, vb = vel[i]
                vW = 0.9 * vW - lr * gW
                vb = 0.9 * vb - lr * gb
                vel[i] = (vW, vb)
                params[i] = (W + vW, b + vb)
    return params


def accuracy(logits, y):
    return float(np.mean(np.argmax(logits, axis=1) == y))


def activation_ranges(params, X, percentile=99.99):
    """Input clipping value of every layer (the percentile of |input| over calibration data), for static scaling."""
    out, H = [], X
    for i, (W, b) in enumerate(params):
        out.append(float(np.percentile(np.abs(H), percentile)))
        Z = H @ W.T + b
        H = np.maximum(Z, 0) if i < len(params) - 1 else Z
    return out


def program_network(params, xbar, rng, X_cal=None, ranges=None, percentile=99.9):
    """Program every layer into its own CrossbarArray; calibrate each ADC range on X_cal if given."""
    arrays = [CrossbarArray(W, xbar, rng) for W, _ in params]
    if X_cal is not None:
        H = X_cal
        for i, (arr, (W, b)) in enumerate(zip(arrays, params)):
            arr.calibrate(H, x_max=ranges[i], percentile=percentile)
            Z = H @ W.T + b
            H = np.maximum(Z, 0) if i < len(params) - 1 else Z
    return arrays


def analog_mlp_forward(params, arrays, X, ranges, t_s=None, compensate=False, rng=None, digital_layers=(),
                       digital_bits=8):
    """
    Run the MLP with each layer's matrix product on its crossbar (biases and ReLU digital).

    [Args] arrays: from program_network; ranges: input clipping per layer (activation_ranges); digital_layers:
        indices of layers computed digitally at digital_bits instead (a hybrid design keeps sensitive layers digital)
    [Returns] logits
    """
    rng = np.random.default_rng(7) if rng is None else rng

    def mm(i, H, W):
        if i in digital_layers:
            return digital_reference(W, H, digital_bits, digital_bits, x_max=ranges[i])
        return arrays[i].mvm(H, x_max=ranges[i], t_s=t_s, compensate=compensate, rng=rng)["y"]

    return mlp_forward(params, X, matmul=mm)


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

def _self_test():
    rng = np.random.default_rng(0)
    W = rng.normal(0, 1, (48, 600))
    X = np.maximum(rng.normal(0, 1, (20, 600)), 0)
    Xs = rng.normal(0, 1, (20, 600))
    exact_u = digital_reference(W, X, 8, 8)
    exact_s = digital_reference(W, Xs, 8, 8)
    for cell_bits, mode in ((1, "bit-serial"), (2, "bit-serial"), (7, "bit-serial"), (7, "pwm")):
        xb = Crossbar(rows=256, cell_bits=cell_bits, input_mode=mode, adc_bits=None)
        arr = CrossbarArray(W, xb)
        assert np.allclose(arr.mvm(X)["y"], exact_u), (cell_bits, mode)
        assert np.allclose(arr.mvm(Xs)["y"], exact_s), (cell_bits, mode)
    # a lossless ADC for bit-serial inputs reproduces the integer product exactly
    for cell_bits in (1, 2):
        L = 2 ** cell_bits - 1
        xb = Crossbar(rows=256, cell_bits=cell_bits, input_mode="bit-serial", adc_bits=lossless_adc_bits(256, L))
        assert np.allclose(CrossbarArray(W, xb).mvm(Xs)["y"], exact_s)
    xb = Crossbar(rows=256, cell_bits=7, input_mode="pwm", adc_bits=lossless_adc_bits(256, 127, 255))
    assert np.allclose(CrossbarArray(W, xb).mvm(X)["y"], exact_u)
    assert np.allclose(CrossbarArray(W, xb).mvm(Xs)["y"], exact_s)
    assert lossless_adc_bits(256, 1) == 10
    assert adder_tree_full_adders(256) == 502
    d = dcim_mvm(W, Xs)
    q, ws = quantize_weights(W, 8)
    xq, xs, _ = quantize_inputs(Xs, 8)
    assert np.array_equal(d["y_int"], xq @ q.T)
    # noise lowers the SNR, compensation restores most of the drift loss
    arr = CrossbarArray(W, replace(PCM_LIKE, adc_bits=None, sigma_read=0, sigma_adc=0, sigma_static=0,
                                   drift_nu_sigma=0.0))
    y_drift = arr.mvm(X, t_s=86400)["y"]
    y_comp = arr.mvm(X, t_s=86400, compensate=True)["y"]
    assert np.allclose(y_comp, exact_u)                       # uniform drift is removed exactly by one factor
    assert sqnr_db(exact_u, y_drift) < 20
    assert 0.4 < adc_energy_pj(8) < 0.6 and adc_energy_pj(14) > 4 * adc_energy_pj(12)
    e = analog_energy(SRAM_LIKE, SRAM_ENERGY, 256, 256)
    assert abs(e["conversions_per_mac"] - 7 * 8 / 256) < 1e-12
    print("imc.py self-test passed")


if __name__ == "__main__":
    _self_test()
