Skip to content

Neuromorphic Silicon and In-Memory Computing

Running a spiking neural network on a conventional graphics card is like staging an intimate chamber quartet inside a roaring football stadium, burning enormous memory traffic on weights that barely need to move. In this section we open the lid on real neuromorphic silicon, tracing how asynchronous digital neurocores, subthreshold analogue transistors, and resistive memristor crossbars collapse memory and compute into the same physical chip.

Breaking the Memory Wall in Silicon

  • Imagine a master baker whose flour, sugar, and spice jars are locked inside a warehouse three streets away. Every time the recipe calls for a single teaspoon of cinnamon, the baker walks down the road, unlocks the warehouse, fetches the jar, measures one spoonful, and walks all the way back. That exhausting commute is the von Neumann memory wall we met in chapter 16 and chapter 19. On a modern GPU, hauling a 16-bit weight across the memory bus from off-chip HBM DRAM can burn fifty to two hundred times more energy than actually multiplying that weight inside an arithmetic unit!

  • Simulating a spiking neural network on standard GPU silicon therefore leaves most of the biological efficiency sitting on the table. Graphics processors are marvels of dense, synchronous linear algebra marching in lockstep to a gigahertz global clock. Biological brains work the opposite way, keeping synaptic weights physically wrapped around every neuron's dendritic tree and consuming power only when sparse spikes actually arrive.

  • To move closer to the human brain's \(20\,\text{W}\) envelope, hardware architects have built three distinct families of neuromorphic silicon. Each family attacks the memory wall from a slightly different physical angle, trading digital precision and programmability against raw analogue energy efficiency.

Comparison of digital neurocore meshes, subthreshold mixed-signal analogue chips, and resistive memristor crossbars against the von Neumann memory wall

Digital Neuromorphic Silicon

  • Picture a quiet guild street lined with tiny craft workshops connected by bicycle couriers. Every artisan keeps their own tools and ledger right on their workbench, sits peacefully with the lights dimmed while nothing is happening, and starts working only when a courier drops a letter through the slot. Digital neuromorphic chips build that exact organisation out of standard CMOS logic, keeping weights inside tiny local SRAM banks bolted directly beside each neuron circuit.

Asynchronous Neurocores and Intel Loihi 2

  • Intel's Loihi architecture, and especially its second-generation successor Loihi 2 (fabricated on Intel's advanced CMOS process with \(128\) neuromorphic cores, up to one million neurons, and \(120\) million synapses per chip), showcases what fully asynchronous digital silicon can achieve. Rather than marching to a power-hungry chip-wide clock, Loihi 2 cores communicate over an asynchronous Network-on-Chip (NoC) using Address-Event Representation (AER) packets. When a neuron stays silent, its local circuits barely switch at all.

  • Loihi 2 also introduced three practical breakthroughs that bridged textbook spiking neurons and real engineering workloads.

    • Graded spikes. Early binary neuromorphic chips restricted every spike to a single bit, forcing neurons to fire rapid bursts just to convey a moderately precise number. Loihi 2 allows graded spikes carrying integer payloads (up to \(32\) bits) inside each sparse event packet, packing richer numerical accuracy into far fewer transmissions.
    • Programmable neuron microcode. Instead of hardwiring a single rigid leaky integrate-and-fire equation into fixed gates, each Loihi 2 neurocore runs tiny programmable microcode instructions. Engineers can implement resonate-and-fire oscillators, sigma-delta neurons, or custom state-space updates directly in silicon.
    • On-chip local plasticity. Each core embeds dedicated learning engines right beside its synaptic SRAM, enabling local three-factor learning rules (combining pre-synaptic activity, post-synaptic activity, and a global modulatory reward or error signal) without ever exporting weights to an external host computer. At system scale, Intel's Hala Point (unveiled in 2024 and deployed at Sandia National Laboratories) integrates \(1{,}152\) Loihi 2 processors (\(140{,}544\) neuromorphic cores) into a compact 6U data-centre chassis drawing up to \(2{,}600\,\text{W}\), supporting \(1.15\) billion neurons and \(128\) billion synapses!

