Brain Architecture and Sensory Pathways¶
If individual neurons are the transistors of the mind, cortical circuits and large-scale brain pathways are its system architecture. This file explores the canonical 6-layer neocortical microcircuit, the hierarchical visual and auditory streams, the hippocampal cognitive map engine, and the prefrontal and basal ganglia circuits that power working memory and reinforcement learning.
The Canonical 6-Layer Neocortical Microcircuit¶
-
Take a microscope and examine a tiny slice of neocortex from the back of the brain (vision), the side (hearing), or the front (planning). You might expect radically different wiring diagrams for such wildly different jobs. Instead, you find a stunning architectural surprise. Almost the entire human neocortex is built from the same repeating 2-millimetre-thick, 6-layer canonical microcircuit (described by Rodney Douglas and Kevan Martin).
-
Think of the neocortex like a modern skyscraper built from a standardised floor-plan module, replicated thousands of times side by side and specialised mainly by what is plugged into each wing. Each layer plays a distinct computational role.
- Layer 1 (L1, top-down context) is almost devoid of cell bodies and is packed instead with long-range axons carrying contextual predictions and attention signals from higher cortical areas onto the upper dendritic tufts of deeper cells.
- Layers 2 and 3 (L2/3, local workshop and feedforward output) are rich in horizontal recurrent connections that integrate nearby context, then send processed representations forward to the next cortical area up the hierarchy.
- Layer 4 (L4, the feedforward inbox) serves as the primary receiving station for bottom-up sensory inputs arriving from the thalamus or from lower cortical areas.
- Layer 5 (L5, motor and subcortical output) houses giant pyramidal neurons that broadcast commands outward to subcortical targets (the basal ganglia, brainstem, and spinal cord), turning perception into action.
- Layer 6 (L6, feedback and thalamic gain control) sends top-down modulatory feedback back down to lower cortical areas and to the thalamus, adjusting the "volume knob" on incoming sensory streams.
-
Vertically, neurons across layers 1 to 6 that share a receptive field and stimulus preference stack into cortical columns (Mountcastle, 1957). In primary visual cortex, a hypercolumn (roughly 1 mm² of cortical surface) neatly packs a complete set of orientation preferences (\(0^\circ\) to \(180^\circ\)) and left/right eye inputs for a single patch of the visual field, much like a tiny local convolutional filter bank (chapter 08).
-
One anatomical fact immediately separates biological cortex from standard feedforward neural networks (chapters 06 and 08). Top-down feedback connections routinely outnumber bottom-up feedforward connections. For example, primary visual cortex (V1) sends roughly ten times more feedback fibres back down to the thalamus (LGN) than the thalamus sends forward to V1. The brain is not a one-way sensory conveyor belt, but a deeply recurrent prediction engine constantly comparing incoming data against top-down expectations.
The Visual Hierarchy and Two Streams¶
-
Imagine assembling a jigsaw puzzle of a cat. First you spot raw patches of dark and light, then short straight edges, then curved whiskers and fur textures, and finally the unmistakable shape of a cat regardless of whether it is sitting on a sofa, facing left, or half-hidden behind a curtain. Primate vision executes this exact progressive untangling across a hierarchy of cortical areas.
- In the retina, photoreceptors capture light and retinal ganglion cells compute centre-surround contrast (firing strongly to a bright dot surrounded by darkness, or vice versa). Mathematically, this acts like a Difference-of-Gaussians filter (chapter 08), discarding uniform illumination and highlighting sharp boundaries.
- The LGN (Lateral Geniculate Nucleus) serves as a thalamic relay station that preserves the spatial map of the retina while receiving massive top-down attention and feedback modulation from cortex.
- In V1 (Primary Visual Cortex), simple cells convert circular centre-surround dots into oriented edges (Gabor-like filters, file 01), while complex cells add local position invariance across tiny, strictly local receptive fields.
- Area V2 combines V1 edges into junctions, corners, border ownership (which side is figure versus background), and illusory contours.
- Area V4 encodes intermediate curvature, surface textures, and colour constancy across larger receptive fields.
- At the summit of object recognition, IT Cortex (Inferotemporal Cortex) neurons have huge receptive fields and respond selectively to high-level categories such as faces (for example, in the Fusiform Face Area), bodies, scenes, and everyday objects, remaining largely invariant to position, scale, lighting, and viewpoint.
-
Beyond V1, visual processing splits along two major anatomical highways (Ungerleider and Mishkin, extended by Goodale and Milner).
- The Ventral ("What") Stream (
V1 -> V2 -> V4 -> IT) runs downward into the temporal lobe and builds view-invariant representations for object recognition, reading, and semantic memory. - The Dorsal ("Where / How") Stream (
V1 -> MT/V5 -> Posterior Parietal Cortex) runs upward into the parietal lobe, tracking motion, 3D depth, spatial layout, and visually guided actions such as catching a ball or shaping your fingers to grasp a mug (closely related to autonomous perception and visuomotor control in chapter 14).
- The Ventral ("What") Stream (
Deep Vision Models Meet the Ventral Stream¶
-
One of the most striking empirical discoveries of NeuroAI (Yamins et al., 2014; Khaligh-Razavi and Kriegeskorte, 2014) is the layer-to-area correspondence between deep vision models (CNNs and Vision Transformers from chapter 08) and the primate ventral stream. When you train a deep network solely to classify natural images, without showing it a single biological brain recording, its early layers spontaneously best predict V1 and V2 neurons, its intermediate layers best predict V4, and its penultimate deep layers best predict IT cortex.
-
Yet biological vision still outperforms modern AI in three critical respects.
- Recurrence for hard images lets primates take an extra 30 to 60 ms when an object is heavily occluded, blurred, or cluttered, allowing lateral and top-down recurrent loops to iteratively clean up the interpretation where purely feedforward CNNs falter.
- Foveated active vision avoids wasting compute uniformly across an entire 4K frame. Your eyes pack dense receptors into a tiny ~2° fovea and dart around 3 to 4 times per second (saccades) to sample only the most informative details.
- Robustness keeps human vision virtually immune to imperceptible pixel-level adversarial perturbations while generalising effortlessly to sketches, silhouettes, and novel weather conditions.
The Auditory Pathway and Speech Hierarchy¶
-
Hearing faces a mirror-image problem to vision. Instead of a 2D spatial grid of photons, the ear receives a single 1D pressure waveform \(x(t)\) mixing every voice, footstep, and siren in the room.
-
Picture a grand piano string board running in reverse. Inside your inner ear, the snail-shaped cochlea houses the basilar membrane, which is narrow and stiff at its base (resonating with high-pitched frequencies) and wide and flexible at its apex (resonating with low-pitched frequencies). This mechanical gradient performs a real-time biological short-time Fourier and Mel-scale decomposition (chapter 10), mapping frequency onto physical position in an organisation called tonotopy.
-
Hair cells along the basilar membrane convert mechanical vibration into phase-locked spikes that ascend through the brainstem, inferior colliculus, and medial geniculate body (MGB) of the thalamus into primary auditory cortex (A1), preserving the smooth tonotopic map all the way up.
-
From A1 onward, human speech processing climbs a hierarchical ladder that closely mirrors automatic speech recognition pipelines (chapter 10).
- A1 (Core) extracts local spectrotemporal modulations such as pitch contours, harmonic stacks, and rapid frequency sweeps.
- Superior Temporal Gyrus (STG, belt and parabelt) builds categorical sensitivity to phonemes, voice-onset times, and syllables, invariant to speaker pitch.
- Superior Temporal Sulcus (STS) and temporal-frontal association cortex integrate syllables into words, syntactic phrases, and sentence-level meaning (connecting to language models in chapter 07). Just like vision, audition splits into a ventral "what" stream for speech comprehension and a dorsal "how" stream mapping sound onto motor speech production.
Hippocampus and Entorhinal Cortex as a Cognitive Map Engine¶
-
How do you walk through your home in pitch darkness without bumping into the coffee table, or immediately take a novel shortcut through a neighbourhood you have only ever walked around the perimeter of? In 1948, Edward Tolman proposed that animals build an internal cognitive map. Decades later, neuroscientists uncovered the exact neural coordinate system inside the hippocampal-entorhinal circuit (earning the 2014 Nobel Prize).
-
Imagine a GPS navigation app broken into specialised cell types.
- Place cells (John O'Keefe, 1971, in hippocampus CA1 and CA3) fire briskly whenever the animal visits one specific spot (its place field) and stay quiet elsewhere. Together, thousands of place cells tile a room like a sparse mosaic.
- Grid cells (May-Britt and Edvard Moser, 2005, in medial entorhinal cortex, MEC) fire at multiple locations arranged in a breathtakingly regular hexagonal (triangular) lattice across the entire environment. Different entorhinal modules use different grid spacings \(\lambda_m\) (from roughly 30 cm up to several metres), functioning like a multi-scale metric ruler.
- Head-direction cells act as an internal compass, firing whenever the animal faces a particular azimuth angle.
- Border and boundary cells fire along walls and edges, anchoring the internal map so dead-reckoning drift does not accumulate.
-
Mathematically, an idealised 2D grid cell's spatial firing pattern \(g(\mathbf{r})\) at position \(\mathbf{r} = (x, y)^T\) can be modelled as the rectified superposition of three cosine plane waves oriented \(60^\circ\) apart.
-
Here \(\mathbf{k}_1, \mathbf{k}_2, \mathbf{k}_3\) are wave vectors of equal length \(k = \frac{4\pi}{\sqrt{3}\,\lambda_{\text{grid}}}\) separated by \(60^\circ\), \(\lambda_{\text{grid}}\) is the grid spacing, and \(\mathbf{r}_0\) sets the spatial phase. Summing grid cells across several spatial scales naturally interferes constructively at a single location and cancels elsewhere, generating a crisp hippocampal place field.
-
Because grid cells update their phase continuously from self-motion velocity signals (speed and heading), they implement path integration (dead reckoning), allowing you to track where you are even with your eyes closed.
From 2D Rooms to Abstract Concepts and the Tolman-Eichenbaum Machine¶
-
The deepest twist came when researchers asked whether this grid-and-place machinery is only for physical rooms. In 2016, Alexandra Constantinescu and colleagues taught human volunteers to associate rewards with cartoon birds whose neck length and leg length varied continuously, forming an abstract 2D "bird space". Using fMRI, they detected the exact 6-fold hexagonal symmetry of grid-cell-like representations in human entorhinal cortex as participants mentally navigated between bird shapes. Subsequent studies found similar cognitive maps for social hierarchies, odour mixtures, and abstract relational graphs.
-
The Tolman-Eichenbaum Machine (TEM) (Whittington et al., 2020) unifies these discoveries into a crisp NeuroAI model by explicitly factorising the world into two interacting parts.
- Structural transitions in entorhinal cortex (\(\mathbf{g}_t\)) learn reusable abstract rules of how actions move you through spaces or graphs (for instance, knowing that stepping North, East, South, and West returns you to the start in every room, regardless of furniture).
- Sensory observations bound to structure in hippocampus (\(\mathbf{p}_t\)) use fast Hebbian conjunctive memory (an attractor network binding \(\mathbf{g}_t\) and sensory input \(\mathbf{x}_t\)) to remember what sits at each node in this specific room or family tree.
-
Because structural knowledge is separated from sensory content, TEM achieves zero-shot relational generalisation. Walk into a brand-new environment, glimpse two landmarks, and immediately infer shortcuts you have never physically travelled.
Prefrontal Cortex and Basal Ganglia for Memory, Gating, and RL¶
- Perceiving the world and mapping space are only half the story. An intelligent agent must also hold goals in mind, switch rules flexibly, and choose rewarding actions. Two tightly coupled systems orchestrate this executive control, namely the prefrontal cortex (PFC) and the basal ganglia.
Prefrontal Cortex, Working Memory, and Meta-Learning¶
-
Picture a mental whiteboard where you jot down a six-digit verification code just long enough to type it in, then wipe it clean. That active online buffer is working memory, and the prefrontal cortex (PFC) maintains it through persistent recurrent attractor activity, in which reverberating loops of excitatory neurons keep firing even after the external stimulus disappears.
-
Crucially, PFC does not just passively store items. It performs executive gating (deciding what gets written to the whiteboard, what stays protected from distraction, and which task rule currently applies) and meta-learning ("learning to learn"). In a celebrated NeuroAI study, Jane Wang and colleagues (2018) trained a recurrent neural network via slow model-free reinforcement learning across a family of bandit tasks. Once weights were frozen, the network's recurrent hidden state alone adapted rapidly to brand-new reward contingencies within seconds, reproducing signature PFC firing patterns and illustrating how slow synaptic learning gives rise to fast in-context adaptation (a direct biological parallel to in-context learning in Transformers, chapter 07).
Basal Ganglia and Midbrain Dopamine as Temporal Difference Learning¶
-
At any moment, your cortex proposes dozens of competing candidate actions (take a sip of coffee, answer a message, stretch your arms). How does the brain commit cleanly to one action without getting paralysed in the middle? Enter the basal ganglia, a subcortical switchboard structured around two opposing pathways.
- The Direct ("Go") pathway releases the brake on the thalamus, amplifying and executing a selected motor or cognitive action (including opening the gate to update PFC working memory).
- The Indirect ("No-Go") pathway tightens the brake on the thalamus, suppressing competing or unrewarding actions.
-
How do the Go and No-Go pathways learn which actions pay off? In 1997, Wolfram Schultz, Peter Dayan, and Read Montague uncovered one of the cleanest mathematical correspondences in all of science. Recording from midbrain dopamine neurons (in the VTA and SNc) during classical conditioning, they found that dopamine cells do not simply fire whenever a monkey receives fruit juice.
- Before learning, an unexpected drop of juice triggers a sharp burst of dopamine spikes.
- After learning (once a tone reliably predicts juice 1 second later), the dopamine burst shifts backward in time to the predictive tone, and the expected juice itself elicits zero extra firing.
- On an unexpected omission trial (the tone plays, the monkey expects juice, and nothing arrives), dopamine neurons dip below baseline at the exact millisecond the juice should have appeared.
-
That three-part signature is literally the Temporal Difference (TD) reward prediction error \(\delta_t\) from reinforcement learning (chapter 06).
- Here \(r_t\) is the immediate reward at time \(t\), \(V(s_t)\) is the estimated expected future return from state \(s_t\), and \(\gamma \in (0, 1]\) is the temporal discount factor. When \(\delta_t > 0\) (better than expected), dopamine bursts strengthen Go synapses in the striatum; when \(\delta_t < 0\) (worse than expected), dopamine dips weaken Go synapses and strengthen No-Go synapses. Long before computer scientists invented deep actor-critic agents, evolution wired a biological actor-critic architecture straight into the striatum and midbrain.
Take-Home¶
- Neocortex reuses one canonical 6-layer microcircuit across sensory and association regions (L4 receives feedforward input, L2/3 computes recurrently and projects forward, L5 drives motor and subcortical output, and L6 sends feedback), with top-down feedback routinely outnumbering bottom-up wires.
- Primate vision separates into ventral ("what") and dorsal ("where/how") streams, with ventral stages (
V1 -> V2 -> V4 -> IT) aligning remarkably with early-to-deep layers of CNNs and ViTs, though biological vision still wins on recurrence, active foveation, and robustness. - Audition transforms 1D waveforms into tonotopic hierarchies, where the cochlea acts as a physical Mel-like filterbank feeding A1 and speech areas that mirror modern ASR pipelines.
- Entorhinal grid cells and hippocampal place cells build a reusable cognitive map, combining hexagonal multi-scale grids for structural path integration with hippocampal sensory binding to navigate both 2D rooms and abstract conceptual spaces (as formalised by the Tolman-Eichenbaum Machine).
- PFC and basal ganglia implement executive control and biological RL, pairing recurrent working memory and meta-learning with Go/No-Go striatal action selection driven by midbrain dopamine TD prediction errors \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\).
Coding Tasks (use CoLab or notebook)¶
-
Construct an idealised 2D hexagonal grid cell from three \(60^\circ\)-rotated cosine plane waves, then sum grid cells across four spatial scales to watch a crisp hippocampal place field emerge via constructive interference.
import jax.numpy as jnp import matplotlib.pyplot as plt def grid_cell_rate(X, Y, spacing, phase=(0.0, 0.0), orientation=0.0): """2D hexagonal grid cell from three plane waves 60 degrees apart.""" k_mag = 4.0 * jnp.pi / (jnp.sqrt(3.0) * spacing) dx = X - phase[0] dy = Y - phase[1] total = jnp.zeros_like(X) for j in range(3): angle = orientation + j * (jnp.pi / 3.0) kx = k_mag * jnp.cos(angle) ky = k_mag * jnp.sin(angle) total = total + jnp.cos(kx * dx + ky * dy) return jnp.maximum(0.0, total) coords = jnp.linspace(-1.0, 1.0, 120) X, Y = jnp.meshgrid(coords, coords) grid_fine = grid_cell_rate(X, Y, spacing=0.45, phase=(0.2, -0.15)) grid_coarse = grid_cell_rate(X, Y, spacing=0.85, phase=(0.2, -0.15)) # Sum grid cells across multiple scales aligned at target (0.2, -0.15) spacings = [0.35, 0.52, 0.77, 1.15] orientations = [0.0, 0.25, 0.55, 0.15] place_sum = jnp.zeros_like(X) for s, ori in zip(spacings, orientations): place_sum = place_sum + grid_cell_rate(X, Y, spacing=s, phase=(0.2, -0.15), orientation=ori) place_cell = jnp.maximum(0.0, place_sum - 0.65 * jnp.max(place_sum)) fig, axes = plt.subplots(1, 3, figsize=(13, 3.8)) for ax, data, title in [ (axes[0], grid_fine, "Fine Grid Cell (spacing=0.45 m)"), (axes[1], grid_coarse, "Coarse Grid Cell (spacing=0.85 m)"), (axes[2], place_cell, "Emergent Place Cell (Multi-Scale Sum)"), ]: ax.imshow(data, origin="lower", extent=[-1, 1, -1, 1], cmap="viridis") ax.set_title(title) ax.set_xlabel("x (m)") ax.set_ylabel("y (m)") plt.tight_layout() plt.show() -
Simulate path integration (dead reckoning) along a smooth 2D foraging trajectory with noisy velocity estimates, showing how drift accumulates over time and how periodic border or landmark anchoring resets position error, then plot the firing of three hippocampal place cells along the path.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(12) T = 240 t = jnp.linspace(0.0, 6.0 * jnp.pi, T) true_x = 0.75 * jnp.sin(t * 0.6) * jnp.cos(t * 0.25) true_y = 0.75 * jnp.sin(t * 0.45) true_pos = jnp.stack([true_x, true_y], axis=1) true_vel = jnp.diff(true_pos, axis=0) noisy_vel = true_vel + jax.random.normal(key, true_vel.shape) * 0.025 # 1. Pure path integration (accumulates unbounded drift) drifted_list = [true_pos[0]] curr = true_pos[0] for v in noisy_vel: curr = curr + v drifted_list.append(curr) drifted_pos = jnp.stack(drifted_list, axis=0) # 2. Path integration with landmark/border reset every 40 steps anchored_list = [true_pos[0]] curr = true_pos[0] for step_idx, v in enumerate(noisy_vel): curr = curr + v if (step_idx + 1) % 40 == 0: curr = true_pos[step_idx + 1] anchored_list.append(curr) anchored_pos = jnp.stack(anchored_list, axis=0) drift_err = jnp.linalg.norm(drifted_pos - true_pos, axis=1) anchor_err = jnp.linalg.norm(anchored_pos - true_pos, axis=1) print(f"Final error (pure dead reckoning): {float(drift_err[-1]):.3f} m") print(f"Mean error (with landmark resets): {float(jnp.mean(anchor_err)):.3f} m") centres = jnp.array([[-0.35, 0.30], [0.35, 0.25], [0.0, -0.45]]) sigma = 0.22 dists_sq = jnp.sum((true_pos[:, None, :] - centres[None, :, :]) ** 2, axis=-1) place_rates = jnp.exp(-dists_sq / (2.0 * sigma ** 2)) fig, axes = plt.subplots(1, 2, figsize=(12, 4.2)) axes[0].plot(true_pos[:, 0], true_pos[:, 1], color="#333333", lw=2, label="True path") axes[0].plot(drifted_pos[:, 0], drifted_pos[:, 1], color="#e74c3c", ls="--", lw=1.4, label="Pure path integration") axes[0].plot(anchored_pos[:, 0], anchored_pos[:, 1], color="#27ae60", lw=1.5, alpha=0.85, label="Landmark-anchored") axes[0].set_title("Path Integration Drift vs Landmark Anchoring") axes[0].set_xlabel("x (m)"); axes[0].set_ylabel("y (m)") axes[0].legend(fontsize=8) for i, col in enumerate(["#3498db", "#e74c3c", "#9b59b6"]): axes[1].plot(place_rates[:, i], color=col, lw=1.8, label=f"Place Cell {i+1}") axes[1].set_title("Hippocampal Place-Cell Activity Along Trajectory") axes[1].set_xlabel("Time step"); axes[1].set_ylabel("Normalised Firing Rate") axes[1].legend() plt.tight_layout() plt.show() -
Reproduce the classic Schultz (1997) midbrain dopamine TD-error experiment by simulating a conditioning trial where a cue at \(t = 5\) predicts a reward at \(t = 15\), training state values \(V(s_t)\) with TD(0), and inspecting \(\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)\) before learning, after learning, and on an unexpected reward-omission trial.
import jax.numpy as jnp import matplotlib.pyplot as plt def run_td_trial(V, cue_t=5, reward_t=15, deliver_reward=True, alpha=0.25, gamma=0.98, update=True): """Run one conditioning trial and return TD prediction errors delta_t and updated V.""" T = len(V) rewards = [0.0] * T if deliver_reward: rewards[reward_t] = 1.0 V_list = [float(v) for v in V] deltas = [] for t in range(T - 1): v_curr = V_list[t] if t >= cue_t else 0.0 v_next = V_list[t + 1] if (t + 1) >= cue_t else 0.0 delta = rewards[t] + gamma * v_next - v_curr deltas.append(delta) if update and t >= cue_t: V_list[t] = V_list[t] + alpha * delta return jnp.array(deltas), jnp.array(V_list) T = 22 V = jnp.zeros(T) # 1. Early trial (naive animal receiving unexpected reward at t=15) delta_naive, V = run_td_trial(V, deliver_reward=True, update=True) # Train across 120 paired cue -> reward trials for _ in range(120): _, V = run_td_trial(V, deliver_reward=True, update=True) # 2. Trained trial (cue predicts reward) delta_trained, _ = run_td_trial(V, deliver_reward=True, update=False) # 3. Unexpected omission trial (cue plays, reward withheld) delta_omission, _ = run_td_trial(V, deliver_reward=False, update=False) print(f"Naive -> delta at cue: {float(delta_naive[5]):+.2f}, at reward: {float(delta_naive[15]):+.2f}") print(f"Trained -> delta at cue: {float(delta_trained[5]):+.2f}, at reward: {float(delta_trained[15]):+.2f}") print(f"Omit -> delta at cue: {float(delta_omission[5]):+.2f}, at expected reward: {float(delta_omission[15]):+.2f}") fig, axes = plt.subplots(1, 3, figsize=(13, 3.6), sharey=True) panels = [ (delta_naive, "Before Learning\n(Burst at Unexpected Reward)", "#3498db"), (delta_trained, "After Learning\n(Burst Shifts to Cue!)", "#27ae60"), (delta_omission, "Reward Omitted\n(Dip at Expected Reward)", "#e74c3c"), ] for ax, (d, title, col) in zip(axes, panels): ax.axhline(0.0, color="#666666", lw=0.9) ax.bar(range(len(d)), d, color=col, alpha=0.8) ax.axvline(5, color="#f39c12", ls="--", lw=1.1, label="Cue (t=5)") ax.axvline(15, color="#9b59b6", ls=":", lw=1.2, label="Reward (t=15)") ax.set_title(title) ax.set_xlabel("Time step t") axes[0].set_ylabel("Dopamine TD Error delta_t") axes[0].legend(fontsize=8) plt.tight_layout() plt.show()