Memory and Learning¶
Human memory is not a passive hard drive that records life verbatim; it is an active, multi-system architecture optimised to guide future decisions under tight capacity limits. This file explores the modal model, Baddeley's working memory and its parallel to LLM context windows, long-term memory taxonomies, forgetting and retrieval practice, Complementary Learning Systems and catastrophic forgetting, and how Rescorla-Wagner associative learning bridges directly to Temporal Difference reinforcement learning.
Why Memory Is Not a Video Camera¶
-
Picture trying to draw a common banknote or coin from memory, something you have handled thousands of times. Almost everyone gets the details wildly wrong. Yet if someone hands you a counterfeit note with a slightly odd texture or colour, you notice instantly.
-
That paradox reveals what memory is really for. Rather than archival video playback, memory is compressed, reconstructive prediction. Your brain keeps whatever statistical regularities and key episodes help you act wisely tomorrow, and throws away redundant pixels.
-
Because remembering what happened five seconds ago, how to ride a bicycle, and what happened on your tenth birthday impose contradictory engineering demands, evolution did not build a single monolithic memory box. It built a coordinated hierarchy of specialised stores.
The Modal Model of Sensory, Short-Term, and Long-Term Stores¶
-
In 1968, Richard Atkinson and Richard Shiffrin proposed the Multi-Store (Modal) Model, dividing memory into three stages distinguished by capacity and duration.
- Sensory memory acts as a fleeting, high-bandwidth buffer that holds raw sensory input just long enough for attention to sample it.
- Iconic memory (visual) lasts roughly 0.25 to 0.5 seconds. George Sperling (1960) flashed a \(3 \times 4\) grid of letters for 50 ms, and participants could only report about 4 letters overall unless a tone immediately cued a single row, in which case they recalled almost the entire row, proving all twelve letters briefly existed in iconic memory before decaying.
- Echoic memory (auditory) lasts roughly 2 to 4 seconds, which is why you can say "Sorry, what?" and then suddenly hear your friend's exact sentence replay inside your head before they even repeat it.
- Short-Term Memory (STM) holds attended information for roughly 15 to 30 seconds unless kept alive by active rehearsal (silently repeating a phone number).
- Long-Term Memory (LTM) offers virtually unlimited capacity, lasting from minutes to a lifetime.
- Sensory memory acts as a fleeting, high-bandwidth buffer that holds raw sensory input just long enough for attention to sample it.
-
The modal model neatly explains the serial position curve. When asked to recall a list of twenty words in any order, people remember the first few words well (the primacy effect, since they had time to be rehearsed into LTM), the last few words very well (the recency effect, since they are still sitting fresh in STM), and struggle most with the middle.
-
Yet patient studies soon exposed cracks in a single passive STM box. Patients with damage to verbal STM could still form normal long-term memories, and healthy volunteers can easily hold a six-digit number in mind while simultaneously judging visual shapes, hinting that short-term memory is actually an active, multi-component workspace.
Baddeley's Working Memory and the LLM Context Window¶
-
Think of a chef cooking dinner. A pantry stores hundreds of dry ingredients (long-term memory), while the small chopping board in front of them holds the handful of items being actively sliced, tasted, and combined right now. That chopping board is Working Memory.
-
Alan Baddeley and Graham Hitch (1974; updated 2000) replaced passive STM with a four-part Working Memory architecture.
- 1. Central Executive is the supervisory controller that allocates attention, switches tasks, inhibits distractions, and coordinates the other buffers (tightly linked to prefrontal cortex).
- 2. Phonological Loop acts as your "inner voice" and phonological store, holding roughly 2 seconds of spoken words or digits via silent rehearsal (which explains why longer words are harder to hold in mind than short ones, the word-length effect).
- 3. Visuospatial Sketchpad serves as your mental canvas for rotating 3D objects, imagining a friend's face, or picturing the turn-by-turn map back to your hotel.
-
4. Episodic Buffer (added in 2000) is a multimodal integration stage that binds sound, vision, and retrieved long-term memories into unified, chronological scenes.
-
How much fits on that chopping board? George Miller (1956) famously estimated the magical number \(7 \pm 2\) items, while emphasising the superpower of chunking. The string
F-B-I-C-I-A-I-B-Mis 9 letters (overloading STM), whereasFBI,CIA,IBMis just 3 meaningful chunks. Once researchers prevent silent rehearsal and chunking, Nelson Cowan (2001) found the pure focus-of-attention limit is even tighter, sitting around \(4 \pm 1\) chunks. -
Pause and appreciate the astonishing architectural parallel to Large Language Models (Chapter 07).
- Working memory mirrors the context window and KV cache. An LLM's context window holds active tokens for immediate reasoning without modifying a single synaptic weight. It is fast, flexible, and strictly bounded in capacity, so once tokens scroll out of the window (or get evicted from the KV cache), they vanish unless written elsewhere.
- Serial position mirrors "Lost in the Middle". Remarkably, long-context LLMs exhibit their own primacy and recency bias, retrieving facts near the start or end of a prompt far more reliably than facts buried in the middle.
- Chunking mirrors subword tokenisation. Grouping raw characters into BPE tokens (Chapter 07) packs far more semantic meaning into the same fixed context budget, forming the exact silicon analogue of Miller's chunking.
Long-Term Memory Taxonomy¶
-
In 1953, a young man known as patient H.M. underwent surgery removing both hippocampi to treat severe epilepsy. Afterwards, he could hold a short conversation normally (intact working memory) and vividly remembered his childhood (consolidated LTM), yet he could never form a single new conscious memory of what happened five minutes ago.
-
Astonishingly, when researchers asked H.M. to trace a star seen only in a mirror day after day, his hand grew steadily faster and smoother, even though each morning he swore he had never seen the apparatus before. Cases like H.M. proved that Long-Term Memory splits into fundamentally distinct neural systems (Larry Squire's taxonomy).
-
Declarative (Explicit) Memory covers "knowing that", meaning consciously recallable facts and events that depend on the medial temporal lobe and hippocampus during acquisition.
- Episodic memory (Endel Tulving) provides autobiographical "mental time travel" tied to a specific time and place ("the rainy Tuesday when I first got backpropagation to converge").
- Semantic memory stores context-free general facts, vocabulary, and conceptual schemas ("the chain rule multiplies local derivatives"). Over time, repeated episodes get distilled into semantic knowledge.
-
Non-Declarative (Implicit) Memory covers "knowing how", expressed automatically through behaviour without conscious recollection.
- Procedural memory holds motor and cognitive skills like riding a bike, touch-typing, or fluent guitar chords (supported by the basal ganglia, cerebellum, and motor cortex).
- Priming speeds up processing after prior exposure, so encountering the word
"DOCTOR"makes you recognise"NURSE"milliseconds faster moments later even if you never consciously noticed the first word. - Classical conditioning and habituation encode automatic learned reflexes and emotional responses.
Forgetting, Spacing, and Retrieval Practice¶
-
In 1885, Hermann Ebbinghaus memorised thousands of nonsense syllables (like
DAX,BOK,WUG) and tested himself after varying delays to measure pure memory decay without prior associations. He uncovered the iconic Ebbinghaus forgetting curve, where forgetting is brutally steep in the first hours before flattening into a long tail. -
A clean mathematical approximation models retrievability \(R(t) \in (0, 1]\) after elapsed time \(t\) as an exponential decay governed by a memory trace's stability \(S > 0\) (the time until recall probability falls to \(1/e \approx 37\%\)).
-
Every time you successfully retrieve a memory, its stability \(S\) grows, flattening the next forgetting curve so the memory lasts days, then weeks, then years. Two robust empirical laws govern how fast \(S\) grows.
- The Spacing Effect shows that ten hours of study spread across ten days produces drastically higher long-term retention than a single ten-hour all-nighter (massed practice). Reviewing a memory right as it becomes effortful to recall (desirable difficulty) yields a far larger boost to stability \(S\) than reviewing it five seconds after reading it.
- The Testing Effect (Active Retrieval Practice), demonstrated by Roediger and Karpicke (2006), shows that passively re-reading notes creates a deceptive illusion of fluency, whereas forcing your brain to actively reconstruct an explanation from memory strengthens the trace far more powerfully.
-
Look back at the Foreword ("How To Study Better") of this very compendium. Without naming the psychology literature, Henry's two-phase method hits both mechanisms dead-centre.
- Phase 1 (Cumulative reading after classes, before bed) harnesses the spacing effect and sleep consolidation so patterns connect across lectures rather than fading overnight.
- Phase 2 (Shadow reading, where you read a subtitle, close the book, reconstruct the concept from scratch, and re-read only the gaps) is pure active retrieval practice. It generates prediction errors on exactly the parts your mental model missed, just like masked-language modelling (Chapter 07) trains a neural network on the tokens it cannot yet predict.
Complementary Learning Systems and Catastrophic Forgetting¶
-
Both brains and neural networks face a deep engineering riddle known as the stability-plasticity dilemma.
- You need high plasticity to remember a one-off fact instantly ("I parked on level 3, bay B14 today").
- You also need high stability so learning today's parking spot does not wipe out your lifelong knowledge of English grammar or how to drive.
-
What happens if you try to solve both inside a single neural network trained with gradient descent (Chapter 06)? Suppose you train a network on Task A until it reaches high accuracy, and then train it sequentially on Task B using fresh gradients. Because both tasks share overlapping weights, the large weight updates optimising Task B violently scramble the representations built for Task A, causing Task A accuracy to plummet. This failure mode is catastrophic forgetting.
-
In 1995, McClelland, McNaughton, and O'Reilly proposed Complementary Learning Systems (CLS) theory to explain how mammalian brains solve this exact dilemma by splitting labour across two interacting systems.
- 1. Hippocampus (Fast Episodic Learner) uses a high learning rate and sparse, pattern-separated representations (like near-orthogonal vectors in Chapter 01). Because each new episode activates a distinct small subset of neurons, you can store today's parking bay in one shot without overwriting yesterday's.
- 2. Neocortex (Slow Statistical Learner) uses a tiny learning rate and dense, overlapping distributed representations. Slow, gentle gradient-like updates allow the neocortex to discover shared statistical structure across thousands of experiences and generalise smoothly.
-
3. Offline Sleep Replay (Interleaved Consolidation) bridges the two systems. During quiet rest and slow-wave sleep, the hippocampus rapidly replays recent episodic traces interleaved with existing neocortical knowledge, allowing the neocortex to absorb new regularities gradually without catastrophic interference.
-
Look at how modern AI independently converged on CLS.
- Deep Q-Networks (Chapter 06) store recent transitions in a fast experience replay buffer (hippocampus) and sample random mini-batches to update the slow neural weights (neocortex); without replay, DQN catastrophically forgets earlier trajectories and diverges.
- Retrieval-Augmented Generation (RAG) pairs a frozen or slowly-trained parametric LLM (neocortex) with a fast non-parametric vector store of fresh documents (hippocampus) so the system absorbs new facts in one shot without retraining.
Associative Learning from Rescorla-Wagner to Temporal Difference RL¶
-
Long before deep reinforcement learning, psychologists asked how animals learn to predict rewards and dangers in the world.
- In classical conditioning (Ivan Pavlov), repeatedly ringing a bell (Conditioned Stimulus, CS) just before delivering food (Unconditioned Stimulus, US) trains a dog to salivate at the bell alone (Conditioned Response, CR).
- In operant conditioning (Thorndike's Law of Effect and B. F. Skinner), behaviours followed by rewarding consequences grow more frequent, while behaviours followed by aversive consequences fade away.
-
For decades, people assumed classical conditioning worked by simple co-occurrence, believing that pairing bell and food enough times mechanically strengthens the link. Then Leon Kamin (1969) ran the landmark blocking experiment that shattered that view.
- First, train a rat that a tone reliably predicts food.
- Next, present tone + light together followed by the exact same food.
- Finally, test the light alone. Surprisingly, the rat shows almost zero response to the light, even though the light was paired with food dozens of times.
-
Why did the tone block learning about the light? Because the food was already completely predicted by the tone, leaving no surprise.
-
Robert Rescorla and Allan Wagner (1972) formalised this surprise-driven learning in one of the most influential equations in cognitive science. Let \(V_i\) be the associative strength (expected reward) of cue \(i\), and let \(V_{\text{total}} = \sum_{j \in \text{present}} V_j\) be the total expectation summed over all cues currently present. On each trial where the actual outcome magnitude is \(\lambda\), every present cue updates according to the prediction error.
-
Every symbol has a crisp meaning.
- \(\alpha_i \in (0, 1]\) is the salience (learnability) of cue \(i\).
- \(\beta \in (0, 1]\) is the learning rate associated with the outcome (US).
- \(\lambda\) is the actual outcome magnitude (for example, \(\lambda = 1\) when food arrives and \(\lambda = 0\) during extinction when food is withheld).
- \(\delta = \lambda - \sum_j V_j\) is the prediction error (surprise).
-
Check what happens in Kamin's blocking experiment. After phase 1, \(V_{\text{tone}} \approx \lambda = 1\). When the light is added in phase 2, \(V_{\text{total}} = V_{\text{tone}} + V_{\text{light}} = 1 + 0 = 1\), so the prediction error is \(\lambda - V_{\text{total}} = 1 - 1 = 0\), giving \(\Delta V_{\text{light}} = 0\). Notice mathematically that Rescorla-Wagner is literally stochastic gradient descent (Chapter 03 and Chapter 06) on the squared prediction error \(\frac{1}{2}(\lambda - \mathbf{w}^T \mathbf{x})^2\).
-
Rescorla-Wagner has one limitation, because it only updates once per whole trial and ignores when inside a trial cues and rewards occur. Sutton and Barto's Temporal Difference (TD) learning (Chapter 06) generalised the exact same prediction-error principle across continuous time steps \(t\).
-
Here \(r_t\) is the immediate reward at step \(t\), \(\gamma \in [0, 1)\) is the discount factor, and \(\delta_t\) is the TD reward prediction error (RPE). When there is only a single time step (\(V(s_{t+1}) = 0\)), TD learning collapses identically back into Rescorla-Wagner.
-
In one of the greatest moments of convergence between neuroscience, cognitive science, and AI, Wolfram Schultz, Peter Dayan, and Read Montague (1997) recorded midbrain dopamine neurons in primates learning cue-reward pairings and discovered that dopamine firing behaves exactly like the TD error \(\delta_t\).
- Before learning, dopamine spikes at the moment unexpected juice arrives (\(\delta > 0\)).
- After learning, the dopamine burst migrates backward in time to the earliest predictive cue (signalling future discounted value \(\gamma V\)), while the fully expected juice itself produces no extra spike (\(\delta \approx 0\)).
- During unexpected omission, if the cue appears and the expected juice fails to arrive, dopamine dips sharply below baseline (\(\delta < 0\)) at the exact instant the juice was due.
-
What began as a mathematical law of animal learning became the core value-learning engine of modern reinforcement learning, from AlphaGo to RLHF.
Take-Home¶
- Working memory (Baddeley's central executive, phonological loop, visuospatial sketchpad, and episodic buffer) is an active, tiny workspace (~4 chunks) that directly parallels an LLM's context window and KV cache.
- Long-term memory separates conscious declarative memory (episodic events and semantic facts) from unconscious non-declarative memory (procedural skills and priming).
- Spacing and active retrieval practice multiply memory stability \(S\) far faster than cramming or passive re-reading, explaining the cognitive science behind the compendium's Foreword study method.
- Complementary Learning Systems (CLS) solves the stability-plasticity dilemma with a fast, sparse hippocampus and a slow, overlapping neocortex bridged by interleaved sleep replay, directly explaining catastrophic forgetting and why experience replay and RAG work in AI.
- Learning is driven by prediction error, not mere repetition. The Rescorla-Wagner rule explains blocking and connects directly to TD learning (Chapter 06) and biological dopamine signals.
Coding Tasks (use CoLab or notebook)¶
-
Simulate the Ebbinghaus forgetting curve \(R(t) = e^{-t/S}\) over 30 days comparing massed cramming (4 reviews on days 0.5 to 2) against spaced retrieval practice (reviews on days 1, 3.5, 9, and 18), where retrieving a harder memory multiplies stability \(S\) more strongly (desirable difficulty).
import jax.numpy as jnp import matplotlib.pyplot as plt def simulate_retention(review_days, total_days=30, dt=0.1): """Simulate Ebbinghaus forgetting with spacing-sensitive stability gains.""" times = jnp.arange(0.0, total_days, dt) S = 1.5 # initial memory stability (days) last_review = 0.0 review_set = sorted(review_days) next_idx = 0 retentions = [] for t in times: t_val = float(t) elapsed = t_val - last_review R = float(jnp.exp(-elapsed / S)) # Check if a review happens now if next_idx < len(review_set) and t_val >= review_set[next_idx]: # Desirable difficulty: retrieving when R is lower boosts stability more! difficulty_bonus = 1.0 + 2.8 * (1.0 - R) S = S * difficulty_bonus last_review = t_val R = 1.0 next_idx += 1 retentions.append(R) return times, jnp.array(retentions), S # Same total number of reviews (4), different schedules t, r_cram, s_cram = simulate_retention([0.5, 1.0, 1.5, 2.0]) _, r_space, s_space = simulate_retention([1.0, 3.5, 9.0, 18.0]) print(f"Day-30 recall -> Cramming: {float(r_cram[-1])*100:.1f}% (S={s_cram:.1f}d) | Spaced: {float(r_space[-1])*100:.1f}% (S={s_space:.1f}d)") plt.figure(figsize=(8.5, 4.5)) plt.plot(t, r_cram * 100, color="#e74c3c", linewidth=2.2, label=f"Massed cramming (4 reviews, final={float(r_cram[-1])*100:.0f}%)") plt.plot(t, r_space * 100, color="#27ae60", linewidth=2.4, label=f"Spaced retrieval (4 reviews, final={float(r_space[-1])*100:.0f}%)") plt.xlabel("Days since initial learning") plt.ylabel("Recall probability R(t) (%)") plt.title("Ebbinghaus Forgetting Curve: Same Effort, Vastly Different Retention") plt.ylim(0, 105) plt.legend() plt.grid(alpha=0.3) plt.show() -
Demonstrate catastrophic forgetting and Complementary Learning Systems (interleaved replay) using a small neural network trained with
jax.grad. Train first on Task A (context 0), then sequentially on Task B (context 1, reversed rule) both without replay and with a hippocampal replay buffer, and plot Task A retention.import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Task A (context=0): classify x > 0 as 1, x < 0 as 0 # Task B (context=1): reversed rule (x > 0 as 0, x < 0 as 1) on the same sensory axis! key = jax.random.PRNGKey(7) k1, k2, k3, k4, kw = jax.random.split(key, 5) xA_neg = jnp.concatenate([jax.random.normal(k1, (40, 1)) * 0.4 - 1.5, jnp.zeros((40, 1))], axis=1) xA_pos = jnp.concatenate([jax.random.normal(k2, (40, 1)) * 0.4 + 1.5, jnp.zeros((40, 1))], axis=1) X_A = jnp.concatenate([xA_neg, xA_pos], axis=0) y_A = jnp.concatenate([jnp.zeros(40), jnp.ones(40)]) xB_neg = jnp.concatenate([jax.random.normal(k3, (40, 1)) * 0.4 - 1.5, jnp.ones((40, 1))], axis=1) xB_pos = jnp.concatenate([jax.random.normal(k4, (40, 1)) * 0.4 + 1.5, jnp.ones((40, 1))], axis=1) X_B = jnp.concatenate([xB_neg, xB_pos], axis=0) y_B = jnp.concatenate([jnp.ones(40), jnp.zeros(40)]) # Pack small MLP weights (2 -> 8 -> 1) into a single flat vector for Pyodide-safe jax.grad def unpack(theta): W1 = theta[:16].reshape((2, 8)) b1 = theta[16:24] W2 = theta[24:32].reshape((8, 1)) b2 = theta[32:33] return W1, b1, W2, b2 def predict(theta, X): W1, b1, W2, b2 = unpack(theta) h = jnp.tanh(jnp.dot(X, W1) + b1) return jax.nn.sigmoid((jnp.dot(h, W2) + b2).reshape((-1,))) def bce_loss(theta, X, y): p = jnp.clip(predict(theta, X), 1e-6, 1.0 - 1e-6) return -jnp.mean(y * jnp.log(p) + (1.0 - y) * jnp.log(1.0 - p)) def accuracy(theta, X, y): return float(jnp.mean((predict(theta, X) > 0.5) == (y > 0.5))) theta_init = jax.random.normal(kw, shape=(33,)) * 0.6 grad_loss = jax.grad(bce_loss) # Phase 1: learn Task A theta_after_A = theta_init for _ in range(80): theta_after_A = theta_after_A - 0.6 * grad_loss(theta_after_A, X_A, y_A) # Phase 2a: naive sequential training on Task B (no replay) theta_naive = theta_after_A acc_A_naive, acc_B_naive = [], [] for _ in range(120): theta_naive = theta_naive - 0.6 * grad_loss(theta_naive, X_B, y_B) acc_A_naive.append(accuracy(theta_naive, X_A, y_A)) acc_B_naive.append(accuracy(theta_naive, X_B, y_B)) # Phase 2b: CLS interleaved replay (mix hippocampal buffer of Task A with Task B) theta_cls = theta_after_A X_mix = jnp.concatenate([X_B, X_A[:20], X_A[40:60]], axis=0) y_mix = jnp.concatenate([y_B, y_A[:20], y_A[40:60]], axis=0) acc_A_cls, acc_B_cls = [], [] for _ in range(120): theta_cls = theta_cls - 0.6 * grad_loss(theta_cls, X_mix, y_mix) acc_A_cls.append(accuracy(theta_cls, X_A, y_A)) acc_B_cls.append(accuracy(theta_cls, X_B, y_B)) print(f"After Task B (Naive): Task A = {acc_A_naive[-1]*100:.1f}%, Task B = {acc_B_naive[-1]*100:.1f}%") print(f"After Task B (CLS): Task A = {acc_A_cls[-1]*100:.1f}%, Task B = {acc_B_cls[-1]*100:.1f}%") steps = jnp.arange(1, 121) plt.figure(figsize=(8.5, 4.5)) plt.plot(steps, jnp.array(acc_A_naive) * 100, color="#e74c3c", linewidth=2.2, label="Task A accuracy (no replay -> catastrophic forgetting)") plt.plot(steps, jnp.array(acc_A_cls) * 100, color="#27ae60", linewidth=2.4, label="Task A accuracy (with CLS replay)") plt.plot(steps, jnp.array(acc_B_cls) * 100, "--", color="#3498db", linewidth=2.0, label="Task B accuracy (with CLS replay)") plt.xlabel("Task B training steps") plt.ylabel("Accuracy (%)") plt.title("Complementary Learning Systems Prevents Catastrophic Forgetting") plt.ylim(0, 105) plt.legend() plt.grid(alpha=0.3) plt.show() -
Simulate both Kamin's blocking effect via Rescorla-Wagner and the dopamine TD prediction-error shift across a 10-step trial, watching the prediction error migrate from reward delivery (\(t=8\)) back to cue onset (\(t=2\)).
import jax.numpy as jnp import matplotlib.pyplot as plt # --- Part A: Rescorla-Wagner Blocking --- def run_rw(pretrain_tone=True, alpha=0.3, beta=0.5, lam=1.0): v_tone, v_light = 0.0, 0.0 hist_tone, hist_light = [], [] # Phase 1: 20 trials of tone -> food (only for blocking group) for _ in range(20): if pretrain_tone: err = lam - v_tone v_tone = v_tone + alpha * beta * err hist_tone.append(v_tone) hist_light.append(v_light) # Phase 2: 20 compound trials of (tone + light) -> food for _ in range(20): err = lam - (v_tone + v_light) v_tone = v_tone + alpha * beta * err v_light = v_light + alpha * beta * err hist_tone.append(v_tone) hist_light.append(v_light) return jnp.array(hist_tone), jnp.array(hist_light) t_block, l_block = run_rw(pretrain_tone=True) t_ctrl, l_ctrl = run_rw(pretrain_tone=False) print(f"Final light strength -> Blocked group: {float(l_block[-1]):.3f} | Control group: {float(l_ctrl[-1]):.3f}") # --- Part B: TD Learning Dopamine Shift --- # 10 time steps per trial: cue appears at t=2, reward arrives at t=8 T = 10 cue_t, rew_t = 2, 8 gamma, lr = 0.95, 0.25 V = [0.0] * (T + 1) def run_td_trial(V_vals): deltas = [] V_new = list(V_vals) for t in range(T): r = 1.0 if t == rew_t else 0.0 # States before cue carry no information yet (V = 0) v_curr = V_new[t] if t >= cue_t else 0.0 v_next = V_new[t + 1] if (t + 1) >= cue_t else 0.0 delta = r + gamma * v_next - v_curr deltas.append(delta) if t >= cue_t: V_new[t] = v_curr + lr * delta return V_new, jnp.array(deltas) delta_early, delta_late = None, None for ep in range(80): V, deltas = run_td_trial(V) if ep == 0: delta_early = deltas if ep == 79: delta_late = deltas fig, axes = plt.subplots(1, 2, figsize=(11, 4)) trials = jnp.arange(1, 41) axes[0].plot(trials, t_block, color="#3498db", linewidth=2, label="Tone (blocked group)") axes[0].plot(trials, l_block, color="#e74c3c", linewidth=2.4, label="Light (blocked -> stays ~0!)") axes[0].plot(trials, l_ctrl, "--", color="#27ae60", linewidth=2.2, label="Light (control -> learns 0.5)") axes[0].axvline(20.5, color="#666666", linestyle=":", label="Compound phase starts") axes[0].set_xlabel("Trial") axes[0].set_ylabel("Associative strength V") axes[0].set_title("Rescorla-Wagner: Kamin Blocking Effect") axes[0].legend(fontsize=8) axes[0].grid(alpha=0.3) ts = jnp.arange(T) axes[1].plot(ts, delta_early, "o-", color="#f39c12", linewidth=2.2, label="Trial 1 (burst at reward t=8)") axes[1].plot(ts, delta_late, "s-", color="#9b59b6", linewidth=2.4, label="Trial 80 (burst shifts to cue t=2)") axes[1].axvline(cue_t, color="#3498db", linestyle=":", alpha=0.7, label="Cue onset (t=2)") axes[1].axvline(rew_t, color="#27ae60", linestyle=":", alpha=0.7, label="Reward (t=8)") axes[1].set_xlabel("Time step within trial") axes[1].set_ylabel("TD prediction error (dopamine)") axes[1].set_title("TD Learning: Dopamine Shifts From Reward to Cue") axes[1].legend(fontsize=8) axes[1].grid(alpha=0.3) plt.tight_layout() plt.show()