Zero Off-Chip DRAM With IBM TrueNorth and NorthPole

  • IBM pioneered large-scale digital neuromorphic chips in 2014 with TrueNorth, a \(5.4\)-billion-transistor chip housing \(4{,}096\) neurosynaptic cores (\(1\) million spiking neurons and \(256\) million binary synapses) that drew roughly \(70\,\text{mW}\) during real-time inference. TrueNorth proved that eliminating external DRAM and routing sparse spikes asynchronously could cut energy per inference by orders of magnitude compared with contemporary CPUs.

  • Nearly a decade later, IBM's NorthPole architecture generalised that co-located memory insight to high-speed deep neural network inference. NorthPole packs \(256\) compute cores woven tightly with high-density on-chip SRAM and operates with zero off-chip DRAM during inference. By blending spatial weight locality with aggressive \(2\)-bit, \(4\)-bit, and \(8\)-bit quantisation (connecting straight back to chapter 20), NorthPole delivers dramatic gains in frames per joule over similarly sized GPUs, demonstrating that neuromorphic memory organisation pays huge dividends even outside strictly biological spiking models.

Many-Core Packet-Switched Simulation With SpiNNaker

  • What if you are a computational neuroscientist who wants to simulate exotic cortical microcircuits with complex multi-compartment dendritic equations that change every Tuesday? Rigid custom neuron gates would slow you down. The University of Manchester's SpiNNaker (Spiking Neural Network Architecture) solves this by placing \(18\) low-power ARM cores on each chip (scaling up to \(152\) ARM cores with dedicated multiply-accumulate accelerators and dynamic voltage-frequency scaling in SpiNNaker2) linked by a bespoke multicast packet-switched router.

  • Normal internet routers are optimised for bulky kilobyte packets. SpiNNaker's router is tuned specifically for millions of tiny \(40\)-bit spike packets fanning out simultaneously to thousands of destination cores across a million-core machine. Because every neuron runs as lightweight C code on an ARM core, SpiNNaker trades a little raw energy efficiency for extraordinary scientific flexibility, simulating biological brain models in real time.

Mixed-Signal and Analogue Neuromorphic Silicon

  • Suppose you want to know how ripples spread when two pebbles splash into a pond. A digital computer dices the pond into a million virtual squares and crunches floating-point differential equations step by step. An analogue neuromorphic engineer simply builds a tiny physical puddle and lets water obey the laws of physics directly!

  • Back in the late 1980s, physicist Carver Mead realised something uncanny about ordinary MOSFET transistors. Digital engineers slam transistors hard between completely OFF and completely ON to represent binary \(0\) and \(1\). Yet when you bias a transistor gently in the subthreshold (weak inversion) regime, where its gate voltage \(V_g\) sits slightly below the digital switching threshold, charge carriers cross the channel by thermal diffusion rather than drift. That nanoampere drain current obeys an exponential Boltzmann law that mirrors the exact physics of biological sodium and potassium ion channels!

\[I_{\text{ds}} = I_0 \exp\!\left(\frac{\kappa V_g - V_s}{U_T}\right)\]
  • Here \(I_0\) is the tiny characteristic leakage current (often picoamperes to nanoamperes), \(\kappa \in (0.6, 0.8)\) captures how strongly the gate voltage couples to the silicon channel, \(V_g\) and \(V_s\) are the gate and source voltages, and \(U_T = k_B T / q \approx 25.8\,\text{mV}\) at room temperature is the thermal voltage. By wiring a handful of subthreshold transistors to a microscopic on-chip capacitor representing membrane capacitance \(C_m\), silicon physically integrates synaptic currents, leaks charge continuously in real time, and fires sharp action potentials while sipping microwatts or even nanowatts!

  • Sending delicate analogue voltages across centimetres of silicon wire would invite electrical noise and crosstalk. Practical chips such as DYNAP-SE (from ETH Zurich and University of Zurich) and Stanford's Neurogrid therefore embrace a mixed-signal design. Every neuron integrates and leaks continuously in ultra-low-power analogue hardware, then converts each action potential into a crisp, noise-immune digital AER spike packet for long-distance routing across the chip.

  • Even more intriguingly, analogue physics does not have to run at biological wall-clock speed. The BrainScaleS wafer-scale system developed at Heidelberg University fabricates physical analogue neuron circuits using tiny silicon capacitors whose natural time constants run \(1{,}000\times\) to \(10{,}000\times\) faster than living cortex. An entire day of biological sleep-wake learning and synaptic consolidation plays out in under ten seconds of physical time, overseen by embedded digital plasticity processors sitting right beside the analogue arrays.

