Skip to content

Foundations of Cognition

Cognitive science asks how biological and artificial minds turn raw sensory signals into internal representations, decisions, and intelligent action. This file introduces Marr's three levels of analysis, the major paradigms of cognitive science, classic cognitive architectures, psychophysics, Signal Detection Theory, and resource-rational decision-making, giving AI practitioners a principled vocabulary for reasoning about intelligence.

What Is Cognition?

  • Imagine crossing a busy London street in the rain. Photons hit your retinas and pressure waves strike your eardrums; within half a second, you recognise an oncoming double-decker bus, estimate its speed despite the glare, recall that wet tarmac lengthens braking distance, suppress the urge to sprint, and step back onto the kerb.

  • Cognition is the full chain of information-processing steps connecting sensation to action, spanning perception, attention, representation, memory, reasoning, learning, decision-making, and motor control.

  • Notice why cognitive science sits right next to artificial intelligence in this compendium. Chapters 01 to 10 built the mathematical and algorithmic machinery for vectors, matrices, calculus, statistics, probability, machine learning, language, vision, and speech. Cognitive science asks the complementary question of what computational problems intelligent agents are actually solving, and how finite biological minds solve them so effortlessly.

  • Many of the biggest breakthroughs in AI (neural networks, reinforcement learning, attention, working-memory buffers, experience replay, and Bayesian inference) were either directly inspired by cognitive science or rediscovered principles that cognitive scientists had been studying for decades.

Marr's Three Levels of Analysis

  • Suppose you walk into a shop and watch a cashier ring up your groceries on a cash register. If someone asks you "how does that machine work?", there are three completely different, and equally valid, ways to answer.

  • Neuroscientist and vision pioneer David Marr (1982) argued that any complex information-processing system can only be understood properly by analysing it at three distinct levels.

