Perception and Attention¶
Raw sensory data is fundamentally ambiguous and overwhelming, because your eyes receive millions of bits of light per second while your brain must reconstruct a coherent 3D world and focus on what matters right now. This file explains Bayesian perception, Gestalt perceptual grouping, Feature Integration Theory, selective attention bottlenecks, inattentional blindness, and how biological attention both inspired and differs from Transformer self-attention.
Why Perception Is an Inverse Problem¶
-
Imagine standing in a dim room looking at the flat shadow of an object cast onto a wall. If you see a circular shadow, was it cast by a sphere, a flat dinner plate held face-on, or a cylinder viewed end-on? You cannot know from the shadow alone, because infinitely many 3D objects cast the exact same 2D projection.
-
That is the daily predicament of your visual system. As we saw with the pinhole camera model in Chapter 08, projecting a 3D world onto a 2D retina throws away depth, tangles illumination with surface reflectance, and mixes object size with distance. Going from 3D reality to a 2D image is a well-posed forward problem, whereas reconstructing 3D reality from a 2D retinal image is an ill-posed inverse problem.
-
Because sensory data alone never uniquely specifies the world, the brain has to bring prior assumptions to the table. That leads to one of the most illuminating insights in cognitive science. Visual illusions are not glitches; they are windows into the brain's hidden priors.
- The light-from-above prior reflects a world where sunlight has shone from overhead throughout evolutionary history. A shaded circle bright on top and dark at the bottom pops out as a convex bump; flip it upside down and it turns instantly into a hollow dent.
- In the hollow-mask illusion, looking at the concave back of a rotating Charlie Chaplin mask fails to look hollow because your extraordinarily strong prior that human faces are convex overrides conflicting binocular depth cues.
- Under illumination and colour constancy, a white piece of paper reflects very different wavelengths under warm indoor tungsten bulbs versus cool blue daylight, yet your brain discounts the inferred illuminant. When a photograph leaves the lighting ambiguous (like the famous blue-and-black versus white-and-gold dress), people with slightly different lighting priors literally perceive completely different colours.
Bayesian Perception and Cue Combination¶
- In the 1860s, Hermann von Helmholtz called perception unconscious inference, arguing that the brain guesses the hidden cause in the world that best explains its noisy sensory measurements. Using Bayes' rule from Chapter 05, if \(s\) is the hidden state of the world (say, an object's position or depth) and \(x\) is the noisy sensory signal, the posterior belief is proportional to the likelihood times the prior.
-
Now picture watching a ventriloquist on stage. Your ears hear the voice coming from the ventriloquist's throat (position \(x_A\)), while your eyes see the dummy's wooden mouth moving fifteen centimetres to the left (position \(x_V\)). Surprisingly, you hear the voice coming straight out of the dummy's mouth. Why does vision hijack hearing?
-
Bayesian cue combination gives an exact, quantitative answer. Suppose Cue 1 (say, audition or a prior) provides a Gaussian estimate with mean \(\mu_1\) and variance \(\sigma_1^2\), and Cue 2 (say, vision) provides an independent Gaussian estimate with mean \(\mu_2\) and variance \(\sigma_2^2\). Define each cue's precision (reliability) as its inverse variance.
- Multiplying the two Gaussians yields a Gaussian posterior whose mean is the precision-weighted average of the two cues and whose precision is the sum of their precisions.
- Look at what those equations predict.
- Sharp cues dominate. Human vision localises space far more precisely than human hearing (\(\sigma_V \ll \sigma_A\)), so \(w_V\) sits close to \(1\) and the combined percept snaps straight onto the dummy's lips.
- Blur reverses the illusion. If you blur the visual cue in a lab experiment (raising \(\sigma_V\)), human observers smoothly decrease \(w_V\) and shift their perceived location back toward the sound, closely matching Bayes' optimal weights (Alais & Burr, 2004; Ernst & Banks, 2002 for vision and touch).
- Two noisy cues beat one. Because \(\tau_{\text{post}} = \tau_1 + \tau_2 > \max(\tau_1, \tau_2)\), the posterior variance \(\sigma_{\text{post}}^2\) is strictly smaller than either sensory modality alone. That same inverse-variance fusion principle is the exact maths behind Kalman filters in autonomous systems and multi-sensor robotics.
Gestalt Principles of Perceptual Grouping¶
-
Look around the room you are sitting in right now. You do not experience a chaotic soup of ten million isolated pixel intensities or disjointed line segments; you immediately see a laptop, a mug, and a desk.
-
In the early twentieth century, Gestalt psychologists (Wertheimer, Koffka, and Köhler) argued that "the whole is different from the sum of its parts" and catalogued the grouping rules the visual system uses to bind local fragments into coherent objects.
- Proximity groups elements that sit close together in space into one cluster (which is why paragraphs work without drawing boxes around them).
- Similarity links elements sharing colour, shape, or orientation (letting you spot your team's jerseys across a crowded pitch).
- Closure mentally completes broken contours into closed shapes, so a triangle missing its corners still reads immediately as a solid triangle.
- Good continuation connects smooth, gently curving edges into one continuous path rather than sharp zigzags (how you follow a power cable winding behind a desk).
- Common fate locks elements moving together at the same velocity into a single object, so a camouflaged leopard disappears in tall grass until it takes a single step.
- Figure-ground segregation splits scenes into a foreground figure (which owns the shared border) and a background ground (which continues behind it), producing reversible bistable percepts like Rubin's vase and faces illusion.
-
Far from being arbitrary quirks, Gestalt laws mirror the statistical regularities of natural physical scenes. Nearby patches of the same colour moving at the same speed almost always belong to the same physical object. In Chapter 08, classical image segmentation algorithms (like normalised cuts and watershed) tried to encode Gestalt cues by hand; today, deep vision backbones and Segment Anything (SAM) learn them automatically from millions of natural images.
Feature Integration Theory and the Binding Problem¶
-
Imagine trying to find a friend in a crowded train station. If they are wearing a neon-orange parka while everyone else wears black coats, they leap off the platform instantaneously whether there are ten people or five hundred. Now imagine they are wearing a red scarf and a blue hat, while the crowd is full of people in red hats and blue scarves. Suddenly you have to scan faces one by one.
-
Why is the second search so much harder? Because the visual cortex is anatomically specialised, with different neural populations processing colour (area V4), motion (area MT/V5), orientation (V1), and shape in separate parallel feature maps. That creates the binding problem, asking how the brain knows that redness belongs to the scarf and blueness belongs to the hat rather than scrambling them together.
-
Anne Treisman's Feature Integration Theory (FIT, 1980) solved this puzzle with a two-stage model.
- In the pre-attentive stage (parallel, automatic), basic features (colour, orientation, size, motion) are extracted simultaneously across the entire visual field in separate feature maps. Searching for a single unique feature (feature search) produces effortless pop-out, so reaction time stays flat (\(O(1)\)) as the number of distractors \(N\) grows.
- In the focused-attention stage (serial, effortful), combining two or more features (conjunction search, like a red
Xamong redOs and greenXs) requires moving an internal attentional spotlight to one spatial location at a time to glue the co-located feature maps into a unified "object file". Reaction time grows linearly (\(O(N)\)), adding roughly 20 to 30 milliseconds per extra item.
-
FIT makes a wonderfully testable prediction. If you flash coloured letters so quickly that attention has no time to bind them, people should report illusory conjunctions, such as seeing a green
Twhen the screen actually showed a redTand a greenX. Indeed, Treisman and Schmidt (1982) observed this exact scrambling in the lab.
Selective Attention, Bottlenecks, and Biased Competition¶
-
Your eyes stream roughly \(10^7\) bits per second down the optic nerve, yet your conscious bottleneck can report only ~40 to 60 bits per second. Selective attention is the brain's triage system, amplifying behaviourally relevant signals while suppressing the rest.
-
For decades, cognitive psychologists debated where along the processing pipeline that bottleneck sits, producing three classic models.
-
1. Early Selection (Broadbent, 1958) emerged from dichotic listening experiments (playing one spoken message into the left ear and another into the right ear while asking the listener to shadow the left). Donald Broadbent found listeners remembered almost nothing of the unattended ear's meaning, though they noticed if the speaker switched from male to female. He proposed an all-or-nothing sensory filter operating early on physical traits (ear, pitch) before any semantic analysis.
-
2. Attenuation Model (Treisman, 1964) fixed a glaring snag in Broadbent's rigid gate, namely that about a third of listeners snapped their head immediately when their own name was whispered into the ignored ear. Anne Treisman replaced the on/off switch with a dimmer switch (attenuator). Unattended channels are turned down rather than deleted, and a downstream dictionary unit assigns permanently low activation thresholds to personally vital words (your name, "fire!", a baby's cry), letting even a weakened signal cross into awareness.
-
3. Late Selection (Deutsch & Deutsch, 1963; Norman, 1968) pushed the filter all the way to the back. Every sensory stream is fully decoded for meaning in parallel, and selection only decides which decoded message earns access to working memory and overt response based on current pertinence.
-
Who was right? Nilli Lavie's Perceptual Load Theory (1995) showed that all three capture part of the truth. When the attended task imposes high perceptual load (complex and demanding), processing capacity fills up early and distractors are filtered out early (Broadbent); when perceptual load is low (easy or boring), spare capacity spills over automatically to process distractors semantically (late selection).
-
Beyond auditory filters, two frameworks capture how attention moves and acts inside the cortex.
- Posner Spatial Cueing (1980) has participants stare at a central cross while a cue hints whether a target will appear on the left or right. Valid cues speed up reaction time and invalid cues slow it down even without moving the eyes (covert attention). A central arrow triggers slow, voluntary endogenous (top-down) attention, whereas a sudden peripheral flash hijacks fast, involuntary exogenous (bottom-up) attention (followed ~300 ms later by inhibition of return, nudging the eye to explore fresh locations).
- Biased Competition (Desimone & Duncan, 1995) zooms down to Marr's implementational level. Multiple objects inside a single cortical neuron's receptive field compete via mutual inhibition (often modelled as divisive normalisation). Top-down feedback from prefrontal and parietal cortex injects an excitatory bias favouring the attended location or feature, tipping the competition so the target dominates firing while distractors fade away.
Striking Failures of Attention¶
-
Because attention is selective and capacity-limited, everyday cognition exhibits three famous phenomena that surprise almost everyone when they first encounter them.
-
The Cocktail Party Effect (Cherry, 1953) happens when you stand in a noisy room buzzing with twenty simultaneous conversations. You can lock onto a single friend's voice using spatial location, pitch, and lip movements, yet still snap alert if someone across the room mentions your name. This exact human feat motivated the audio source separation and speaker extraction systems in Chapter 10.
-
Inattentional Blindness was famously demonstrated by Simons and Chabris (1999). Viewers count basketball passes made by players in white shirts, and half of all viewers completely fail to notice a person in a full gorilla suit walking into the middle of the court, beating their chest, and strolling off. Looking directly at an object is not enough to see it when attention is consumed elsewhere.
-
Change Blindness appears in Rensink's flicker paradigm, where two photographs alternate rapidly with a brief blank grey screen in between. Even massive changes (a jet engine vanishing from an aircraft wing, or a background building disappearing) take tens of seconds to spot. Normally, a sudden change creates a local motion transient that grabs exogenous attention; the blank flicker masks that transient, revealing that we do not hold a high-resolution photographic buffer of the scene inside our heads. As Kevin O'Regan put it, "the world serves as its own outside memory."
From Cognitive Attention to Transformer Self-Attention¶
- The word attention in deep learning was borrowed directly from cognitive psychology, first by Bahdanau et al. (2015) for neural machine translation so a decoder could focus selectively on relevant source words, and then generalised into scaled dot-product self-attention in Transformers (Chapter 07).
-
Meanwhile, in computer vision (Chapter 08), cognitive theories of bottom-up pop-out inspired classic visual saliency models (such as Itti and Koch's feature-contrast maps) and modern Vision Transformer (ViT) attention visualisations.
-
Yet as AI engineers, we should be crystal clear about where the analogy holds and where biological attention and Transformer attention part ways.
| Dimension | Human Cognitive Attention | Transformer Self-Attention |
|---|---|---|
| Primary purpose | Resource conservation & binding to avoid metabolic overload and feature scrambling | Flexible routing to mix information across arbitrary token pairs in parallel |
| Bottleneck stage | Genuine early/mid bottleneck where unselected stimuli are physically suppressed | Closer to late selection, computing every pairwise score \(QK^T\) first (\(O(N^2)\)) before soft-weighting |
| Temporal dynamics | Serial spotlight plus ~3 eye saccades/sec exploring an external world | Single parallel forward pass over the whole context window per layer |
| Top-down vs bottom-up | Explicit split between exogenous saliency (pop-out) and endogenous goals | Blended implicitly inside learned \(W_Q, W_K, W_V\) projections across heads |
- Understanding this gap immediately points toward active AI research frontiers, including sparse and linear attention, active vision (foveated glimpse models that decide where to look at high resolution instead of rasterising every pixel), and top-down goal-conditioned perception in embodied agents.
Take-Home¶
- Perception is an inverse problem. Sensory inputs are ambiguous, so the brain combines noisy likelihoods with ecological priors, and perceptual illusions expose those priors directly.
- Bayesian cue combination weights each sensory modality by its precision (\(1/\sigma^2\)), producing a fused estimate with strictly lower variance than any single sense alone.
- Gestalt grouping and Feature Integration Theory explain how raw pixels become bound objects, where single features pop out in parallel (\(O(1)\)) while feature conjunctions require a serial attentional spotlight (\(O(N)\)).
- Selective attention acts as a flexible, load-dependent gain modulator (biased competition), explaining both our superpower (the cocktail party effect) and our blind spots (inattentional and change blindness).
- Transformer self-attention borrowed the metaphor of selective weighting, yet unlike biological attention it evaluates all pairs in parallel rather than discarding inputs early to save energy.
Coding Tasks (use CoLab or notebook)¶
-
Implement Bayesian cue combination for the ventriloquist effect by fusing a visual cue (dummy's mouth at \(+4^\circ\)) and an auditory cue (ventriloquist's throat at \(-4^\circ\)) as visual blur \(\sigma_V\) increases from crisp (\(0.8^\circ\)) to foggy (\(8.0^\circ\)). Verify the analytical posterior mean and variance, and plot how visual dominance \(w_V\) shifts with blur.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt def gaussian_pdf(x, mu, sigma): return (1.0 / (jnp.sqrt(2.0 * jnp.pi) * sigma)) * jnp.exp(-0.5 * ((x - mu) / sigma) ** 2) # Ventriloquist setup: sound at -4 deg (noisy), vision at +4 deg (crisp) mu_a, sigma_a = -4.0, 3.0 mu_v, sigma_v = 4.0, 1.0 tau_a, tau_v = 1.0 / (sigma_a ** 2), 1.0 / (sigma_v ** 2) w_a = tau_a / (tau_a + tau_v) w_v = tau_v / (tau_a + tau_v) mu_post = w_a * mu_a + w_v * mu_v sigma_post = jnp.sqrt(1.0 / (tau_a + tau_v)) print(f"Weights -> Vision: {w_v:.3f}, Audition: {w_a:.3f}") print(f"Posterior -> mean = {mu_post:+.2f} deg, std = {sigma_post:.2f} deg (sharper than both!)") # Sweep visual blur sigma_v to watch visual capture give way to audition blur_levels = jnp.linspace(0.5, 8.0, 100) tau_v_sweep = 1.0 / (blur_levels ** 2) visual_weights = tau_v_sweep / (tau_a + tau_v_sweep) perceived_pos = visual_weights * mu_v + (1.0 - visual_weights) * mu_a fig, axes = plt.subplots(1, 2, figsize=(11, 4)) grid = jnp.linspace(-12.0, 12.0, 300) axes[0].plot(grid, gaussian_pdf(grid, mu_a, sigma_a), color="#f39c12", linewidth=2, label="Auditory cue (noisy)") axes[0].plot(grid, gaussian_pdf(grid, mu_v, sigma_v), color="#3498db", linewidth=2, label="Visual cue (crisp)") axes[0].plot(grid, gaussian_pdf(grid, mu_post, sigma_post), color="#27ae60", linewidth=2.5, label="Bayesian posterior") axes[0].set_xlabel("Spatial position (degrees)") axes[0].set_ylabel("Probability density") axes[0].set_title("Ventriloquist Effect: Sharp Vision Captures Sound") axes[0].legend() axes[0].grid(alpha=0.3) axes[1].plot(blur_levels, perceived_pos, color="#9b59b6", linewidth=2.5) axes[1].axhline(mu_v, color="#3498db", linestyle="--", alpha=0.6, label="Visual position (+4 deg)") axes[1].axhline(mu_a, color="#f39c12", linestyle="--", alpha=0.6, label="Auditory position (-4 deg)") axes[1].set_xlabel("Visual blur sigma_V (degrees)") axes[1].set_ylabel("Perceived voice location (degrees)") axes[1].set_title("Blurring Vision Shifts Percept Back Toward Sound") axes[1].legend() axes[1].grid(alpha=0.3) plt.tight_layout() plt.show() -
Simulate Treisman's visual search paradigm (Feature Search versus Conjunction Search) across display sizes \(N \in \{4, 8, 12, 16, 24, 32\}\). Compare target-present and target-absent reaction times for a parallel pop-out detector versus a serial binding spotlight.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Items are represented by (colour, shape): # colour: 0 = red, 1 = green | shape: 0 = X, 1 = O # Target is always (red=0, X=0). def simulate_search(set_sizes, mode="feature", target_present=True, n_trials=200, seed=0): key = jax.random.PRNGKey(seed) mean_rts = [] base_rt = 350.0 # motor + perceptual baseline (ms) item_bind_ms = 25.0 # serial spotlight binding cost per item (ms) for N in set_sizes: rts = [] for _ in range(n_trials): key, k1, k2 = jax.random.split(key, 3) noise = float(jax.random.normal(k1, shape=(1,))[0]) * 20.0 if mode == "feature": # Parallel feature map detects red pop-out in O(1) time rt = base_rt + (0.0 if target_present else 40.0) + noise else: # Serial conjunction search checks items one by one until found if target_present: pos = int(jax.random.randint(k2, shape=(1,), minval=1, maxval=N + 1)[0]) rt = base_rt + item_bind_ms * pos + noise else: # Must inspect all N items to confirm absence! rt = base_rt + item_bind_ms * N + noise rts.append(rt) mean_rts.append(float(jnp.mean(jnp.array(rts)))) return jnp.array(mean_rts) set_sizes = [4, 8, 12, 16, 24, 32] rt_feat_pres = simulate_search(set_sizes, "feature", True, seed=1) rt_feat_abs = simulate_search(set_sizes, "feature", False, seed=2) rt_conj_pres = simulate_search(set_sizes, "conjunction", True, seed=3) rt_conj_abs = simulate_search(set_sizes, "conjunction", False, seed=4) plt.figure(figsize=(8, 4.5)) plt.plot(set_sizes, rt_feat_pres, "o-", color="#27ae60", linewidth=2, label="Feature search (present) ~ O(1)") plt.plot(set_sizes, rt_feat_abs, "o--", color="#27ae60", linewidth=1.6, alpha=0.7, label="Feature search (absent)") plt.plot(set_sizes, rt_conj_pres, "s-", color="#e74c3c", linewidth=2.2, label="Conjunction search (present) ~ N/2") plt.plot(set_sizes, rt_conj_abs, "s--", color="#9b59b6", linewidth=2.2, label="Conjunction search (absent) ~ N") plt.xlabel("Display set size (N items)") plt.ylabel("Mean reaction time (ms)") plt.title("Feature Integration Theory: Parallel Pop-Out vs Serial Binding") plt.legend() plt.grid(alpha=0.3) plt.show() slope_pres = float((rt_conj_pres[-1] - rt_conj_pres[0]) / (set_sizes[-1] - set_sizes[0])) slope_abs = float((rt_conj_abs[-1] - rt_conj_abs[0]) / (set_sizes[-1] - set_sizes[0])) print(f"Conjunction slope (present): {slope_pres:.1f} ms/item | (absent): {slope_abs:.1f} ms/item (~2:1 ratio!)") -
Compare Biased Competition (divisive normalisation with a top-down attentional gain) against Transformer Scaled Dot-Product Attention when a target stimulus competes with a brighter distractor, and use
jax.gradto measure how strongly top-down bias shifts the representation toward the target.import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Two stimuli in a shared receptive field: # Stimulus 0 (target): weaker bottom-up contrast (0.6) # Stimulus 1 (distractor): stronger bottom-up saliency (1.0) contrasts = jnp.array([0.6, 1.0]) sigma_norm = 0.25 # semi-saturation constant for divisive normalisation def biased_competition_response(top_down_gain): """Divisive normalisation: top-down bias multiplies target drive before competition.""" drives = jnp.array([top_down_gain * contrasts[0], contrasts[1]]) responses = drives / (sigma_norm + jnp.sum(drives)) return responses # Compare with Transformer scaled dot-product attention where query tilts toward target key keys = jnp.array([[1.0, 0.0], # target key [0.0, 1.0]]) # distractor key values = jnp.array([[1.0, 0.0], [0.0, 1.0]]) def transformer_target_weight(query_strength): # Query blends bottom-up saliency with top-down target preference q = jnp.array([query_strength * contrasts[0], contrasts[1]]) scores = jnp.dot(keys, q) / jnp.sqrt(2.0) weights = jax.nn.softmax(scores) return weights[0] gains = jnp.linspace(0.5, 5.0, 100) bc_target = jnp.array([biased_competition_response(g)[0] for g in gains]) bc_distract = jnp.array([biased_competition_response(g)[1] for g in gains]) tf_target = jnp.array([transformer_target_weight(g) for g in gains]) # Sensitivity of target representation to top-down gain at gain = 1.5 d_bc = jax.grad(lambda g: biased_competition_response(g)[0])(jnp.array(1.5)) d_tf = jax.grad(transformer_target_weight)(jnp.array(1.5)) print(f"Sensitivity at gain=1.5 -> Biased Competition: {float(d_bc):.3f}, Transformer Softmax: {float(d_tf):.3f}") plt.figure(figsize=(8.5, 4.5)) plt.plot(gains, bc_target, color="#27ae60", linewidth=2.3, label="Biased competition: target firing") plt.plot(gains, bc_distract, color="#e74c3c", linewidth=2.0, linestyle="--", label="Biased competition: distractor suppressed") plt.plot(gains, tf_target, color="#3498db", linewidth=2.2, label="Transformer softmax: target weight") plt.axvline(1.0 / 0.6, color="#666666", linestyle=":", label="Equal-drive crossover (gain = 1.67)") plt.xlabel("Top-down attentional gain on target") plt.ylabel("Normalised activation / attention weight") plt.title("Top-Down Bias Overcoming a Brighter Distractor") plt.legend() plt.grid(alpha=0.3) plt.show()