Resistive In-Memory Computing and Memristor Crossbars

  • Digital SRAM is wonderfully fast and reliable, yet storing a single bit demands six transistors, leaks standby current continuously, and wipes itself clean the instant you unplug the battery. What if a single nanoscale two-terminal device could remember an analogue synaptic weight permanently without power and perform multiplication right inside the memory cell itself?

  • Picture a vintage theatre lighting board built from horizontal copper bars crossing over vertical copper bars, with a tiny rotary dimmer soldered at every intersection. Push different voltages onto all the horizontal bars at once, and electric currents immediately pour through every dimmer and add themselves together along every vertical bar in one silent flash, obeying nature's own arithmetic without fetching a single byte! That is the core beauty of resistive in-memory computing (IMC) using a crossbar array.

Memristor crossbar array performing O(1) analogue matrix-vector multiplication via Ohm's law and Kirchhoff's current law with differential conductance pairs

Non-Volatile Synaptic Devices

  • Several competing materials-science technologies can serve as the programmable conductance \(G_{ij} = 1 / R_{ij}\) sitting at each crossbar intersection.

    • Memristors and Resistive RAM (RRAM). A thin insulating metal-oxide film (often hafnium oxide or tantalum oxide, just a few nanometres thick) sits sandwiched between two metallic electrodes. Short voltage pulses nudge oxygen vacancies to grow or retract a microscopic conductive filament across the oxide, tuning the cell's conductance smoothly across multiple levels.
    • Phase-Change Memory (PCM). A tiny droplet of chalcogenide glass (such as germanium-antimony-telluride) flips between a neatly ordered, low-resistance crystalline phase and a disordered, high-resistance amorphous glass phase depending on how sharply a brief electrical pulse heats and quenches it. IBM's prototype analogue AI chips have already demonstrated millions of PCM synapses running speech and vision models at remarkable efficiency.
    • MRAM and FeFETs. Spin-transfer torque magnetic RAM (STT-MRAM) stores weights in nanoscale magnetic tunnel junctions with extraordinarily high write endurance, while ferroelectric field-effect transistors (FeFETs) shift a transistor's threshold voltage via electric dipole polarisation with ultralow write energy.

Computing Matrix-Vector Products in \(O(1)\) Physical Time

  • Place an \(M \times N\) grid of these non-volatile devices with programmed conductances \(G_{ij}\) at the intersections of \(M\) horizontal wordlines and \(N\) vertical bitlines. Present an input activation vector \(\mathbf{V} \in \mathbb{R}^M\) as analogue voltages (or fixed-amplitude pulse widths) along the horizontal rows simultaneously.

  • By Ohm's law, the device at row \(i\) and column \(j\) conducts an electric current \(I_{ij} = G_{ij} V_i\). Because every device in column \(j\) empties into the exact same vertical wire, Kirchhoff's current law automatically sums every row's contribution at the bottom of the column in parallel!

\[I_j = \sum_{i=1}^{M} G_{ij} V_i, \qquad \mathbf{I} = G^\top \mathbf{V}\]
  • Pause and appreciate what just happened. On a conventional processor, multiplying an \(M \times N\) matrix by an \(M\)-element vector requires \(O(MN)\) multiply-accumulate instructions and drags \(MN\) weights out of memory. Inside a resistive crossbar, the weights never move a single atomic diameter, and the entire matrix-vector multiply finishes in \(O(1)\) physical pulse time! Because real physical conductances are strictly non-negative (\(G_{ij} \ge 0\)), engineers encode signed neural weights \(W_{ij} \in \mathbb{R}\) cleanly using a differential pair of cells per synapse (\(W_{ij} \propto G_{ij}^{+} - G_{ij}^{-}\)), subtracting the negative column's current from the positive column's current at the periphery.