Marr's three levels of analysis comparing a cash register, human vision, and Transformer attention across computational, algorithmic, and implementational levels

  • 1. Computational level (the "what" and "why") asks what mathematical problem the system is solving, what mapping from inputs to outputs it implements, and why that mapping fits the environment.

    • For a cash register, the goal is computing the exact arithmetic sum of item prices (associative, commutative, with zero as the identity).
    • For human vision, the goal is inferring the 3D geometry, materials, and layout of a scene from ambiguous 2D retinal light patterns.
    • For Transformer attention (Chapter 07), the goal is dynamically routing relevant contextual information from past tokens to the current token based on semantic compatibility.
  • 2. Algorithmic / Representational level (the "how") specifies what representations (data structures) encode the inputs and outputs, and what step-by-step procedure transforms one into the other.

    • For a cash register, prices are represented in base-10 Arabic numerals (rather than Roman numerals, where addition is painful) and added column by column from right to left with carry.
    • For human vision, the visual system extracts local edges and blobs (Marr's primal sketch), infers surface depth and orientation (the 2.5D sketch), and assembles object-centred 3D models.
    • For Transformer attention, token embeddings are projected into query, key, and value vectors and combined via scaled dot-product attention \(\text{softmax}(QK^T / \sqrt{d_k}) V\).
  • 3. Implementational level (the "physical substrate") describes how those representations and algorithms are physically realised in hardware or biological wetware.

    • For a cash register, the substrate could be interlocking brass gears in a 1920s mechanical till, or CMOS logic gates on a silicon chip today.
    • For human vision, the substrate consists of photoreceptors in the retina, lateral geniculate nucleus relays, and spiking cortical neurons across areas V1 to V4.
    • For Transformer attention, the substrate is FP16/BF16 matrix multiplications tiled in GPU SRAM using FlashAttention kernels running on Tensor Cores.
  • A profound consequence of Marr's framework is multiple realisability. The same computational goal can be solved by many different algorithms, and the same algorithm can run on wildly different physical substrates. Knowing every synapse in a fly's brain (implementational) does not automatically tell you why it flies toward light (computational), just as knowing the laws of addition does not tell you whether a register uses brass gears or transistors.

  • Why do AI researchers need all three levels? Because debugging or innovating at the wrong level stalls progress.

    • If a model fails because its training objective is misspecified (for instance, next-token prediction without alignment to human preferences), tweaking CUDA kernels will not fix it. That is a computational problem.
    • If a model has the right objective but loses track of long-range dependencies, changing the architecture (for instance, from an RNN to a Transformer or state-space model) is an algorithmic fix.
    • If attention is mathematically right but hits a memory-bandwidth wall at long context lengths, FlashAttention keeps the exact same maths while reorganising SRAM reads, making it a pure implementational triumph.

Four Major Paradigms of Cognitive Science

  • Over the past seventy years, four grand research traditions have offered competing, and increasingly complementary, answers to what kind of computation the mind performs.

  • 1. Symbolic / Classical Cognitive Science (GOFAI) grew out of digital computers and formal logic. Allen Newell and Herbert Simon proposed the Physical Symbol System Hypothesis (1976), claiming that intelligence consists of manipulating discrete symbols according to explicit rules.

    • Its core strength is natural compositionality and systematicity. If you understand "Alice loves Bob" and know the rule for reversing subject and object, you immediately understand "Bob loves Alice" without needing ten thousand training examples.
    • Its core weakness is brittleness to noisy sensory inputs, difficulty scaling hand-written rules, and trouble with common-sense exceptions (known as the frame problem and the symbol grounding problem).
  • 2. Connectionism (Neural Networks / PDP), spearheaded by Rumelhart, McClelland, and Hinton in the 1980s, models cognition as Parallel Distributed Processing across networks of simple neuron-like units (the direct ancestor of Chapter 06 deep learning).

    • Its core strength is representing concepts as distributed vectors (Chapter 01) rather than brittle discrete tokens, giving automatic similarity generalisation, noise tolerance, graceful degradation, and learning straight from raw pixels or audio.
    • Its historical weakness is exact variable binding, out-of-distribution systematicity, and data efficiency, all of which remain active challenges in frontier LLMs.
  • 3. Probabilistic / Bayesian Cognition, championed by researchers such as Joshua Tenenbaum and Thomas Griffiths, works primarily at Marr's computational level. It treats the mind as an approximate Bayesian inference engine (Chapter 05) combining structured priors \(P(h)\) with noisy sensory likelihoods \(P(d \mid h)\) to infer the posterior \(P(h \mid d) \propto P(d \mid h) P(h)\).

    • Its strength is explaining how humans generalise a new word or physical concept from a single example (one-shot learning) while smoothly managing uncertainty.
    • Its main limitation is that exact Bayesian inference is computationally intractable for complex hypotheses, forcing the brain to rely on clever approximations such as sampling, amortised inference, and heuristics.
  • 4. Embodied and Enactive Cognition challenges the "brain in a vat" metaphor altogether. Think of catching a cricket ball. You do not solve a differential equation for parabolic drag in your head; you simply run at a speed that keeps the ball's optical trajectory linear on your retina.

    • Following James Gibson's theory of affordances (objects are perceived directly in terms of the actions they invite, so a chair affords sitting and a handle affords grasping), embodied cognition insists that perception, body mechanics, and environment form a tight closed loop. This perspective sits at the heart of modern robotics and embodied AI.
Paradigm Primary Representation Core Mechanism Signature Strength Classic Limitation
Symbolic (GOFAI) Discrete symbols & trees Logical rule application & search Exact compositionality & interpretability Brittle to noise; hand-crafted rules
Connectionist Continuous dense vectors Weighted sums, nonlinearities, backprop Pattern recognition & graceful degradation Data-hungry; weak strict variable binding
Probabilistic / Bayesian Probability distributions Posterior inference & causal models Few-shot learning & calibrated uncertainty Exact inference is often intractable
Embodied / Enactive Sensorimotor loops Continuous agent-environment coupling Real-time physical control & grounding Harder to explain abstract math or poetry
  • Modern AI increasingly synthesises all four perspectives, combining neural perception and generation (connectionist), structured tool use and code execution (symbolic), uncertainty-aware reasoning (Bayesian), and closed-loop physical interaction (embodied).

Mental Representations and Cognitive Architectures

  • Every paradigm relies on mental representations, internal states that stand in for things in the real world (or imaginary worlds) so the mind can compute over them offline. A mental representation might be symbolic (the proposition CAPITAL(France, Paris)), distributed (a dense embedding vector in \(\mathbb{R}^d\)), or analogue and map-like (a spatial layout you can mentally rotate; Shepard and Metzler famously showed that the time people take to judge whether two rotated 3D shapes match scales linearly with the angle of rotation).

  • A cognitive architecture specifies the fixed blueprint of a mind (its memory stores, processing modules, and control loop) across which any specific task knowledge runs. Two landmark architectures shaped both psychology and AI.

  • ACT-R (Adaptive Control of Thought, Rational, developed by John Anderson) models the human mind as a set of specialised modules (visual, motor, declarative memory, goal) communicating through small buffers coordinated by a central procedural system of IF-THEN production rules.

    • Declarative facts ("chunks") are not all equally accessible. Each chunk carries an activation level determined by how frequently and recently it has been used, plus spreading activation from current context, allowing ACT-R to predict exact human reaction times and error patterns in milliseconds.
  • Soar (State, Operator, And Result, developed by Laird, Newell, and Rosenbloom) models all cognition as search through problem spaces using operators. Whenever Soar hits an impasse (it does not know which operator to apply), it automatically creates a subgoal to resolve it. Once solved, a mechanism called chunking compiles the multi-step reasoning trace into a single fast rule for future use, a classic precursor to distilling slow chain-of-thought reasoning into fast intuition.

  • Pause and compare ACT-R and Soar to a modern LLM agent. The prompt and context window act like working-memory buffers, a vector database (RAG) acts like activation-weighted declarative memory, tool definitions act like motor and perceptual modules, and fine-tuned weights act like compiled procedural knowledge. The architectural ideas never went away; they were reborn in neural form.

Psychophysics and Mapping the Physical to the Mental

  • Before cognitive science even had computers, nineteenth-century scientists asked a deceptively simple question. If you double the physical intensity of a light, sound, or weight, does it feel twice as bright, loud, or heavy?

  • Try a quick thought experiment. Hold a single 10-gram coin in your palm; add a second 10-gram coin and you instantly feel the jump. Now carry a 10-kilogram backpack; drop that exact same 10-gram coin inside and you will feel nothing at all.

  • Weber's Law (1834) captures this ratio principle. The Just Noticeable Difference (JND), the smallest change \(\Delta I\) you can reliably detect, is a constant fraction of the baseline physical intensity \(I\).

\[\frac{\Delta I}{I} = k\]
  • Here \(I\) is the starting stimulus intensity, \(\Delta I\) is the detection threshold increment, and \(k\) is the Weber fraction (roughly \(0.02\) for lifted weights, \(0.08\) for brightness, and \(0.003\) for pitch frequency).

  • Gustav Fechner (1860) integrated Weber's law by assuming each JND corresponds to one equal unit step \(\Delta S\) in subjective sensation \(S\). Integrating \(dS = c \, dI / I\) from the absolute detection threshold \(I_0\) yields the Weber-Fechner Law.

\[S = k \ln\!\left(\frac{I}{I_0}\right)\]
  • Subjective perception grows logarithmically with physical energy. That is why human hearing spans twelve orders of magnitude of sound intensity and why Chapter 10 measures loudness in decibels (a logarithmic scale) and pitch on the logarithmic Mel scale, compressing vast physical dynamic ranges into a manageable neural firing range.

  • A century later, S. S. Stevens (1957) asked participants to assign numbers directly to perceived magnitudes and discovered that some sensations (like electric shock or pain) actually accelerate faster than physical intensity, which a logarithm can never represent. He proposed Stevens' Power Law.

\[S = a \, I^{b}\]
  • Here \(a\) is a unit-dependent scaling constant and the exponent \(b\) characterises the sensory modality.
    • When \(b < 1\) (compressive), as in brightness (\(b \approx 0.33\)) and loudness (\(b \approx 0.67\)), the brain packs enormous physical ranges into modest neural responses.
    • When \(b \approx 1\) (linear), as in perceived line length (\(b \approx 1.0\)), our visual ruler stays remarkably faithful.
    • When \(b > 1\) (expansive), as in electric shock (\(b \approx 3.5\)) or painful heat, small physical increases trigger urgent, amplified alarm signals so you pull your hand away before tissue burns.

Signal Detection Theory (SDT)

  • Picture a radiologist scanning a faint, grainy mammogram for an early tumour, or an air-traffic controller watching a noisy radar screen. Whenever you decide "is a signal really there, or is that just noise?", two completely different forces shape your answer.

    1. How sharp your eyes and equipment are, meaning how cleanly signal separates from noise.
    2. How cautious you choose to be, meaning how willing you are to raise a false alarm to avoid missing a real danger.
  • Classical psychophysics assumed a single fixed "threshold", which hopelessly tangled those two forces together. Signal Detection Theory (SDT), born in 1950s radar engineering and adopted across cognitive psychology and machine learning, separates them cleanly.

Signal Detection Theory showing overlapping Noise and Signal+Noise distributions separated by sensitivity d', decision criterion c, and the resulting ROC curve

  • Model the observer's noisy internal evidence on any trial as a single scalar \(x\).

    • When only Noise is present, \(x \sim \mathcal{N}(0, 1)\).
    • When Signal + Noise is present, \(x \sim \mathcal{N}(d', 1)\).
  • The observer picks a decision criterion (threshold) \(\tau\) and says "Yes, signal!" whenever \(x > \tau\), and "No, just noise" otherwise. This yields the classic \(2 \times 2\) outcome table (the exact counterpart of Type I and Type II errors in Chapter 04 hypothesis testing).

Signal Present Noise Only
Respond "Yes" Hit (\(H\)) False Alarm (\(F\), Type I error)
Respond "No" Miss (\(1 - H\), Type II error) Correct Rejection (\(1 - F\))
  • Using the inverse standard normal CDF \(z(\cdot) = \Phi^{-1}(\cdot)\), SDT extracts two independent, crystal-clear metrics from just the observed Hit rate \(H\) and False Alarm rate \(F\).
\[d' = z(H) - z(F)\]
\[c = -\frac{1}{2}\big[z(H) + z(F)\big]\]
  • Sensitivity \(d'\) ("d-prime") is the distance between the means of the Noise and Signal+Noise distributions measured in standard deviation units. If \(d' = 0\), the two bell curves sit directly on top of each other and the observer is guessing at chance. Higher \(d'\) means genuinely better perceptual discrimination.

  • Decision criterion \(c\) measures response bias relative to the neutral midpoint between the two curves.

    • When \(c = 0\), the observer is unbiased, with equal miss and false-alarm rates.
    • When \(c > 0\), the observer is conservative, needing strong evidence to say "Yes" (fewer false alarms, more misses).
    • When \(c < 0\), the observer is liberal, triggering "Yes" easily (catching almost every signal at the cost of more false alarms). A radiologist screening for cancer rationally uses a liberal criterion (\(c < 0\)) because a miss is far deadlier than a follow-up scan.
  • What happens if you keep perceptual skill \(d'\) fixed and sweep the criterion \(c\) from \(-\infty\) to \(+\infty\)? Plotting Hit Rate \(H\) on the y-axis against False Alarm Rate \(F\) on the x-axis traces out the Receiver Operating Characteristic (ROC) curve.

    • Moving \(c\) simply slides your operating point along the same ROC curve.
    • Increasing true sensitivity \(d'\) bows the entire curve upward toward the ideal top-left corner \((F=0, H=1)\).
    • That is why AUC-ROC (Chapter 06) is such a beloved metric in ML classification, because it evaluates a classifier's intrinsic separability \(d'\) across all possible decision thresholds.

Bounded Rationality and Resource-Rational Analysis

  • Classical economics once imagined Homo economicus, a mythical decision-maker who evaluates every possible option to infinite precision and picks the exact maximum of expected utility.

  • Try doing that in a real supermarket or over a chessboard. Chess has roughly \(10^{120}\) possible games; no human (and no supercomputer) can search the full tree before the clock runs out.

  • Herbert Simon (1955) replaced perfection with bounded rationality. Real minds operate under tight limits on time, working memory, and metabolic energy. Instead of optimising globally, humans satisfice, searching until they find an option that is "good enough" for their aspiration level by using fast heuristics that exploit the structure of the environment.

  • Modern cognitive science takes Simon's insight one step further with resource-rational analysis (Lieder & Griffiths, 2020). Rather than calling heuristics "irrational bugs", resource-rationality asks what the mathematically optimal cognitive algorithm is once every step of thinking costs time and energy.

  • Formally, an agent chooses an internal computation strategy (or meta-policy) \(\pi\) from its available algorithms \(\Pi\) to maximise expected decision utility minus the computational cost of running \(\pi\).

\[\pi^{*} = \arg\max_{\pi \in \Pi} \left( \mathbb{E}\big[U(\text{action}(\pi))\big] - \lambda \, \text{Cost}(\pi) \right)\]
  • Here \(U(\cdot)\) is the external reward or utility of the action chosen after thinking, \(\text{Cost}(\pi)\) is the time, memory, or energy spent computing, and \(\lambda > 0\) is the opportunity cost per unit of mental effort (high when a bus is hurtling toward you, low when choosing a holiday destination on a Sunday afternoon).

  • When thinking is expensive (\(\lambda\) is large) or the stakes are small, a quick heuristic beats slow deliberation, making fast intuition rationally optimal. Conversely, when the stakes are huge, spending extra compute pays off.

  • Notice the striking convergence with modern AI systems engineering. Test-time compute scaling, early-exit neural networks, speculative decoding, and quantisation are all AI implementations of resource-rationality, trading FLOPs and latency against accuracy to maximise net value per joule.

Take-Home

  • Marr's three levels (computational, algorithmic, implementational) keep you from confusing what problem an intelligent system solves with how it computes it or what hardware it runs on.
  • Four cognitive paradigms (symbolic, connectionist, Bayesian, embodied) highlight complementary facets of intelligence, and modern AI increasingly combines them rather than picking just one.
  • Psychophysics (Weber-Fechner and Stevens' power law) shows that minds compress or expand physical reality nonlinearly to match ecological needs, directly explaining decibels and Mel scales in speech AI.
  • Signal Detection Theory cleanly separates true perceptual sensitivity (\(d'\)) from decision bias (\(c\)), giving the exact mathematical foundation behind ROC curves and classifier thresholding.
  • Resource-rational analysis reframes human heuristics not as flaws, but as optimal solutions when computation itself has a cost, mirroring efficient AI inference and test-time compute budgets.

Coding Tasks (use CoLab or notebook)

  1. Compare the Weber-Fechner logarithmic law and Stevens' power law across three sensory modalities (brightness \(b=0.33\), line length \(b=1.0\), and electric shock \(b=2.0\)), and verify that Weber's ratio \(\Delta I / I\) stays constant across baseline weights.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Stimulus intensity range (normalised above threshold I0 = 1.0)
    I = jnp.linspace(1.0, 20.0, 200)
    I0 = 1.0
    
    # Weber-Fechner law: S = k * ln(I / I0)
    S_fechner = jnp.log(I / I0)
    S_fechner = S_fechner / jnp.max(S_fechner)
    
    # Stevens' power law: S = I^b (normalised to [0, 1] for visual comparison)
    exponents = {
        "Brightness (b = 0.33, compressive)": 0.33,
        "Line length (b = 1.00, linear)": 1.00,
        "Electric shock (b = 2.00, expansive)": 2.00,
    }
    
    plt.figure(figsize=(8, 4.5))
    plt.plot(I, S_fechner, "--", color="#333333", linewidth=2, label="Weber-Fechner (logarithmic)")
    colours = ["#3498db", "#27ae60", "#e74c3c"]
    for (name, b), col in zip(exponents.items(), colours):
        S = (I ** b - I0 ** b)
        S = S / jnp.max(S)
        plt.plot(I, S, color=col, linewidth=2.2, label=name)
    
    plt.xlabel("Physical stimulus intensity (I / I0)")
    plt.ylabel("Normalised perceived magnitude")
    plt.title("Psychophysical Scaling: Physical Intensity vs Subjective Sensation")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.show()
    
    # Verify Weber's law for lifted weights (Weber fraction k = 0.02)
    k_weight = 0.02
    baselines_g = jnp.array([50.0, 200.0, 1000.0, 5000.0])
    jnds_g = k_weight * baselines_g
    for base, jnd in zip(baselines_g, jnds_g):
        print(f"Baseline: {float(base):6.0f} g -> JND: {float(jnd):5.1f} g (ratio = {float(jnd/base):.2f})")
    

  2. Simulate a Signal Detection Theory observer across noisy and signal+noise trials, estimate sensitivity \(d'\) and criterion \(c\) empirically, and plot ROC curves for three perceptual sensitivities (\(d' \in \{0.6, 1.5, 2.5\}\)).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def normal_cdf(x):
        """Fast Abramowitz-Stegun approximation to standard normal CDF (Pyodide-safe)."""
        sign = jnp.where(x >= 0, 1.0, -1.0)
        z = jnp.abs(x) / jnp.sqrt(2.0)
        t = 1.0 / (1.0 + 0.3275911 * z)
        poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))))
        erf_approx = sign * (1.0 - poly * jnp.exp(-z * z))
        return 0.5 * (1.0 + erf_approx)
    
    def approx_inv_normal(p):
        """Invert normal_cdf via binary search on [-5, 5] for a scalar probability p."""
        lo, hi = -5.0, 5.0
        for _ in range(30):
            mid = 0.5 * (lo + hi)
            if float(normal_cdf(mid)) < p:
                lo = mid
            else:
                hi = mid
        return 0.5 * (lo + hi)
    
    # Simulate 10,000 Noise trials and 10,000 Signal+Noise trials
    key = jax.random.PRNGKey(42)
    k1, k2 = jax.random.split(key)
    true_dprime = 1.6
    true_tau = 0.5  # slightly liberal criterion (midpoint is 0.8)
    
    noise_samples = jax.random.normal(k1, shape=(10000,))
    signal_samples = jax.random.normal(k2, shape=(10000,)) + true_dprime
    
    hit_rate = float(jnp.mean(signal_samples > true_tau))
    fa_rate = float(jnp.mean(noise_samples > true_tau))
    
    est_dprime = approx_inv_normal(hit_rate) - approx_inv_normal(fa_rate)
    est_c = -0.5 * (approx_inv_normal(hit_rate) + approx_inv_normal(fa_rate))
    print(f"Hit rate = {hit_rate:.3f}, FA rate = {fa_rate:.3f}")
    print(f"Estimated d' = {est_dprime:.2f} (true {true_dprime:.2f}), criterion c = {est_c:.2f}")
    
    # Plot ROC curves for three d' values
    thresholds = jnp.linspace(-3.5, 5.5, 200)
    plt.figure(figsize=(6.5, 5.5))
    for dp, col in [(0.6, "#f39c12"), (1.5, "#27ae60"), (2.5, "#3498db")]:
        fa = 1.0 - normal_cdf(thresholds)
        hr = 1.0 - normal_cdf(thresholds - dp)
        plt.plot(fa, hr, color=col, linewidth=2.2, label=f"d' = {dp:.1f}")
    
    plt.plot([0, 1], [0, 1], "--", color="#999999", label="Chance (d' = 0)")
    plt.scatter([fa_rate], [hit_rate], color="#e74c3c", s=70, zorder=5, label=f"Simulated observer (c={est_c:.2f})")
    plt.xlabel("False Alarm Rate P(FA)")
    plt.ylabel("Hit Rate P(Hit)")
    plt.title("Signal Detection Theory: ROC Curves Across Sensitivity d'")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.show()
    

  3. Model a resource-rational agent deciding how many noisy mental samples \(n\) to collect before choosing between two actions whose true reward gap is \(\Delta = 0.4\) (observation noise \(\sigma = 1.0\)). Use both analytical calculation and jax.grad to find the optimal thinking budget \(n^*\) as the cost of time \(\lambda\) varies.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def normal_cdf(x):
        sign = jnp.where(x >= 0, 1.0, -1.0)
        z = jnp.abs(x) / jnp.sqrt(2.0)
        t = 1.0 / (1.0 + 0.3275911 * z)
        poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))))
        return 0.5 * (1.0 + sign * (1.0 - poly * jnp.exp(-z * z)))
    
    # Expected decision utility after n noisy samples (each N(delta, sigma^2)):
    # P(pick better option) = Phi(sqrt(n) * delta / sigma)
    delta = 0.4
    sigma = 1.0
    stake = 10.0  # reward difference between the good and bad choice
    
    def net_value(n, lam):
        p_correct = normal_cdf(jnp.sqrt(jnp.maximum(n, 1e-4)) * delta / sigma)
        expected_utility = stake * p_correct
        thinking_cost = lam * n
        return expected_utility - thinking_cost
    
    # Optimise thinking budget n via gradient ascent using jax.grad for three urgency levels
    n_grid = jnp.linspace(0.5, 45.0, 200)
    plt.figure(figsize=(8.5, 4.5))
    
    for lam, col, label in [
        (0.05, "#27ae60", "Low urgency (lambda = 0.05)"),
        (0.15, "#3498db", "Medium urgency (lambda = 0.15)"),
        (0.40, "#e74c3c", "High urgency (lambda = 0.40)"),
    ]:
        grad_fn = jax.grad(lambda x: net_value(x, lam))
        n_opt = jnp.array(5.0)
        for _ in range(150):
            n_opt = jnp.clip(n_opt + 2.0 * grad_fn(n_opt), 0.5, 45.0)
        vals = net_value(n_grid, lam)
        plt.plot(n_grid, vals, color=col, linewidth=2.2, label=f"{label} -> n* = {float(n_opt):.1f}")
        plt.scatter([float(n_opt)], [float(net_value(n_opt, lam))], color=col, s=60, zorder=5)
        print(f"{label:32s} | Optimal samples n* = {float(n_opt):5.1f} | Net value = {float(net_value(n_opt, lam)):.2f}")
    
    plt.xlabel("Mental samples drawn (compute budget n)")
    plt.ylabel("Resource-rational net value: E[U] - lambda * n")
    plt.title("Resource-Rationality: Thinking Longer Pays Off Only Up to a Point")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.show()