Honest Hardware Realities and Engineering Challenges

  • On paper, analogue transistors and memristor crossbars sound almost too magical to believe. Real silicon engineering is never free, and understanding the five tough physical imperfections holding analogue in-memory computing back today is essential for evaluating real hardware claims honestly.

    • Device-to-device and cycle-to-cycle variability. Growing an atomic filament just five atoms wide is inherently stochastic. Sending the exact same programming pulse to two neighbouring RRAM cells produces slightly different conductances \(G_{ij} + \epsilon_{ij}\), and rewriting the same cell twice rarely lands on the identical value without slow iterative verify-and-pulse loops.
    • Conductance drift and finite write endurance. Amorphous phase-change glass relaxes structurally after programming, causing its conductance to sag slowly over hours and weeks following a power law \(G(t) = G(t_0)(t / t_0)^{-\nu}\) where the drift exponent \(\nu\) itself varies from cell to cell. Moreover, repeatedly rewriting RRAM or PCM degrades cells after roughly \(10^6\) to \(10^9\) cycles (compared with SRAM's practically unlimited endurance), making resistive crossbars much better suited for write-once, read-many inference than relentless dense backpropagation training.
    • Wire IR drop and thermal noise. Real microscopic metal crossbar lines carry finite electrical resistance. As current flows down a wide row or column, voltage sags subtly toward the far end (IR drop), distorting the matrix multiplication unless tile dimensions stay compact (typically \(128 \times 128\) or \(256 \times 256\)). Johnson-Nyquist thermal noise and shot noise further cap each analogue column's effective signal-to-noise ratio around \(4\) to \(6\) true bits of precision.
    • The ADC and DAC peripheral tax. This is the single biggest surprise for newcomers to in-memory computing. While the crossbar cells themselves sip femtojoules per multiply-accumulate, converting digital activations into analogue row voltages (DACs) and digitising summed column currents back into numbers (ADCs) routinely consumes \(60\%\) to \(80\%\) of total chip area and power! Clever architectures trim that tax by replacing multi-bit DACs with single-bit pulse-width modulation, sharing ADCs across columns, or passing sparse spikes directly between analogue tiles.
    • Mapping large networks and hardware-aware training. Even digital neuromorphic chips like Loihi 2 and NorthPole carry strict on-chip SRAM budgets per core. Mapping a deep model cleanly across dozens of cores without saturating inter-core spike routing requires specialised compilers. Meanwhile, deploying neural networks onto noisy resistive crossbars depends critically on hardware-aware training (injecting realistic conductance variability, quantisation, IR drop, and drift noise directly into the forward pass during training so the learned weights naturally land in flat, noise-tolerant minima).

Take-Home

  • Conventional GPUs spend the vast majority of their energy shuttling weights across the von Neumann memory wall, which motivated neuromorphic architects to co-locate synaptic memory directly beside or inside neural compute units.
  • Digital neuromorphic chips eliminate off-chip DRAM traffic by tiling local SRAM neurocores over asynchronous spike-routing meshes, spanning Intel Loihi 2 (graded spikes and programmable microcode), IBM TrueNorth and NorthPole (ultra-efficient local SRAM inference), and SpiNNaker (flexible many-core ARM brain simulation).
  • Mixed-signal analogue chips exploit subthreshold MOSFET physics where drain current scales exponentially with gate voltage like biological ion channels, letting platforms such as BrainScaleS emulate continuous neural dynamics thousands of times faster than real time.
  • Resistive in-memory crossbars built from RRAM, phase-change memory, or MRAM compute full matrix-vector multiplications in \(O(1)\) physical time via Ohm's law (\(I_{ij} = G_{ij} V_i\)) and Kirchhoff's current law (\(I_j = \sum_i G_{ij} V_i\)) using differential pairs for signed weights.
  • Real analogue and resistive silicon faces tough engineering constraints including filament variability, conductance drift, wire IR drop, and peripheral ADC/DAC energy overhead, making compact tile sizes and hardware-aware training essential for accurate deployment.

Coding Tasks (use CoLab or notebook)

  1. Simulate a differential memristor crossbar performing signed matrix-vector multiplication with physical imperfections (device-to-device programming variability, wire IR-drop attenuation, and finite-bit column ADC quantisation). Sweep ADC resolution from \(2\) to \(8\) bits under low and high conductance noise and measure output signal-to-noise ratio (SNR).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(42)
    M, N = 64, 32
    key, kW, kx, k_pos, k_neg = jax.random.split(key, 5)
    
    # Signed target weights and normalised positive input voltages in [0, 1]
    W = jax.random.normal(kW, (M, N)) * 0.45
    V_in = jax.random.uniform(kx, (M,), minval=0.0, maxval=1.0)
    I_ideal = jnp.dot(V_in, W)
    
    # Map signed weights onto differential positive conductances (microsiemens)
    G_scale = 50.0
    G_pos_nom = jnp.maximum(W, 0.0) * G_scale
    G_neg_nom = jnp.maximum(-W, 0.0) * G_scale
    
    # Wire IR-drop voltage attenuation along the row index
    ir_attenuation = jnp.exp(-0.004 * jnp.arange(M))
    V_eff = V_in * ir_attenuation
    
    def simulate_crossbar(sigma, adc_bits, eps_p, eps_n):
        G_pos = jnp.maximum(G_pos_nom * (1.0 + sigma * eps_p), 0.0)
        G_neg = jnp.maximum(G_neg_nom * (1.0 + sigma * eps_n), 0.0)
        I_pos = jnp.dot(V_eff, G_pos)
        I_neg = jnp.dot(V_eff, G_neg)
        I_diff = (I_pos - I_neg) / G_scale
    
        # Uniform symmetric ADC quantisation over full-scale range
        v_max = jnp.max(jnp.abs(I_ideal)) * 1.25
        levels = (2.0 ** (adc_bits - 1)) - 1.0
        I_q = jnp.round(jnp.clip(I_diff / v_max, -1.0, 1.0) * levels) / levels * v_max
        snr = 10.0 * jnp.log10(jnp.sum(I_ideal ** 2) / jnp.maximum(jnp.sum((I_ideal - I_q) ** 2), 1e-12))
        return I_q, float(snr)
    
    eps_p = jax.random.normal(k_pos, (M, N))
    eps_n = jax.random.normal(k_neg, (M, N))
    bits_list = [2, 3, 4, 5, 6, 8]
    snr_low = [simulate_crossbar(0.03, b, eps_p, eps_n)[1] for b in bits_list]
    snr_high = [simulate_crossbar(0.12, b, eps_p, eps_n)[1] for b in bits_list]
    I_4bit, snr_4b = simulate_crossbar(0.08, 4, eps_p, eps_n)
    
    print(f"4-bit crossbar with 8% conductance noise -> SNR: {snr_4b:.2f} dB")
    for b, s1, s2 in zip(bits_list, snr_low, snr_high):
        print(f"ADC {b} bits -> Low noise SNR: {s1:5.2f} dB | High noise SNR: {s2:5.2f} dB")
    
    fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
    axes[0].plot(bits_list, snr_low, marker="o", color="#27ae60", lw=2, label="3% Device Noise")
    axes[0].plot(bits_list, snr_high, marker="s", color="#e74c3c", lw=2, label="12% Device Noise")
    axes[0].set_title("Crossbar Output SNR vs ADC Bit-Width"); axes[0].set_xlabel("ADC Resolution (bits)")
    axes[0].set_ylabel("Output SNR (dB)"); axes[0].grid(alpha=0.3); axes[0].legend()
    
    axes[1].scatter(I_ideal, I_4bit, color="#3498db", alpha=0.8, label="4-bit Noisy Crossbar")
    lim = float(jnp.max(jnp.abs(I_ideal))) * 1.15
    axes[1].plot([-lim, lim], [-lim, lim], color="#333", ls="--", lw=1.2, label="Ideal MVM")
    axes[1].set_title("Ideal vs Noisy Differential Crossbar Output"); axes[1].set_xlabel("Ideal Output")
    axes[1].set_ylabel("Crossbar Output"); axes[1].legend()
    plt.tight_layout(); plt.show()
    

  2. Compare standard clean training against hardware-aware training on a two-layer classifier deployed onto a phase-change memory (PCM) crossbar suffering from both write variability (\(\sigma = 0.08\)) and heterogeneous power-law conductance drift \(G(t) = G(t_0)(t / t_0)^{-\nu_{ij}}\) across six decades of time (\(1\,\text{s}\) to \(10^6\,\text{s}\)).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(7)
    n_per_class = 80
    key, k0, k1, k2, k3 = jax.random.split(key, 5)
    # Two concentric rings classification dataset
    theta0 = jax.random.uniform(k0, (n_per_class,), minval=0.0, maxval=2.0 * jnp.pi)
    r0 = 0.55 + 0.14 * jax.random.normal(k1, (n_per_class,))
    theta1 = jax.random.uniform(k2, (n_per_class,), minval=0.0, maxval=2.0 * jnp.pi)
    r1 = 1.35 + 0.16 * jax.random.normal(k3, (n_per_class,))
    
    X0 = jnp.stack([r0 * jnp.cos(theta0), r0 * jnp.sin(theta0)], axis=1)
    X1 = jnp.stack([r1 * jnp.cos(theta1), r1 * jnp.sin(theta1)], axis=1)
    X = jnp.concatenate([X0, X1], axis=0)
    y = jnp.concatenate([jnp.zeros(n_per_class, dtype=jnp.int32), jnp.ones(n_per_class, dtype=jnp.int32)])
    
    def init_params(k):
        k1, k2 = jax.random.split(k)
        return (jax.random.normal(k1, (2, 24)) * 0.6, jnp.zeros(24),
                jax.random.normal(k2, (24, 2)) * 0.4, jnp.zeros(2))
    
    def logits_fn(params, X_in, k_noise=None, noise_std=0.0):
        W1, b1, W2, b2 = params
        if noise_std > 0.0 and k_noise is not None:
            kn1, kn2 = jax.random.split(k_noise)
            W1 = W1 * (1.0 + noise_std * jax.random.normal(kn1, W1.shape))
            W2 = W2 * (1.0 + noise_std * jax.random.normal(kn2, W2.shape))
        h = jax.nn.tanh(jnp.dot(X_in, W1) + b1)
        return jnp.dot(h, W2) + b2
    
    def loss_fn(W1, b1, W2, b2, X_in, y_in, k_noise, noise_std):
        logits = logits_fn((W1, b1, W2, b2), X_in, k_noise, noise_std)
        log_probs = jax.nn.log_softmax(logits, axis=1)
        y_oh = jnp.stack([1.0 - y_in, y_in], axis=1)
        return -jnp.mean(jnp.sum(y_oh * log_probs, axis=1)) + 1e-3 * (jnp.sum(W1 ** 2) + jnp.sum(W2 ** 2))
    
    grad_fn = jax.grad(loss_fn, argnums=(0, 1, 2, 3))
    
    def train_model(seed, noise_std, steps=350, lr=0.18):
        k = jax.random.PRNGKey(seed)
        k, ki = jax.random.split(k)
        W1, b1, W2, b2 = init_params(ki)
        for _ in range(steps):
            k, kn = jax.random.split(k)
            gW1, gb1, gW2, gb2 = grad_fn(W1, b1, W2, b2, X, y, kn, noise_std)
            W1, b1, W2, b2 = W1 - lr * gW1, b1 - lr * gb1, W2 - lr * gW2, b2 - lr * gb2
        return (W1, b1, W2, b2)
    
    params_clean = train_model(101, noise_std=0.0)
    params_hat = train_model(101, noise_std=0.18)
    
    # Evaluate under write variability + cell-specific PCM power-law conductance drift
    key, kv1, kv2, ke1, ke2 = jax.random.split(key, 5)
    nu1 = jax.random.uniform(kv1, params_clean[0].shape, minval=0.02, maxval=0.11)
    nu2 = jax.random.uniform(kv2, params_clean[2].shape, minval=0.02, maxval=0.11)
    var1 = 1.0 + 0.08 * jax.random.normal(ke1, params_clean[0].shape)
    var2 = 1.0 + 0.08 * jax.random.normal(ke2, params_clean[2].shape)
    
    times = jnp.array([1.0, 10.0, 1e2, 1e3, 1e4, 1e5, 1e6])
    def eval_drift(params):
        W1, b1, W2, b2 = params
        accs = []
        for t in times:
            d1 = (t ** (-nu1)) * var1
            d2 = (t ** (-nu2)) * var2
            logits = logits_fn((W1 * d1, b1, W2 * d2, b2), X)
            accs.append(float(jnp.mean(jnp.argmax(logits, axis=1) == y)) * 100.0)
        return accs
    
    acc_clean = eval_drift(params_clean)
    acc_hat = eval_drift(params_hat)
    print(f"Accuracy at t=1 s -> Clean: {acc_clean[0]:.1f}% | Hardware-Aware: {acc_hat[0]:.1f}%")
    print(f"Accuracy at t=1e6 s -> Clean: {acc_clean[-1]:.1f}% | Hardware-Aware: {acc_hat[-1]:.1f}%")
    
    plt.figure(figsize=(7.2, 4.0))
    plt.semilogx(times, acc_clean, marker="o", color="#e74c3c", lw=2.2, label="Standard Clean Training")
    plt.semilogx(times, acc_hat, marker="s", color="#27ae60", lw=2.2, label="Hardware-Aware Training (Noise Injected)")
    plt.title("Classifier Retention Under PCM Conductance Drift and Variability")
    plt.xlabel("Elapsed Time Since Programming (seconds)"); plt.ylabel("Accuracy (%)")
    plt.ylim(45, 103); plt.grid(alpha=0.3); plt.legend(); plt.tight_layout(); plt.show()
    

  3. Build an architecture energy model comparing a conventional off-chip DRAM GPU, an event-driven digital neuromorphic SRAM core, and a resistive memristor crossbar (including ADC/DAC periphery) for a \(1024 \times 1024\) synaptic layer across activation sparsity levels from \(1\%\) to \(100\%\).

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    N = 1024
    active_frac = 10.0 ** jnp.linspace(-2.0, 0.0, 40)
    n_active = active_frac * N
    
    # Energy coefficients in picojoules (pJ) per operation / access
    E_dram_weight = 40.0     # Off-chip HBM fetch for 16-bit weight
    E_gpu_mac = 0.5          # Digital FP16 MAC on GPU
    E_sram_weight = 1.2      # Local on-chip SRAM weight read
    E_neuro_add = 0.3        # Event-driven synaptic accumulate
    E_aer_route = 15.0       # On-chip AER spike packet routing
    E_xbar_mac = 0.05        # Resistive crossbar analogue MAC
    E_dac_row = 1.2          # Peripheral DAC energy per active row
    E_adc_col = 4.5          # Peripheral ADC conversion energy per output column
    
    # Total energy per layer pass in microjoules (1 uJ = 1e6 pJ)
    gpu_dram = jnp.full_like(active_frac, N * N * E_dram_weight) / 1e6
    gpu_comp = jnp.full_like(active_frac, N * N * E_gpu_mac) / 1e6
    gpu_total = gpu_dram + gpu_comp
    
    neuro_sram = (n_active * N * E_sram_weight) / 1e6
    neuro_comp = (n_active * N * E_neuro_add + n_active * E_aer_route) / 1e6
    neuro_total = neuro_sram + neuro_comp
    
    imc_core = (n_active * N * E_xbar_mac) / 1e6
    imc_periph = (n_active * E_dac_row + N * E_adc_col * 8.0) / 1e6  # 8 bit-serial cycles
    imc_total = imc_core + imc_periph
    
    idx_5pct = int(jnp.argmin(jnp.abs(active_frac - 0.05)))
    print(f"At 5% spike activity -> GPU: {float(gpu_total[idx_5pct]):.3f} uJ | "
          f"Digital Neurocore: {float(neuro_total[idx_5pct]):.3f} uJ | "
          f"Memristor IMC: {float(imc_total[idx_5pct]):.3f} uJ")
    
    fig, axes = plt.subplots(1, 2, figsize=(11.2, 4.0))
    axes[0].loglog(active_frac * 100.0, gpu_total, color="#e74c3c", lw=2.3, label="Von Neumann GPU (DRAM)")
    axes[0].loglog(active_frac * 100.0, neuro_total, color="#3498db", lw=2.3, label="Digital Neurocore (Local SRAM)")
    axes[0].loglog(active_frac * 100.0, imc_total, color="#27ae60", lw=2.3, label="Memristor Crossbar (IMC + ADC)")
    axes[0].set_title("Layer Energy vs Activation Density (1024x1024)"); axes[0].set_xlabel("Active Input Fraction (%)")
    axes[0].set_ylabel("Energy per Pass (uJ)"); axes[0].grid(alpha=0.3); axes[0].legend()
    
    # Share of dominant bottleneck at 5% activity
    labels = ["GPU\n(DRAM vs MAC)", "Neurocore\n(SRAM vs Add)", "Memristor IMC\n(ADC/DAC vs Core)"]
    dominant = [float(gpu_dram[idx_5pct] / gpu_total[idx_5pct]) * 100.0,
                float(neuro_sram[idx_5pct] / neuro_total[idx_5pct]) * 100.0,
                float(imc_periph[idx_5pct] / imc_total[idx_5pct]) * 100.0]
    compute = [100.0 - d for d in dominant]
    axes[1].bar(labels, dominant, color="#f39c12", width=0.52, label="Memory / Periphery Overhead")
    axes[1].bar(labels, compute, bottom=dominant, color="#9b59b6", width=0.52, label="Core Arithmetic")
    axes[1].set_title("Energy Breakdown Share at 5% Sparsity"); axes[1].set_ylabel("Share of Total Energy (%)")
    axes[1].set_ylim(0, 110); axes[1].legend()
    plt.tight_layout(); plt.show()