<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankur Saran on Medium]]></title>
        <description><![CDATA[Stories by Ankur Saran on Medium]]></description>
        <link>https://medium.com/@ankursaran_59645?source=rss-91fe21a2a8f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4Cy3-bAVpA1IeaeuO7JtFA.jpeg</url>
            <title>Stories by Ankur Saran on Medium</title>
            <link>https://medium.com/@ankursaran_59645?source=rss-91fe21a2a8f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:45:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankursaran_59645/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TECH DEBT! Are we far from it?]]></title>
            <link>https://medium.com/@ankursaran_59645/tech-debt-are-we-far-from-it-86b8d2215ca2?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b8d2215ca2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 02:23:56 GMT</pubDate>
            <atom:updated>2026-12-02T02:23:56.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4bzsH2uEloo8SMk594X6A.png" /></figure><p>Were you ever able to justify or sell the rationale for your tech debt? That used to be an evolving, never-ending loop!</p><p>What is happening to it now?</p><p>Consider a few examples from the industry:</p><p>#Airbnb: 3,500 test files migrated in 6 weeks. Estimate: 18 months.</p><p>#Amazon: Java 17 upgrades from 50 developer-days to a few hours.</p><p>#Google: an estimated 50% less time on code migrations.</p><p>To state the obvious, AI now finds debt (hotspots, dead code, dependencies), repays it (migrations as background jobs), and prevents it (review, tests, docs on every PR).</p><p>The 20% sprint tax for mechanical debt is fading fast and becoming obsolete.</p><p>What used to be “Can we afford to fix it?” has rapidly moved to “Can we verify the fix?”</p><p>But who owns the verification on various teams?</p><p>#AI hasn’t removed tech debt. It has made writing new code and fixing old code much quicker. What it hasn’t made quicker is understanding code: Knowing what the system does and why. That is where the debt now builds up.</p><p>More to follow!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b8d2215ca2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Which LLM is the best?” is the question I hear and read about lot and i feel it’s the wrong one.]]></title>
            <link>https://medium.com/@ankursaran_59645/which-llm-is-the-best-is-the-question-i-hear-and-read-about-lot-and-i-feel-its-the-wrong-one-43d230dd79a9?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d230dd79a9</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[ai-product-management]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 04:25:10 GMT</pubDate>
            <atom:updated>2026-11-30T04:25:10.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jvrse9zjO9vafZuc7m1fYA.png" /><figcaption>The LunchBox</figcaption></figure><p>“Which LLM is the best?” is the question I hear and read about lot and i feel it’s the wrong one.</p><p>Mumbai’s dabbawalas move around 200,000 lunches a day without ever picking a “best” runner.They pick the right hand for each leg of the journey and that’s how I think good AI systems should work.</p><p>Swipe through my post on LinkedIn to see why routing is the architecture.</p><p><a href="https://lnkd.in/p/eyAN_6Bt">https://lnkd.in/p/eyAN_6Bt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d230dd79a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Wrongness in AI]]></title>
            <link>https://medium.com/@ankursaran_59645/the-wrongness-in-ai-a838d10baf02?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a838d10baf02</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 04:14:58 GMT</pubDate>
            <atom:updated>2026-11-23T04:14:58.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4D3is84YC6tQ6hbUMqruA.png" /></figure><p>“Assume the AI will be wrong. Decide where that’s acceptable, catch it where it isn’t, make it cheap to fix everywhere and turn every correction into an improvement. Then expand autonomy only as fast as the evidence earns it.”</p><p>How is that for an AI System Design Principle!!</p><p>— — -</p><p>Your AI agent has a 12% error rate.</p><p>That’s the AI Evals Harness telling you about the accuracy of the output.</p><p>What will you do with that number?</p><p>B’coz in my opinion, that number is useless.But why? What to track instead?</p><p>Picture a surveillance agent that triages alerts. Leadership sees 12% wrong and asks the obvious question: “Should we switch to a better model?” What’s your response gonna be?</p><p>I would recommend classifying every failure by type-60% retrieval misses. It reasoned well over the wrong account hierarchy.25% silent omissions.</p><p>Correct answer, but it never mentioned the linked beneficial owner.15% fabrication. It made something up.</p><p>A better model fixes maybe 15% of that problem. The other 85% lives in your data pipeline and your output design i.e. the Overall Data Governance!</p><p>That’s a System Design for designing around wrong AI answers:</p><p>Classify the wrongness before you try to fix it.</p><p>I typically use the 8 failure types as depicted in the infographic.</p><p>1. Fabrication: invented facts. Fix with grounding and verification.</p><p>2. Retrieval miss: right logic, wrong context. Fix the retrieval, not the prompt.</p><p>3. Reasoning error: right facts, wrong conclusion. Move the logic into code.</p><p>4. Action error: wrong tool, wrong parameters. Fix the tool contracts.</p><p>5. Silent omission: what it left out mattered most. Use structured, complete outputs.</p><p>6. Miscalibration: wrong and confident. Make “I don’t know” a valid answer.</p><p>7. Policy breach: accurate but not allowed. Put guardrails outside the model.</p><p>8. Drift: quality decays after a change. Run regression evals on every release.</p><p>Then add severity on top.</p><p>Factually, 1 missed pattern outweighs a thousand mislabeled low-risk alerts. Raw accuracy treats them the same. The regulator won’t.</p><p>Error composition has to be the roadmap.</p><p>If your team can’t say what share of last week’s AI failures were retrieval versus reasoning, you don’t have a model problem. You have an observability problem.</p><p>Agree, or am I being too harsh?</p><p>So, before you switch to a bigger model, answer one question: What kind of wrong is your AI!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a838d10baf02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Neural Networks Learn Like Reality Observes: Wave-Particle Duality]]></title>
            <link>https://medium.com/@ankursaran_59645/why-neural-networks-learn-like-reality-observes-wave-particle-duality-e0e0e039088b?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0e0e039088b</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 03:32:34 GMT</pubDate>
            <atom:updated>2026-10-26T03:32:34.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Article 3 of “Quantum Consciousness in AI Architecture: From Physics to Transcendence”</h3><p>Recommended pre-read: <a href="https://medium.com/@ankursaran_59645/you-are-not-binary-superposition-intuition-and-the-architecture-of-thought-d16b9d05183d?sharedUserId=ankursaran_59645">Article 1</a> and <a href="https://medium.com/@ankursaran_59645/when-information-becomes-non-local-7b7b7a9221a8?sharedUserId=ankursaran_59645">Article 2</a> of this series</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWLVY9_gylAZai3_YQlCwA.png" /><figcaption>IC: G-GEMINI | The super-position</figcaption></figure><h3>The Expectation Experiment</h3><p>A capable engineer is told, offhand, that the assessment she’s about to take is one most people in her role struggle with. She takes it and underperforms. Another engineer with same skills, same preparation is told the assessment is a routine diagnostic, nothing to worry about. He does fine.</p><p>Nothing about their ability changed. The task didn’t change. What changed was the frame in which the performance was <em>observed</em> and the frame reached backward into the performance itself.</p><p>This effect is real and I am sure most of us have encountered it though I want to be careful about how real, because the psychology here has had a hard decade. The classic demonstrations Rosenthal and Jacobson’s <em>Pygmalion in the Classroom</em>, where teachers told certain students were “late bloomers” saw those students improve and Steele and Aronson’s stereotype threat experiments have been enormously influential and have also run into serious replication problems. Effect sizes shrink under pre-registration some findings don’t hold.</p><p>The honest summary is that Expectation effects on performance are real but smaller, noisier and more context-dependent than the popular retellings suggest.</p><p>Let’s Keep the phenomenon, lose the overclaim. Something genuinely does happen when an observation is set up one way rather than another. And the question underneath it is the one this article is about:</p><p><strong>Is there such a thing as a neutral observation, a measurement that simply reveals what was already there without participating in what it finds?</strong></p><p>Quantum mechanics answered that question in the most uncomfortable possible way about a century ago. Machine learning quietly answered it again, in a different vocabulary and most practitioners haven’t noticed that it’s the same answer. The connection isn’t that your network is secretly quantum. It’s that <strong>both are systems where the apparatus you used to extract an answer is part of what determines the answer</strong> and in ML, unlike in physics, you <em>chose</em> the apparatus and can change it.</p><h3>The registers, once more!</h3><p>As in Articles <a href="https://medium.com/@ankursaran_59645/you-are-not-binary-superposition-intuition-and-the-architecture-of-thought-d16b9d05183d?sharedUserId=ankursaran_59645">1</a> and <a href="https://medium.com/@ankursaran_59645/when-information-becomes-non-local-7b7b7a9221a8?sharedUserId=ankursaran_59645">2</a>:</p><ol><li><strong>Literal physics</strong> real quantum mechanics. Wave-particle duality, the double slit, the measurement problem. Established and strange.</li><li><strong>Mathematical structure</strong> the formalism. This article contains the most substantive register-2 claim of the series so far: a real, precise mathematical relationship between the equation governing quantum evolution and the equation governing gradient descent. Not a vibe. A derivation.</li><li><strong>Interpretive metaphor</strong> observation shaping outcome, in human expectation and in AI deployment. Useful; not physics.</li></ol><p>And one explicit correction to the premise some readers may arrive with: <strong>Neural Networks are not Quantum Systems and do not exhibit quantum phenomena.</strong> Their parameters are definite floating-point numbers, not superposed states. There is no phase, no amplitude, no interference in the physical sense, no Born rule. Anyone who tells you a transformer “is quantum” is wrong. What follows is more interesting than that claim, and it has the advantage of being true.</p><h3>Wave-Particle Duality, Explained Properly</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q0W4Htukd6-pHKKB.png" /><figcaption>IC: G-Gemini | The passing light</figcaption></figure><p>Going by the modern history, in 1801 Thomas Young passed light through two narrow slits and found a pattern of bright and dark bands on the screen behind. That’s an interference pattern the signature of waves. Where two crests meet, they reinforce; where crest meets trough, they cancel.</p><p>Light, verdict: WAVE.</p><p>Then in 1905 Einstein explained the photoelectric effect by treating light as discrete packets of energy, and that’s the work he actually got the Nobel for.</p><p>Light, verdict: PARTICLE.</p><p>The experiment that makes this genuinely disturbing is the one where you send the particles through <strong>one at a time.</strong> Fire single electrons at a double slit, hours apart if you like and each one arrives at the screen as a single localized dot unmistakably a particle. But let the dots accumulate and they build up, 1 by 1, into an interference pattern. Each individual electron behaved as though it passed through both slits and interfered with itself.</p><p>Now add the detector. Put an instrument at the slits that determines which one each electron goes through. The interference pattern vanishes. You get two plain bands exactly what you’d expect from particles. Remove the detector and interference returns.</p><p>The wave behavior survives only as long as there is no <em>which-path information</em> available in the universe. This has been pushed to beautiful extremes: in <strong>quantum eraser</strong> experiments (Kim and colleagues, 1999, among others) which-path information is recorded and then destroyed and the interference pattern reappears in the correlated data. In <strong>delayed-choice</strong> versions, the decision about whether to record path information is made after the particle has already passed the slits.</p><h3>3 corrections that keep this honest</h3><p>This is where popularity goes badly wrong, so let me be explicit because the credibility of everything after this depends on it.</p><p><strong>“Observation” means physical interaction, not a conscious observer.</strong> The detector at the slit is a piece of equipment. It destroys interference because it physically couples to the electron and entangles with it, leaking which-path information into the environment. A camera with nobody watching the feed does exactly the same thing. The idea that human consciousness collapses the wave function is a minority philosophical position, not a result and it’s the single most abused claim in all of popular quantum writing. This series does not rely on it anywhere.</p><p><strong>“Measurement creates reality” is interpretation dependent.</strong> The mathematics of quantum mechanics is undisputed and fantastically well-confirmed. What it <em>means</em> is not. In the <strong>Copenhagen</strong> interpretation, measurement genuinely collapses the wave function and it’s meaningless to ask what the value was before. In <strong>many-worlds</strong>, nothing collapses, the observer simply becomes entangled with every outcome, each in its own branch. In <strong>decoherence</strong> accounts, apparent collapse is the rapid, irreversible leaking of coherence into the environment no special measurement axiom required. These predict the same experimental results. For this article I will use the <strong>decoherence-informed Copenhagen</strong> view collapse as effective, environment-driven, requiring no consciousness and flag where interpretation matters. Picking one and saying so is what distinguishes rigor from handwaving.</p><p><strong>Bell’s theorem (</strong><a href="https://medium.com/@ankursaran_59645/when-information-becomes-non-local-7b7b7a9221a8?sharedUserId=ankursaran_59645"><strong>Article 2</strong></a><strong>) does not prove measurement creates reality.</strong> It proves no <em>local hidden-variable</em> theory can reproduce the observed correlations. That’s a narrower and sharper claim. Don’t let the two blur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMxKmZETy7ap1ocr.png" /><figcaption>IC: G-Gemini | The power to observe</figcaption></figure><h3>So, what actually transfers??</h3><p>Strip away the metaphysics and what’s left is a structural fact of enormous practical use:</p><p><strong>The system has a richer description than any single measurement can return and the choice of measurement determines which part of that description you get.</strong></p><p>Set up the apparatus to ask “which slit?” and you get particle behavior.</p><p>Set it up to ask “what’s the interference pattern?” and you get wave behavior.</p><p>Both answers are correct. Neither is complete. There is no apparatus that gives you both at once.</p><p>Hold that sentence. It’s about to describe your model.</p><h3>What Training Actually Is (and the Equation missing the mentions it is worth)</h3><p>Here’s where I earn the physics.</p><h3>The naive version and why it’s probably wrong</h3><p>A tempting story: during training, network parameters “exist in superposition” across the loss landscape and optimization collapses them to final values.</p><p>This is false and an architect will spot it instantly. At every step of training, every parameter has one definite value. There’s no superposition, no amplitude, no phase. Nothing is in two states at once. If the analogy needs that, the analogy is dead.</p><p>But there’s a real relationship and it’s considerably more interesting.</p><h3>Gradient flow is a diffusion equation</h3><p>Take gradient descent to its continuous limit (infinitesimal learning rate) and you get <strong>gradient flow</strong>:</p><pre>dθ/dt = -∇L(θ)</pre><p>Parameters move downhill on the loss surface. First-order, dissipative, monotonically decreasing no oscillation, no conserved energy. Now add the fact that we use <em>stochastic</em> gradient descent: each step carries noise from minibatch sampling. The continuous limit becomes a stochastic differential equation (Langevin dynamics) and the probability distribution over parameters, p (θ, t), evolves according to a <strong>Fokker–Planck equation</strong> a diffusion equation. The density spreads, drifts downhill and settles into regions of low loss.</p><p>So training <em>is</em> governed by a partial differential equation describing a spreading, evolving distribution. That part of the brief’s intuition is correct. But it’s a <strong>diffusion</strong> equation, not a wave equation. Diffusion smooths and decays; waves oscillate and propagate. These are mathematically different animals, and conflating them is a tell.</p><h3>And here is the bridge</h3><p>Write the Schrödinger equation:</p><pre>iħ ∂ψ/∂t = Ĥ</pre><p>And the heat/diffusion equation:</p><pre>∂p/∂t = D ∇²p</pre><p>They look like relatives and they are but the i makes all the difference. It’s what turns decay into oscillation. Now perform the substitution physicists call <strong>Wick rotation</strong>: replace time t with imaginary time τ = it. The i cancels, and the Schrödinger equation <em>becomes</em> a diffusion equation.</p><p>This isn’t a cute observation. It’s a working tool. <strong>Imaginary-time evolution is how quantum Monte Carlo finds ground states.</strong> Evolve a quantum system in imaginary time and the excited-state components decay exponentially faster than the ground state, so the system relaxes to its lowest-energy configuration. Diffusion Monte Carlo is built on exactly this.</p><p>Now look at what training does. Gradient descent relaxes a system toward the minimum of an energy function the loss. Imaginary-time Schrödinger evolution relaxes a system toward the minimum of an energy function the Hamiltonian’s ground state. <strong>These are the same mathematical operation.</strong></p><p>So the precise, defensible statement and it’s a strong one:</p><blockquote><strong><em>Training is not wave evolution.</em></strong></blockquote><blockquote><strong><em>It is wave evolution’s imaginary-time counterpart: The same equation with oscillation replaced by decay. Quantum systems explore, gradient descent relaxes. One </em></strong><em>i</em><strong><em> separates them.</em></strong></blockquote><p>That’s why training converges instead of ringing forever. The dissipation is structural.</p><h3>Momentum restores the oscillation</h3><p>And here’s the satisfying corollary. Add momentum heavy-ball SGD and the dynamics become second order:</p><pre>m·θ̈ + γ·θ̇ + ∇L(θ) = 0</pre><p>That’s a <strong>damped harmonic oscillator.</strong> You’ve reintroduced the second time-derivative that makes wave equations wave-like. And the empirical behavior matches the physics exactly: momentum methods <em>overshoot</em> minima, <em>oscillate</em> across the walls of narrow ravines, and need damping (the γ term) to settle. Every practitioner who has watched a loss curve bounce has watched an underdamped oscillator.</p><p>So, within a single optimizer family you can move between regimes: plain SGD is diffusive relaxation; momentum SGD is damped wave propagation. Tuning momentum is tuning how wave-like your optimization is. That’s not metaphor it’s the ODE.</p><h3>Where there is literal interference??</h3><p>Real-valued networks have no phase, so “activations interfere like waves” is generally wrong. But there’s a genuine exception worth knowing, because it’s one of the most striking results in mechanistic interpretability.</p><p>When small transformers are trained on modular arithmetic, they don’t learn a lookup table. Neel Nanda and colleagues showed (in the work on <em>grokking</em>) that these networks converge on a <strong>Fourier-based algorithm</strong>: they represent inputs as sines and cosines at particular frequencies, multiply them through trigonometric identities, and read off the answer from constructive and destructive combination of those components. That is literal interference of periodic functions, discovered by gradient descent because it’s an efficient solution not because anything quantum is happening. Fourier structure is the natural language of periodic problems, in physics and in networks alike.</p><h3>3 mechanisms, correctly labeled</h3><p><strong>Ensembles</strong> work through <strong>variance reduction</strong>, not constructive interference. Average several models with uncorrelated errors and the errors partially cancel while the signal reinforces the bias–variance decomposition, not wave superposition. The structural rhyme (combining multiple solutions into a better one) is real; the mechanism is statistics.</p><p><strong>Dropout</strong> is noise injection and implicit ensembling randomly zeroing units forces redundant representations and approximates averaging over an exponential family of subnetworks. Calling it “decoherence” is a reasonable register-2 gloss (environmental noise destroying delicate structure), as long as nobody thinks a quantum state is being destroyed.</p><p><strong>Batch normalization</strong> stabilizes the distribution of activations between layers. The deeper point for this article isn’t what it does during training; it’s that <strong>it behaves differently at training time and at inference time</strong> and we’re about to see why that matters enormously.</p><h3>Inference as Measurement</h3><p>Training produces a distribution. Inference returns a value. That transition is the closest thing in machine learning to a measurement and the analogy is tight enough to be genuinely useful.</p><h3>The output is a distribution before it is an answer</h3><p>A language model’s forward pass ends in a vector of logits over the vocabulary, which a softmax turns into a probability distribution. That distribution is the model’s full state of belief about the next token the richest description available.</p><p>Then you take <em>one token</em>.</p><p>Everything that distinguishes a good generation system from a bad one happens in that step, and the step is a choice of measurement apparatus.</p><p>A note on precision, since this is where analogies get sloppy: SoftMax is exp(logit)/Σexp(logit) the Born rule is |ψ|².</p><p>Both map an unnormalized state to probabilities, and both make the normalization step meaningful but they are different functions and SoftMax is not the Born rule. The shared structure is <em>state → distribution → single sampled outcome</em> not the formula.</p><h3>Decoding strategies as apparatus</h3><p><strong>Greedy decoding</strong> takes the argmax. Maximum-precision measurement, zero exploration it returns the single most probable continuation and discards the shape of the distribution entirely. Deterministic, safe, and prone to degenerate repetition, because locally optimal tokens compound into globally dull text.</p><p><strong>Beam search</strong> keeps k candidate sequences alive, extends each, and prunes. This is the closest thing to <em>deferred</em> measurement: partial resolution, multiple hypotheses maintained through time, collapse postponed until the end. It’s excellent for tasks with a single correct answer (translation, structured extraction) and notoriously flat for open-ended generation keeping only high-probability paths strips out exactly the surprise that makes text feel alive.</p><p><strong>Temperature sampling</strong> rescales the logits before sampling, controlling how much of the distribution survives into the draw. We covered this in Article 1; here’s the refinement: temperature isn’t noise, it’s <strong>measurement resolution.</strong> Low temperature is a sharp instrument that always reports the peak. High temperature is a blurrier instrument that reports the distribution’s shape, including its tails. Top-k and nucleus (top-p) sampling are apparatus refinements truncate the tail, then sample which is why they beat both greedy and pure sampling in practice.</p><p>The point that generalizes: <strong>the model is the same; the output is not.</strong> Change the decoding strategy and you get different text from identical weights and identical input. Nothing about the model’s “knowledge” changed. The measurement changed.</p><p>That’s the register-2 payload of this article: <em>the apparatus participates in the result.</em></p><h3>The genuine observer effect in deployment</h3><p>Now the part that isn’t analogy at all and that every ML engineer has hit:</p><p><strong>Dropout is on during training and off at inference.</strong> The network you deploy is literally not the network you trained it’s the full, un-dropped network, with activations rescaled to compensate.</p><p><strong>Batch normalization uses batch statistics during training and running averages at inference.</strong> Same weights, different normalization, different outputs. The number of production incidents caused by a model left in train() mode is not small.</p><p>These are real, mechanical, well-documented train/test discrepancies baked into standard architectures. The framing the physics gives us is a good one: <strong>You are measuring the system with a different apparatus than the one you calibrated it with, and you should expect the reading to differ.</strong></p><p>That’s not mysticism. It’s model.eval().</p><h3>When the Apparatus Is the Problem</h3><p>Scale this up and you get most of the hard problems in deployed ML.</p><p><strong>Distribution shift</strong> is the measurement conditions changing underneath you. The model learned a mapping on one input distribution and is being queried on another. Nothing about the weights decayed; the world moved. Monitoring input distributions rather than only output metrics is the practical response — watch the apparatus, not just the reading.</p><p><strong>Adversarial examples</strong> deserve a correction from the brief. They do not work by “exploiting wave structure.” The dominant explanation (Goodfellow, Shlens and Szegedy) is nearly the opposite and more unsettling: networks are <em>too linear</em> in high-dimensional space. Many tiny coordinated perturbations, each individually negligible, sum along a gradient direction into a large change in the logits. A panda becomes a gibbon with 99% confidence under a perturbation invisible to you. Subsequent work (Ilyas and colleagues) argues these perturbations often latch onto genuinely predictive but non-robust features the model is reading real signal that humans simply don’t use. The honest frame: an adversarial example is <strong>an apparatus deliberately built to produce a misleading reading</strong>, which is precisely what makes it a measurement problem rather than a bug.</p><p><strong>Confirmation bias in evaluation</strong> is where the human enters the loop. You believe the new model is better. You inspect outputs. You find examples that confirm it, because you chose which prompts to run and which outputs to scrutinize, and you stop looking when the story coheres. The defense is the same as in physics: <strong>fix the apparatus before you take the reading.</strong> Pre-register the eval set, define the metric before you see results, hold out data you don’t look at. Not because you’re dishonest because selective observation is the default behavior of an interested mind.</p><h3>Performativity: Where the model stops predicting and starts causing!!</h3><p>The strongest version of this argument isn’t an analogy at all. It’s a formal concept in ML and it’s the anchor I’d build Section 5 on.</p><p><strong>Performative prediction</strong> (Perdomo, Zrnic, Mendler-Dünner and Hardt, 2020) names the situation where deploying a model <em>changes the distribution it was trying to predict.</em> A credit model that denies loans in a neighborhood changes that neighborhood’s economic trajectory. A predictive policing model that sends patrols to a district generates more recorded crime there, confirming itself. A recommender that shows you a genre teaches you to prefer it, then observes the preference it manufactured and calls it discovery.</p><p>This is a real research area with real mathematics the fixed point you converge to is not the one you’d get from passive prediction and it’s the rigorous core of the “AI creates reality” claim. You don’t need quantum mechanics for it. You need to notice that in a feedback loop, <strong>the measurement is also an intervention.</strong></p><p>Which is, in fairness, exactly what the physics has been saying all along.</p><h3>Designing the Apparatus</h3><p>If the apparatus shapes the result, then apparatus design is the real work. In ML, every one of these is a choice someone makes, usually without noticing:</p><p><strong>The Loss function</strong> declares what counts as being right. Optimize engagement and you’ll get engagement, including the kind nobody wanted. The loss is not a description of the goal it’s a <em>definition</em> of it, and the model will satisfy the definition rather than the intent.</p><p><strong>The label schema</strong> carves the world into categories. Every taxonomy is a decision about what distinctions matter and what differences are invisible. The model cannot see a distinction your labels don’t make.</p><p><strong>The training distribution</strong> determines what “normal” means. Bias in data is best understood not as contamination of an otherwise objective process but as the <strong>calibration of the instrument.</strong> An instrument calibrated on one population reads reliably on that population and misleads elsewhere and gives no warning that it’s doing so.</p><p><strong>The evaluation metric</strong> decides what success looks like, which decides what gets shipped, which decides what the next model is trained to imitate.</p><p>So, Is “objective AI” possible? Not in the sense of a system with no viewpoint. Every one of those four choices encodes a position, and there is no neutral default declining to choose just means inheriting someone else’s. But this is where I’d resist the fashionable despair, because the honest conclusion isn’t that objectivity is a lie, it’s the more demanding one: <strong>Objectivity isn’t a property you can have, it’s a practice you perform.</strong> You state the apparatus. You publish the loss, the labels, the data provenance, the metric. You let others measure with a different instrument and compare. That’s exactly how experimental physics handles an observer-dependent world, and it works not by escaping the apparatus, but by making it explicit enough to argue about.</p><p>Which is the empowering version of this whole article, and the one I’d want a team to take away. Physicists are stuck with their measurement problem. <strong>You chose yours, and you can change it.</strong> Reframe the loss, rebuild the dataset, redefine the metric, change the decoding strategy and a different reality comes out of the same model. That’s not a limitation of machine learning. It’s the only real leverage anyone has over it.</p><h3>Conclusion: Where the Analogy Ends and What Survives~</h3><p>Let me close by being explicit about the boundary, since this article pressed harder on the physics than either of the previous two.</p><p><strong>What is literally true:</strong> The double-slit experiment, measurement-dependent outcomes, and the interpretive openness of quantum mechanics all real, all established, none requiring a conscious observer. The mathematical relationship between the Schrödinger equation and diffusion equations under Wick rotation real, and the working basis of quantum Monte Carlo. The fact that gradient flow is a diffusion process and momentum SGD is a damped oscillator real, and derivable from the update rules. Train/inference divergence from dropout and batch norm real and mechanical. Performative prediction real, formalized, peer reviewed.</p><p><strong>What is structural analogy:</strong> Inference as measurement. Decoding strategies as apparatus. Dropout as decoherence. These are genuine shape-matches that will improve how you reason about systems, and they are not statements about physics occurring inside a GPU.</p><p><strong>What is false, and what I declined to write:</strong> That neural networks are quantum, exhibit quantum phenomena, or hold parameters in superposition. They don’t. The truthful version is stronger that two very different systems independently ran into the same deep constraint, <em>the apparatus participates in the result</em> and arrived at structurally similar mathematics for dealing with it.</p><p>So, the thesis stated carefully: A trained network holds a rich distributional description of its problem. Any single inference returns one value drawn through one apparatus. The distribution is as real as the value and if you only ever look through one instrument, you’ll mistake its reading for the whole of what your model knows.</p><p>There’s a question left hanging, and it’s the one that governs everything built on top of these three articles. Quantum superposition and entanglement are real but <em>fragile</em> they survive only in isolation and the universe is not an isolating place. The interference pattern vanishes the moment which-path information leaks out. Why? What is the actual mechanism by which possibility becomes actuality, coherence becomes classicality, and the strange quantum world we’ve been describing produces the stubbornly definite one we live in?</p><p>That mechanism is <strong>De-Coherence</strong> and it’s the most practically important concept in this entire series, because it governs not just qubits but teams, memory, data platforms and every system that has to stay coherent while in contact with a noisy world.</p><h3>References and further reading</h3><ul><li>Young, T. (1804); Einstein, A. (1905) — wave and particle evidence for light.</li><li>Kim, Y.-H. et al. (1999). <em>Delayed “choice” quantum eraser.</em> PRL.</li><li>Zurek, W. H. (2003). <em>Decoherence, einselection, and the quantum origins of the classical.</em> Rev. Mod. Phys. — The decoherence account of apparent collapse.</li><li>Rosenthal, R. &amp; Jacobson, L. (1968). <em>Pygmalion in the Classroom</em>; Steele, C. &amp; Aronson, J. (1995) on stereotype threat — with the replication literature as essential counterweight.</li><li>Risken, H. <em>The Fokker–Planck Equation.</em> — SGD’s continuous limit.</li><li>Foulkes, W. M. C. et al. (2001). <em>Quantum Monte Carlo simulations of solids.</em> Rev. Mod. Phys. Imaginary-time projection to ground states.</li><li>Polyak, B. T. (1964); Sutskever, I. et al. (2013) Momentum as damped oscillator dynamics.</li><li>Nanda, N. et al. (2023). <em>Progress measures for grokking via mechanistic interpretability.</em> ICLR. Fourier algorithms learned by gradient descent.</li><li>Srivastava, N. et al. (2014). <em>Dropout</em>; Ioffe, S. &amp; Szegedy, C. (2015). <em>Batch Normalization.</em></li><li>Goodfellow, I., Shlens, J. &amp; Szegedy, C. (2015). <em>Explaining and harnessing adversarial examples</em>; Ilyas, A. et al. (2019). <em>Adversarial examples are not bugs, they are features.</em></li><li>Holtzman, A. et al. (2020). <em>The curious case of neural text degeneration.</em> Nucleus sampling; why high-probability decoding fails.</li><li>Perdomo, J., Zrnic, T., Mendler-Dünner, C. &amp; Hardt, M. (2020). <em>Performative prediction.</em> ICML.</li></ul><p><em>As in Articles 1 and 2: the physics is presented as established where established and interpretation-dependent where contested; the parallels to neural networks are mathematical relationships where stated as such, and structural analogies otherwise. No claim is made that neural networks are quantum systems.</em></p><p><em>Ankur Saran · AI Product Leader | AI First Builder</em></p><p>HAPPY READING to all of you!</p><p>Read, Learn, Experiment, Implement, Share, Express!</p><p>👉 I write about <a href="https://www.linkedin.com/in/ankur-saran/">Data</a>, <a href="https://www.linkedin.com/in/ankur-saran/">AI Strategy</a> and <a href="https://www.linkedin.com/in/ankur-saran/">Product Leadership</a> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</p><p>Connect with me on LinkedIn <a href="https://www.linkedin.com/in/ankur-saran/"><em>Ankur Saran | LinkedIn</em></a></p><p>Follow my SUBSTACK Channel <a href="https://ankursaran.substack.com/"><em>Ankur Saran</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0e0e039088b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who Is Allowed to See the Future?]]></title>
            <link>https://medium.com/@ankursaran_59645/who-is-allowed-to-see-the-future-7f836498d077?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f836498d077</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 03:59:27 GMT</pubDate>
            <atom:updated>2026-10-23T04:05:45.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jwxz0a8MTL6EZCQBcIkww.png" /><figcaption>The Casual Masking paradigm</figcaption></figure><h3>The surveillance model that was too good to be real!</h3><p>Every AI system makes one design decision before any other: at each moment, what is it allowed to see? Get it wrong and the model can look brilliant in testing and fail on day one in production.</p><p>Here is a composite story, assembled from patterns that come up again and again.</p><p>A bank’s surveillance team builds a model to catch spoofing. Spoofing means placing large orders you never intend to fill, to push the price, then cancelling them. The team trains a sequence model on two years of order-book events, each order’s full life cycle from placement to cancellation.</p><p>The definition itself points at the future. <a href="https://news.law.fordham.edu/jcfl/wp-content/uploads/sites/5/2017/10/MSar-Note.pdf">US law, through the anti-spoofing provision Dodd-Frank added to the Commodity Exchange Act, describes spoofing as bidding or offering with the intent to cancel before execution</a>. Intent is judged now, the cancellation happens later.</p><p>The back test is spectacular: 98% precision, alerts on almost every known case. Compliance signs off and the model goes live.</p><p>In week one it barely raises an alert.</p><p>The post-mortem takes a day. The model had learned spoofing from <em>complete</em> order histories. The single strongest signal for spoofing is that the order gets cancelled, and in the training data that cancellation was always visible. In production, an alert must fire while the order is still resting on the book. The cancellation has not happened yet.</p><blockquote>The model was never detecting intent. It was reading the end of the story.</blockquote><p>In transformer language, the team had used <strong>bidirectional attention</strong> on a problem that required <strong>causal attention</strong>. Every token could see every other token, including the future. This article explains that one design decision from first principles: what causal masking is, what goes wrong without it, the alternatives, and why it matters for the agentic systems we are all building now.</p><p>It is built around a small lab you can run yourself: about 500 lines of plain NumPy, with every number in this article coming from it.</p><h3>Causal masking in one picture</h3><p>A causal mask stops each token from attending to any token after it. It is a lower-triangular matrix applied inside every attention layer, and it is what makes a model honest about time.</p><p>Inside a transformer, each token builds its representation by taking a weighted mix of the other tokens. The weights come from a SoftMax over attention scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*JZhVOuFW2oSf_h4UFjmSPw.png" /></figure><p>Setting a score to minus infinity makes its softmax weight exactly zero. Token <em>i</em> can then only draw on tokens 1 to <em>i</em>. Here is the arithmetic on four tokens of an order, &lt;s&gt; BUY INFY 100, from the lab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*awwADPwMppWcDSib.png" /></figure><p>Each row sums to 1 and every cell above the diagonal is exactly zero.</p><p>Remove the mask and the same scores give a very different row for BUY: it sends <strong>60% of its attention to “100”</strong>, a quantity that has not been typed yet.</p><p>Three masks cover most of what you will meet in practice:</p><ul><li><strong>Causal</strong> (lower triangle): GPT, Claude, Llama and almost every generative LLM.</li><li><strong>Bidirectional</strong> (full matrix): BERT-style encoders, embedding and reranking models.</li><li><strong>Prefix-LM</strong> (a full block for the prompt, causal after it): T5/UL2 variants, GLM, some vision-language models.</li></ul><p>One naming trap: causal masking belongs to <strong>decoders</strong>. Encoders are bidirectional by design. When people say “masking” about BERT they usually mean something else: hiding input tokens as a training puzzle, which we will meet as infilling.</p><h3>The lab: a tiny world of order events</h3><p>The lab trains small one-layer transformers on a toy “language” in which every sentence is one order’s life-cycle. Because we wrote the rules, we know the exact right answer to every question we ask the models.</p><p>Every sequence is 8 tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*Y6xfmG0Rj7BF0JRd.png" /></figure><p>The rules of this world:</p><ul><li>SIDE, TICKER and QTY are random.</li><li>QTY 10 or 50 is always acknowledged. QTY 500 is always rejected (a risk limit). QTY 100 is a coin flip.</li><li>ACK always leads to FILL; REJECT always leads to CANCEL.</li><li>FILLQTY copies QTY if the order filled, otherwise it is 0.</li></ul><p>That gives exactly 40 valid orders, with both short-range rules (STATUS → OUTCOME) and a long-range copy (QTY → FILLQTY).</p><p>It also gives us a ruler. An honest next-token model cannot predict genuine randomness, so its loss has a floor. Side carries 1 bit, ticker 2 bits, quantity 2 bits and status a quarter of a bit; averaged over seven predictions, the floor is <strong>0.520 nats per token</strong>. Any model that scores below that on this task is not predicting. It is peeking.</p><p>The model, the masks, the backpropagation and the optimizer are all written by hand, and the gradients are checked against finite differences (worst error 3.9 × 10⁻¹⁰). No framework sits between you and the numbers.</p><h3>Act 1: what happens when you remove the mask</h3><p>Train the same model twice on the same next-token task, once with the causal mask and once without. The unmasked model reaches a perfect training loss and is useless at inference.</p><p>The only difference between the two runs is one line in the attention layer:</p><pre>S = Q @ K.transpose(0, 1, 3, 2) / np.sqrt(dh)   # raw attention scores<br>S = np.where(allowed, S, -1e9)                  # the mask: causal_mask(n) vs full_mask(n)</pre><p>Training uses teacher forcing: the whole order goes in at once, and position <em>t</em> is asked to predict token <em>t + 1</em>. Without the mask, position <em>t</em> can simply look at token <em>t + 1</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0-OLSfT3Mifr4UkD.png" /></figure><p>Read the table left to right and the trap appears:</p><ol><li><strong>The unmasked model beats the theoretical floor.</strong> A loss of 0.000 on a task with 0.520 nats of genuine randomness is impossible for an honest model. Its attention confirms it: each position puts 50% of its attention on the very next token, against 14% for uniform attention. It learned to read the answer key.</li><li><strong>Scored the way inference actually works, it collapses.</strong> Given only the prefix, its loss jumps to 5.27, ten times worse than the causal model.</li><li><strong>It stops representing the world.</strong> Asked to generate orders from scratch, it produces one memorized order (SELL HDFC 100 REJECT CANCEL 0) 90.6% of the time. It never had to learn the distribution of sides or tickers, because during training it just looked them up.</li></ol><p>The causal model’s training loss and inference loss are the same number, 0.520, right on the floor. That equality is the whole point of the mask: <strong>training conditions match deployment conditions</strong>.</p><p>The causal model’s attention also shows something it learned legitimately. When it sits at OUTCOME and must produce FILLQTY next, one of its heads puts 100% of its attention on QTY. It discovered the copy rule using only the past.</p><p>Now reread the spoofing story. The surveillance model is the unmasked row of this table. Its back test is the training loss; its first live week is the inference column. The cancellation it relied on is the token at <em>t + 1</em>.</p><p><strong>The general lesson:</strong> a validation score that beats what the information available at decision time could support is not a triumph. It is a leak, and finding it is cheaper before go-live than after.</p><h3>Act 2: Two analysts, one trade blotter</h3><p>The alternatives to causal masking are not better or worse. Each one fits a different job, and the cleanest way to see which is to ask who would do that job without AI, and what they are allowed to see.</p><p>Picture one day’s trades flowing through a bank, seen by four people:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ftoiiAKuQEK5biF.png" /></figure><p>The lab gives each of them a turn.</p><h3>The risk officer: causal</h3><p>This is Act 1’s causal model. It is the only one of the four that can work live, because it never relies on information that does not exist yet.</p><h3>The compliance reviewer: understanding</h3><p>Give two models the same job: at every token, predict whether this order will end up filled. One is causal, one is bidirectional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*ox7tsbczMHSpnwSq.png" /></figure><p>The causal curve is the best any live system could do. At SIDE and TICKER it can only guess the base rate. At QTY it learns that 10 and 50 always fill and 500 never does. From STATUS on it is certain.</p><p>The bidirectional model is perfect from the first token, because the SIDE token can read OUTCOME. For the T+1 reviewer judging a <em>complete</em> record, that is exactly right: richer context, better classification. That is why BERT-style encoders still power classification, entity extraction and retrieval, and why some teams strip the causal mask from LLMs before turning them into embedding models (LLM2Vec and NV-Embed are well-known examples).</p><p>For the risk officer, the same 100% is look-ahead bias. <strong>Same data, same architecture, different information rights.</strong></p><h3>The reconciliation analyst: infilling</h3><p>A reconciliation break often has a missing field in the middle of a record, with the evidence sitting after it. A masked-LM is trained exactly for this: hide random tokens, predict them from both sides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2RsYbDb5dJY8EcSj.png" /></figure><p>The 87.5% is not a shortfall; it is the best possible score. If the order filled, FILLQTY reveals the quantity, so it is recovered every time. If it was cancelled, FILLQTY is 0 and the quantity could be 100 or 500 (500 is twice as likely), so the best guess is right two-thirds of the time. 0.625 × 1 + 0.375 × ⅔ = 87.5%.</p><p>The causal model is blind to everything on the right, so it guesses one in four. The same problem is why code assistants are trained with fill-in-the-middle: the function you are editing usually has code below the cursor.</p><h3>The end-of-day batch: parallel decoding</h3><p>A causal model writes one token per forward pass. A masked-LM can start from a fully masked sequence, predict every hole at once, keep the most confident few, and repeat. That is the core loop behind masked diffusion language models such as LLaDA and Inception’s Mercury.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*cTV18aSBBPOolQ3R.png" /></figure><p>The 87.5% is not a shortfall; it is the best possible score. If the order filled, FILLQTY reveals the quantity, so it is recovered every time. If it was cancelled, FILLQTY is 0 and the quantity could be 100 or 500 (500 is twice as likely), so the best guess is right two-thirds of the time. 0.625 × 1 + 0.375 × ⅔ = 87.5%.</p><p>The causal model is blind to everything on the right, so it guesses one in four. The same problem is why code assistants are trained with fill-in-the-middle: the function you are editing usually has code below the cursor.</p><h3>The end-of-day batch: parallel decoding</h3><p>A causal model writes one token per forward pass. A masked-LM can start from a fully masked sequence, predict every hole at once, keep the most confident few, and repeat. That is the core loop behind masked diffusion language models such as LLaDA and Inception’s Mercury.</p><p>[embed: node/5e5dc21b-26ca]</p><p>One pass is fast and mostly wrong. Every hole is sampled from its own distribution, so the model writes things like INFY 100 ACK CANCEL 50: ACK is plausible, CANCEL is plausible, but not together. With three passes, later tokens can condition on earlier ones, and 96.6% of orders come out valid using fewer than half the forward passes of the causal model.</p><p>That is the trade every parallel decoder manages: <strong>speed against coherence</strong>, tuned by how many tokens you commit per pass.</p><p><strong>The question to take into any design review:</strong> which of these four people is this AI standing in for, and what were they allowed to see?</p><h3>Act 3: The back test that read tomorrow’s newspaper</h3><p>Causal masking is one instance of a discipline finance already has a name for: <strong>point-in-time data</strong>. In an LLM system, the future can leak in through at least four other doors, and the attention mask guards only one of them.</p><p>Another composite story. A quant team uses an LLM to score the sentiment of news headlines and earnings-call snippets, then trades on the scores. The back test Sharpe ratio is the best the desk has seen. Before it goes to the investment committee, a skeptical risk manager asks one question: <em>what did the system know, and when did it know it?</em></p><p>The answer takes a week to assemble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_HXvbB453uMRnmn.png" /></figure><p>How big is the leak in practice? The research is genuinely mixed, which is itself the lesson:</p><ul><li><strong>Glasserman and Lin (2023)</strong> stripped company names from headlines before asking GPT for sentiment. In-sample, the anonymized version did <em>better</em>, which they read as general knowledge about a company distracting the model more than look-ahead was helping it (<a href="https://arxiv.org/abs/2309.17322">arXiv</a>).</li><li><strong>He, Lv, Manela and Wu (2025)</strong> trained “chronologically consistent” models on text available only up to each date. In their next-day return prediction test, the measured look-ahead bias was modest (<a href="https://arxiv.org/abs/2502.21206">arXiv</a>).</li><li><strong>Benhenda (2026)</strong> ran LLMs inside an agentic trading workflow. Standard open-weight models lost roughly 15 to 22 percentage points of alpha between the in-sample and out-of-sample periods, while point-in-time models stayed stable. The author flags it as a proof of concept on five stocks (<a href="https://arxiv.org/abs/2601.13770">arXiv</a>).</li></ul><p>Read together, they say the size of the leak depends on the model, the task and the workflow, and that agentic workflows may be where it bites hardest. Either way, <strong>you cannot know how big it is unless you built the system so that you could switch the future off.</strong> That is what a causal mask does inside a transformer, and what as-of discipline does everywhere else.</p><h3>Act 4: The agent with an append-only memory</h3><p>An LLM agent is a causal system whether you design it that way or not. Its context grows left to right, and both its serving cost and its auditability depend on never rewriting the past.</p><p>A final composite story. A financial-crime team builds an agent to work KYC and AML alerts. For each alert it runs dozens of tool calls: the customer’s KYC profile, transaction history, counterparties, adverse-media searches. Then it drafts a recommendation and, where needed, a suspicious-activity narrative.</p><p>An engineer “improves” it. Instead of letting the context grow, the agent now keeps a tidy running case summary near the top, rewritten after every tool call. Answers get marginally neater. Latency and cost per case climb sharply.</p><p>A month later, model-risk review asks a routine question about one escalation: <em>at the moment the agent recommended filing, what had it actually seen?</em> Nobody can answer, because the summary that drove the decision was overwritten forty times.</p><p>Both problems trace back to the lab. Experiment 3 appends one token and measures how much the earlier positions’ internal states change:</p><ul><li><strong>Causal model:</strong> 0.0 at every step. Earlier states never change, so their keys and values are computed once and cached.</li><li><strong>Bidirectional model:</strong> changes of 1.4 to 23 at every step. Every new token rewrites the past, so nothing can be reused.</li></ul><p>This is why LLM serving engines keep a KV cache, and why model providers offer prompt caching that reuses an already-computed prefix at a fraction of the normal input price. It also explains the catch: a change to any early token invalidates everything after it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*7yT3bPtRxArvjtHc.png" /></figure><p>The append-only version solves the audit problem too. If the context is an ordered log, the state of the agent’s knowledge at step <em>k</em> is simply the first <em>k</em> entries. Data engineers will recognize the pattern: it is event sourcing, applied to an agent’s working memory.</p><p>There is a second role in this story. A four-eyes <strong>reviewer agent</strong> that checks the closed case afterwards is entitled to read everything at once: it is the T+1 compliance reviewer from Act 2, and a bidirectional view is correct for it. The design mistake is letting the reviewer’s hindsight leak back into the live agent, for example by evaluating the live agent against labels it could not have known at the step it acted. Score each step only on what was in the log up to that step.</p><h3>The playbook: designing agentic systems that only know what they should</h3><p>The four stories share one design principle: <strong>every AI component should see exactly what the person it replaces would be allowed to see, at the moment it acts.</strong> Here is how that turns into product and architecture decisions.</p><h3>For AI Product Managers</h3><ol><li><strong>Write information rights into the PRD.</strong> For every decision the AI makes, state the decision time and what is knowable at that time. “Alert while the order rests on the book” and “review the order after it closes” are different products, even on the same data.</li><li><strong>Name the analyst.</strong> Live decisions, after-the-fact review, record repair and bulk generation map to causal, bidirectional, infilling and parallel designs. Getting this wrong is a product error, not an engineering detail.</li><li><strong>Treat “too good” as a defect.</strong> A back test that beats what the available information could support is a leak until proven otherwise. Make a point-in-time replay score a launch gate, and set expectations from it, not from the back test.</li><li><strong>Measure Live and hindsight products differently.</strong> An alerting product is judged on what it caught in time. A review product is judged on completeness. Mixing the two metrics hides look-ahead bias in the dashboard.</li><li><strong>Treat context layout as unit economics.</strong> Prompt caching turns a stable, append-only context into lower cost and latency per task. Ask for cache hit rate as a tracked metric alongside quality.</li><li><strong>Make “what did it know, and when” answerable.</strong> In regulated workflows, model-risk and audit teams will ask. If the answer requires reconstruction by hand, the product is not ready.</li></ol><h3>For AI Architects</h3><ol><li><strong>Order the context from most stable to least.</strong> System prompt, then tool definitions, then case facts, then an append-only turn log. Never mutate an earlier block. When you must compress, append the summary as a new entry or compact at an explicit checkpoint and accept a one-time recompute.</li><li><strong>Time-fence every tool.</strong> Give each tool an as_of parameter that the harness sets and enforces, not the model. In simulation and backtests, the harness pins it to the simulated clock.</li><li><strong>Store knowledge bi-temporally.</strong> Record when a fact was true and when it became known. Retrieval filters on the second one. Restated financials and revised notes then stop leaking into historical runs.</li><li><strong>Make agent memory an event log.</strong> An immutable, ordered log gives you replay to any step, a natural audit trail and maximal cache reuse, all from one decision.</li><li><strong>Pick the attention regime per component, not per system.</strong> A causal LLM for live reasoning and actions. A bidirectional encoder for embeddings, classification and reranking of complete documents. An infilling model for repairing records and code. A parallel decoder where throughput matters and outputs can be validated.</li><li><strong>Validate anything generated in parallel.</strong> The lab’s one-pass outputs were 91% invalid. Put schema and business-rule checks after any parallel or batch generation step.</li><li><strong>Separate the actor from the reviewer.</strong> Information flows from the live agent to the hindsight reviewer, never back at decision time. When reviewer labels are reused for training or evaluation, align them to what the actor could see at each step.</li><li><strong>Build a point-in-time evaluation harness.</strong> Replay events up to time <em>t</em> only, score, and compare with the full-information score. The gap is your measured look-ahead. For backtests, use models whose training cutoff precedes the test window, or anonymize entities.</li></ol><h3>Design-review checklist</h3><ul><li>Each AI decision has a written decision time and information boundary</li><li>Every tool and retriever honors an as_of date enforced by the harness</li><li>The agent’s context is append-only, ordered from most to least stable</li><li>Point-in-time replay scores exist, and the gap to full-information scores is known</li><li>Live actors and hindsight reviewers are separate, with one-way information flow</li><li>Parallel or batch generation is followed by rule-based validation</li><li>Anyone can reconstruct what the agent knew at any step from the log</li></ul><h3>Is this still relevant for today’s LLMs?</h3><p>More than ever. Causal masking is arguably the most load-bearing design choice in modern language models, and the agentic era has raised its stakes.</p><ul><li><strong>The frontier is causal.</strong> The major generative model families are decoder-only and use causal attention.</li><li><strong>The economics depend on it.</strong> KV caching, prompt caching and the attention kernels that skip the masked half of the matrix all exist because the past never changes.</li><li><strong>The alternatives are thriving in their niches.</strong> Embedding and reranking models are bidirectional. Code models train for fill-in-the-middle. Masked diffusion language models are pushing parallel decoding toward production speed.</li><li><strong>Agents extend the principle beyond the model.</strong> Tools, retrieval, memory and evaluation all need the same discipline the mask enforces inside attention.</li></ul><h3>The one idea underneath</h3><p>A mask is a policy about information. It decides what each part of a system may use at the moment it acts, and the right policy is the one that matches what will really be available when the system is used.</p><p>The surveillance model failed because it was trained with a policy it could not have in production. The quant back test flattered itself for the same reason. The investigation agent became expensive and un-auditable because it kept rewriting what it had already seen.</p><p>Before you choose a model, a prompt layout or an agent topology, ask the question this article opened with: <strong>who is allowed to see the future?</strong> For most live systems in finance, the answer should be nobody.</p><h3>Run the lab yourself</h3><p>The lab is a single Python file that needs only NumPy. Run python causal_masking_lab.py; it takes about two minutes on a laptop CPU and prints every number in this article. Run python causal_masking_lab.py --grad check to verify the hand-written backpropagation.</p><p>It covers seven experiments: the mask by hand, training with and without the mask, generation, KV-cache stability, per-token understanding, infilling and parallel decoding. A natural extension is to add a prefix-LM model and watch it gain richer prompt representations while losing incremental caching inside the prompt.</p><p>The PYTHON LAB</p><pre>&quot;&quot;&quot;<br>causal_masking_lab.py  —  a crude, end-to-end, NumPy-only lab on attention masks.Nothing is hidden behind a framework: the transformer, its masks, the backprop<br>and the optimiser are all written out by hand below, so you can read exactly<br>what a mask does to every number.<br><br>THE TOY WORLD  (&quot;order-event language&quot;)<br>---------------------------------------<br>Every sequence is one order&#39;s life-cycle, always 8 tokens long:<br>    pos:   0     1      2       3      4        5        6      7<br>         &lt;s&gt;   SIDE  TICKER   QTY   STATUS   OUTCOME  FILLQTY  &lt;/s&gt;<br>   e.g.  &lt;s&gt;   BUY   INFY     100   ACK      FILL     100     &lt;/s&gt;<br>         &lt;s&gt;   SELL  TCS      500   REJECT   CANCEL   0       &lt;/s&gt;<br>Rules of the world (the &quot;grammar&quot; the models must learn):<br>  * SIDE, TICKER, QTY are random (uniform).<br>  * STATUS: QTY 10 or 50 -&gt; always ACK; QTY 500 -&gt; always REJECT (risk limit);<br>            QTY 100 -&gt; ACK or REJECT 50/50 (genuinely unpredictable).<br>  * OUTCOME: ACK -&gt; FILL, REJECT -&gt; CANCEL            (deterministic)<br>  * FILLQTY: FILL -&gt; copy of QTY, CANCEL -&gt; 0         (deterministic, long-range copy)<br>EXPERIMENTS<br>-----------<br>  0. The mask, by hand: raw scores -&gt; masked scores -&gt; SoftMax, on 4 tokens.<br>  1. Next-token training WITH a causal mask vs WITHOUT any mask (leakage).<br>  2. Generation: the leaky model collapses, the causal one writes valid orders.<br>  3. KV cache: exact for causal attention, invalid for bidirectional attention.<br>  4. UNDERSTANDING: per-token &quot;will this order fill?&quot; tagging, causal vs bidirectional.<br>  5. INFILLING: masked-LM (bidirectional) fills holes using the right-hand context.<br>  6. PARALLEL DECODING: masked-diffusion-style generation in 1/2/3/6 steps.<br>Run:  python causal_masking_lab.py            (≈1–2 minutes on a laptop CPU)<br>      python causal_masking_lab.py --grad check (verifies the hand-written backprop)<br>&quot;&quot;&quot;<br>import sys<br>import numpy as np<br>np.set_printoptions(precision=3, suppress=True, linewidth=120)<br>RNG = np.random.default_rng(7)<br># ----------------------------------------------------------------------------<br># 1. Vocabulary and data<br># ----------------------------------------------------------------------------<br>VOCAB = [&#39;&lt;pad&gt;&#39;, &#39;&lt;s&gt;&#39;, &#39;&lt;/s&gt;&#39;, &#39;[MASK]&#39;,<br>         &#39;BUY&#39;, &#39;SELL&#39;,<br>         &#39;INFY&#39;, &#39;TCS&#39;, &#39;HDFC&#39;, &#39;RELI&#39;,<br>         &#39;10&#39;, &#39;50&#39;, &#39;100&#39;, &#39;500&#39;,<br>         &#39;ACK&#39;, &#39;REJECT&#39;, &#39;FILL&#39;, &#39;CANCEL&#39;, &#39;0&#39;]<br>ID = {t: i for i, t in enumerate(VOCAB)}<br>V = len(VOCAB)<br>T = 8  # every order is exactly 8 tokens<br>SIDES, TICKERS, QTYS = [&#39;BUY&#39;, &#39;SELL&#39;], [&#39;INFY&#39;, &#39;TCS&#39;, &#39;HDFC&#39;, &#39;RELI&#39;], [&#39;10&#39;, &#39;50&#39;, &#39;100&#39;, &#39;500&#39;]<br><br>def sample_orders(n, rng=RNG):<br>    seqs = np.zeros((n, T), dtype=int)<br>    for i in range(n):<br>        side, tic, qty = rng.choice(SIDES), rng.choice(TICKERS), rng.choice(QTYS)<br>        if qty in (&#39;10&#39;, &#39;50&#39;):<br>            status = &#39;ACK&#39;<br>        elif qty == &#39;500&#39;:<br>            status = &#39;REJECT&#39;<br>        else:<br>            status = rng.choice([&#39;ACK&#39;, &#39;REJECT&#39;])<br>        outcome = &#39;FILL&#39; if status == &#39;ACK&#39; else &#39;CANCEL&#39;<br>        fillqty = qty if outcome == &#39;FILL&#39; else &#39;0&#39;<br>        seqs[i] = [ID[t] for t in [&#39;&lt;s&gt;&#39;, side, tic, qty, status, outcome, fillqty, &#39;&lt;/s&gt;&#39;]]<br>    return seqs<br><br>def decode(seq):<br>    return &#39; &#39;.join(VOCAB[i] for i in seq)<br><br>def is_valid(seq):<br>    &quot;&quot;&quot;Does a generated 8-token sequence obey every rule of the world?&quot;&quot;&quot;<br>    t = [VOCAB[i] for i in seq]<br>    if len(t) != 8 or t[0] != &#39;&lt;s&gt;&#39; or t[7] != &#39;&lt;/s&gt;&#39;:<br>        return False<br>    side, tic, qty, status, outcome, fq = t[1:7]<br>    if side not in SIDES or tic not in TICKERS or qty not in QTYS:<br>        return False<br>    if qty in (&#39;10&#39;, &#39;50&#39;) and status != &#39;ACK&#39;:<br>        return False<br>    if qty == &#39;500&#39; and status != &#39;REJECT&#39;:<br>        return False<br>    if status not in (&#39;ACK&#39;, &#39;REJECT&#39;):<br>        return False<br>    if outcome != (&#39;FILL&#39; if status == &#39;ACK&#39; else &#39;CANCEL&#39;):<br>        return False<br>    return fq == (qty if outcome == &#39;FILL&#39; else &#39;0&#39;)<br><br># ----------------------------------------------------------------------------<br># 2. Masks  -  the whole topic in four functions<br>#    allowed[i, j] == True  means  &quot;query position i MAY attend to key position j&quot;<br># ----------------------------------------------------------------------------<br>def causal_mask(n):<br>    return np.tril(np.ones((n, n), dtype=bool))          # j &lt;= i<br><br>def full_mask(n):<br>    return np.ones((n, n), dtype=bool)                    # everyone sees everyone<br><br>def prefix_lm_mask(n, prefix_len):<br>    m = causal_mask(n)<br>    m[:prefix_len, :prefix_len] = True                    # prefix is bidirectional<br>    return m<br><br>def show_mask(m, labels, title):<br>    print(f&quot;\n  {title}&quot;)<br>    print(&quot;          &quot; + &quot; &quot;.join(f&quot;{l[:6]:&gt;6}&quot; for l in labels))<br>    for i, l in enumerate(labels):<br>        print(f&quot;  {l[:7]:&gt;7} &quot; + &quot; &quot;.join(f&quot;{&#39;  ✓   &#39; if m[i, j] else &#39;  ·   &#39;}&quot; for j in range(len(labels))))<br><br># ----------------------------------------------------------------------------<br># 3. A one-layer transformer, forward + backward by hand<br>#    tokens -&gt; embed + pos -&gt; multi-head attention (with MASK) -&gt; +res -&gt; FFN -&gt; +res -&gt; logits<br># ----------------------------------------------------------------------------<br>class TinyTransformer:<br>    def __init__(self, d=64, heads=4, ffn=128, seed=0):<br>        r = np.random.default_rng(seed)<br>        s = lambda *shape: r.normal(0, 0.08, shape)<br>        self.h, self.d, self.dh = heads, d, d // heads<br>        self.p = {<br>            &#39;E&#39;: s(V, d), &#39;P&#39;: s(T, d),<br>            &#39;Wq&#39;: s(d, d), &#39;Wk&#39;: s(d, d), &#39;Wv&#39;: s(d, d), &#39;Wo&#39;: s(d, d),<br>            &#39;W1&#39;: s(d, ffn), &#39;b1&#39;: np.zeros(ffn), &#39;W2&#39;: s(ffn, d), &#39;b2&#39;: np.zeros(d),<br>            &#39;Wout&#39;: s(d, V), &#39;bout&#39;: np.zeros(V),<br>        }<br>        self.m = {k: np.zeros_like(v) for k, v in self.p.items()}   # Adam state<br>        self.v = {k: np.zeros_like(v) for k, v in self.p.items()}<br>        self.t = 0<br>    # ---- forward ---------------------------------------------------------<br>    def forward(self, tok, allowed, return_attn=False):<br>        p, h, dh = self.p, self.h, self.dh<br>        B, n = tok.shape<br>        X = p[&#39;E&#39;][tok] + p[&#39;P&#39;][:n]                                   # (B,n,d)<br>        split = lambda M: M.reshape(B, n, h, dh).transpose(0, 2, 1, 3)  # (B,h,n,dh)<br>        Q, K, Vv = split(X @ p[&#39;Wq&#39;]), split(X @ p[&#39;Wk&#39;]), split(X @ p[&#39;Wv&#39;])<br>        S = Q @ K.transpose(0, 1, 3, 2) / np.sqrt(dh)                  # (B,h,n,n) raw scores<br>        S = np.where(allowed[:n, :n], S, -1e9)                         # &lt;&lt;&lt; THE MASK &gt;&gt;&gt;<br>        S = S - S.max(-1, keepdims=True)<br>        A = np.exp(S); A /= A.sum(-1, keepdims=True)                   # softmax: masked -&gt; exactly 0<br>        O = (A @ Vv).transpose(0, 2, 1, 3).reshape(B, n, -1)           # (B,n,d)<br>        Z1 = X + O @ p[&#39;Wo&#39;]<br>        U = Z1 @ p[&#39;W1&#39;] + p[&#39;b1&#39;]<br>        R = np.maximum(U, 0)<br>        Z2 = Z1 + R @ p[&#39;W2&#39;] + p[&#39;b2&#39;]<br>        logits = Z2 @ p[&#39;Wout&#39;] + p[&#39;bout&#39;]<br>        self.cache = (tok, X, Q, K, Vv, A, O, Z1, U, R, Z2)<br>        return (logits, A) if return_attn else logits<br>    # ---- backward --------------------------------------------------------<br>    def backward(self, dlogits):<br>        p, h, dh = self.p, self.h, self.dh<br>        tok, X, Q, K, Vv, A, O, Z1, U, R, Z2 = self.cache<br>        B, n, d = X.shape<br>        flat = lambda M: M.reshape(-1, M.shape[-1])<br>        g = {}<br>        g[&#39;Wout&#39;] = flat(Z2).T @ flat(dlogits); g[&#39;bout&#39;] = dlogits.sum((0, 1))<br>        dZ2 = dlogits @ p[&#39;Wout&#39;].T<br>        g[&#39;W2&#39;] = flat(R).T @ flat(dZ2); g[&#39;b2&#39;] = dZ2.sum((0, 1))<br>        dU = (dZ2 @ p[&#39;W2&#39;].T) * (U &gt; 0)<br>        g[&#39;W1&#39;] = flat(Z1).T @ flat(dU); g[&#39;b1&#39;] = dU.sum((0, 1))<br>        dZ1 = dZ2 + dU @ p[&#39;W1&#39;].T<br>        g[&#39;Wo&#39;] = flat(O).T @ flat(dZ1)<br>        dO = (dZ1 @ p[&#39;Wo&#39;].T).reshape(B, n, h, dh).transpose(0, 2, 1, 3)<br>        dA = dO @ Vv.transpose(0, 1, 3, 2)<br>        dV = A.transpose(0, 1, 3, 2) @ dO<br>        dS = A * (dA - (dA * A).sum(-1, keepdims=True)) / np.sqrt(dh)  # masked cells: A=0 -&gt; grad 0<br>        dQ, dK = dS @ K, dS.transpose(0, 1, 3, 2) @ Q<br>        merge = lambda M: M.transpose(0, 2, 1, 3).reshape(B, n, d)<br>        dQ, dK, dV = merge(dQ), merge(dK), merge(dV)<br>        g[&#39;Wq&#39;], g[&#39;Wk&#39;], g[&#39;Wv&#39;] = flat(X).T @ flat(dQ), flat(X).T @ flat(dK), flat(X).T @ flat(dV)<br>        dX = dZ1 + dQ @ p[&#39;Wq&#39;].T + dK @ p[&#39;Wk&#39;].T + dV @ p[&#39;Wv&#39;].T<br>        g[&#39;E&#39;] = np.zeros_like(p[&#39;E&#39;]); np.add.at(g[&#39;E&#39;], tok, dX)<br>        g[&#39;P&#39;] = np.zeros_like(p[&#39;P&#39;]); g[&#39;P&#39;][:n] = dX.sum(0)<br>        return g<br>    def adam(self, g, lr=3e-3, b1=0.9, b2=0.99):<br>        self.t += 1<br>        for k in self.p:<br>            self.m[k] = b1 * self.m[k] + (1 - b1) * g[k]<br>            self.v[k] = b2 * self.v[k] + (1 - b2) * g[k] ** 2<br>            mh, vh = self.m[k] / (1 - b1 ** self.t), self.v[k] / (1 - b2 ** self.t)<br>            self.p[k] -= lr * mh / (np.sqrt(vh) + 1e-8)<br><br>def softmax(z):<br>    z = z - z.max(-1, keepdims=True)<br>    e = np.exp(z)<br>    return e / e.sum(-1, keepdims=True)<br><br>def ce_loss(logits, targets, weights):<br>    &quot;&quot;&quot;Weighted cross-entropy. weights=0 positions don&#39;t train (used by MLM).&quot;&quot;&quot;<br>    P = softmax(logits)<br>    B, n, _ = logits.shape<br>    pt = P[np.arange(B)[:, None], np.arange(n)[None, :], targets]<br>    loss = -(weights * np.log(pt + 1e-12)).sum() / weights.sum()<br>    d = P.copy()<br>    d[np.arange(B)[:, None], np.arange(n)[None, :], targets] -= 1<br>    return loss, d * (weights / weights.sum())[..., None]<br><br>def train(model, batch_fn, allowed, steps, label, log_every=500):<br>    for s in range(1, steps + 1):<br>        inp, tgt, w = batch_fn()<br>        loss, dl = ce_loss(model.forward(inp, allowed), tgt, w)<br>        model.adam(model.backward(dl))<br>        if s % log_every == 0 or s == 1:<br>            print(f&quot;    [{label}] step {s:5d}  loss {loss:.4f}&quot;)<br>    return loss<br><br># ----------------------------------------------------------------------------<br># Batch builders for the three training objectives<br># ----------------------------------------------------------------------------<br>def lm_batch(B=128):<br>    &quot;&quot;&quot;Next-token prediction: input tokens 0..6, target tokens 1..7 (teacher forcing).&quot;&quot;&quot;<br>    s = sample_orders(B)<br>    return s[:, :-1], s[:, 1:], np.ones((B, T - 1))<br><br>def tag_batch(B=128):<br>    &quot;&quot;&quot;Understanding: at EVERY position, predict whether this order ends FILL or CANCEL.&quot;&quot;&quot;<br>    s = sample_orders(B)<br>    return s, np.repeat(s[:, 5:6], T, axis=1), np.ones((B, T))<br><br>def mlm_batch(B=128):<br>    &quot;&quot;&quot;Masked LM / masked diffusion: hide a random fraction r~U(0.1,1) of positions 1..6.&quot;&quot;&quot;<br>    s = sample_orders(B)<br>    inp, w = s.copy(), np.zeros((B, T))<br>    for i in range(B):<br>        r = RNG.uniform(0.1, 1.0)<br>        hide = 1 + np.flatnonzero(RNG.random(6) &lt; r)<br>        if len(hide) == 0:<br>            hide = np.array([RNG.integers(1, 7)])<br>        inp[i, hide] = ID[&#39;[MASK]&#39;]<br>        w[i, hide] = 1.0<br>    return inp, s, w<br><br># ----------------------------------------------------------------------------<br># Generation helpers<br># ----------------------------------------------------------------------------<br>def generate_autoregressive(model, allowed, n=500, temp=1.0, rng=RNG):<br>    seqs = np.full((n, 1), ID[&#39;&lt;s&gt;&#39;])<br>    for t in range(T - 1):                       # 7 forward passes<br>        logits = model.forward(seqs, allowed)[:, -1] / temp<br>        P = softmax(logits)<br>        nxt = np.array([rng.choice(V, p=p) for p in P])<br>        seqs = np.concatenate([seqs, nxt[:, None]], axis=1)<br>    return seqs<br><br>def generate_parallel(model, steps, n=500, rng=RNG):<br>    &quot;&quot;&quot;Masked-diffusion-style: start all [MASK]; each pass, predict every hole in<br>    parallel, sample, and COMMIT the most confident k of them. steps=1 -&gt; fully parallel.&quot;&quot;&quot;<br>    full = full_mask(T)<br>    seqs = np.full((n, T), ID[&#39;[MASK]&#39;])<br>    seqs[:, 0], seqs[:, -1] = ID[&#39;&lt;s&gt;&#39;], ID[&#39;&lt;/s&gt;&#39;]<br>    sched = np.diff(np.round(np.linspace(0, 6, steps + 1)).astype(int))  # how many to commit per pass<br>    for k in sched:<br>        P = softmax(model.forward(seqs, full))<br>        P[..., ID[&#39;[MASK]&#39;]] = 0; P /= P.sum(-1, keepdims=True)<br>        for b in range(n):<br>            holes = np.flatnonzero(seqs[b] == ID[&#39;[MASK]&#39;])<br>            draws = np.array([rng.choice(V, p=P[b, j]) for j in holes])<br>            conf = P[b, holes, draws]<br>            for idx in np.argsort(-conf)[:k]:<br>                seqs[b, holes[idx]] = draws[idx]<br>    return seqs<br><br># ----------------------------------------------------------------------------<br># Gradient check (run with --gradcheck)<br># ----------------------------------------------------------------------------<br>def gradcheck():<br>    m = TinyTransformer(d=8, heads=2, ffn=8, seed=1)<br>    inp, tgt, w = lm_batch(3)<br>    allowed = causal_mask(T)<br>    _, dl = ce_loss(m.forward(inp, allowed), tgt, w)<br>    g = m.backward(dl)<br>    worst = 0<br>    for k in [&#39;Wq&#39;, &#39;Wk&#39;, &#39;Wv&#39;, &#39;Wo&#39;, &#39;W1&#39;, &#39;Wout&#39;, &#39;E&#39;, &#39;P&#39;]:<br>        for _ in range(5):<br>            idx = tuple(RNG.integers(0, s) for s in m.p[k].shape)<br>            old = m.p[k][idx]<br>            m.p[k][idx] = old + 1e-6; lp, _ = ce_loss(m.forward(inp, allowed), tgt, w)<br>            m.p[k][idx] = old - 1e-6; lm, _ = ce_loss(m.forward(inp, allowed), tgt, w)<br>            m.p[k][idx] = old<br>            num = (lp - lm) / 2e-6<br>            worst = max(worst, abs(num - g[k][idx]))   # absolute error (some true grads are ~1e-7)<br>    print(f&quot;gradcheck worst absolute error vs finite differences: {worst:.1e}  ({&#39;OK&#39; if worst &lt; 1e-7 else &#39;FAIL&#39;})&quot;)<br><br># ============================================================================<br>#                                   MAIN<br># ============================================================================<br>def banner(s):<br>    print(&quot;\n&quot; + &quot;=&quot; * 100 + f&quot;\n{s}\n&quot; + &quot;=&quot; * 100)<br><br>def main():<br>    LABELS = [&#39;&lt;s&gt;&#39;, &#39;SIDE&#39;, &#39;TICKER&#39;, &#39;QTY&#39;, &#39;STATUS&#39;, &#39;OUTCOME&#39;, &#39;FILLQTY&#39;, &#39;&lt;/s&gt;&#39;]<br>    # ------------------------------------------------------------------ 0<br>    banner(&quot;EXPERIMENT 0 - The mask by hand (4 tokens: &#39;&lt;s&gt; BUY INFY 100&#39;)&quot;)<br>    toks = [&#39;&lt;s&gt;&#39;, &#39;BUY&#39;, &#39;INFY&#39;, &#39;100&#39;]<br>    S = np.array([[2.0, 0.5, 0.1, 1.0],<br>                  [0.3, 1.5, 0.8, 2.5],<br>                  [0.2, 1.1, 1.9, 0.7],<br>                  [0.4, 0.9, 1.3, 2.2]])<br>    print(&quot;  Raw scores S = QKᵀ/√d (row = query token, col = key token):\n&quot;, S)<br>    Sm = np.where(causal_mask(4), S, -np.inf)<br>    print(&quot;\n  After causal mask (upper triangle -&gt; -inf):\n&quot;, Sm)<br>    print(&quot;\n  softmax(masked) - each row sums to 1, future columns are EXACTLY 0:\n&quot;, softmax(np.where(causal_mask(4), S, -1e9)))<br>    print(&quot;\n  softmax(unmasked) for contrast - row &#39;BUY&#39; gives 60% of its attention to the future token &#39;100&#39;:\n&quot;, softmax(S))<br>    show_mask(causal_mask(8), LABELS, &quot;Causal mask over a full order (✓ = may attend):&quot;)<br>    show_mask(full_mask(8), LABELS, &quot;Bidirectional (encoder / BERT) mask:&quot;)<br>    show_mask(prefix_lm_mask(8, 4), LABELS, &quot;Prefix-LM mask (prefix &#39;&lt;s&gt; SIDE TICKER QTY&#39; bidirectional, rest causal):&quot;)<br>    print(&quot;\n  A few training orders from our toy world:&quot;)<br>    for s in sample_orders(4):<br>        print(&quot;    &quot;, decode(s))<br>    # ------------------------------------------------------------------ 1<br>    banner(&quot;EXPERIMENT 1 - Next-token training: causal mask vs NO mask&quot;)<br>    floor = np.log(2) * (1 + 2 + 2 + 0.25) / 7<br>    print(f&quot;  Theoretical minimum loss for an HONEST next-token model: {floor:.4f} nats/token&quot;)<br>    print(&quot;  (SIDE=1 bit, TICKER=2 bits, QTY=2 bits, STATUS=0.25 bit of irreducible randomness, averaged over 7 predictions)\n&quot;)<br>    causal_lm = TinyTransformer(seed=1)<br>    leaky_lm = TinyTransformer(seed=1)<br>    lc = train(causal_lm, lm_batch, causal_mask(T), 2500, &quot;causal&quot;)<br>    ll = train(leaky_lm, lm_batch, full_mask(T), 2500, &quot;no-mask&quot;)<br>    print(f&quot;\n  Final loss  causal: {lc:.4f}  (≈ floor {floor:.4f} → learned the real distribution)&quot;)<br>    print(f&quot;  Final loss  no-mask: {ll:.4f}  (BELOW the floor → impossible honestly; it is copying the answer)&quot;)<br>    _, A = leaky_lm.forward(sample_orders(256)[:, :-1], full_mask(T), return_attn=True)<br>    nxt = np.mean([A[:, :, i, i + 1].mean() for i in range(T - 2)])<br>    print(f&quot;  Proof: in the no-mask model, the average attention a position pays to the very next token = {nxt:.2f}&quot;<br>          f&quot;\n         (uniform would be {1/7:.2f}). It learned to look at the answer key.&quot;)<br>    # Honest evaluation = the inference situation: the model sees ONLY the prefix, never the future.<br>    test = sample_orders(2000)<br>    def honest_loss(model, mask):<br>        tot = 0.0<br>        for t in range(1, T):<br>            P = softmax(model.forward(test[:, :t], mask)[:, -1])<br>            tot += -np.log(P[np.arange(len(test)), test[:, t]] + 1e-12).mean()<br>        return tot / (T - 1)<br>    print(&quot;\n  Now score both models the way inference works - prefix only, future tokens absent:&quot;)<br>    print(f&quot;    causal : {honest_loss(causal_lm, causal_mask(T)):.4f} nats/token  (same as its training loss: train == inference)&quot;)<br>    print(f&quot;    no-mask: {honest_loss(leaky_lm, full_mask(T)):.4f} nats/token  (its 0.0000 training loss was an illusion)&quot;)<br>    _, A = causal_lm.forward(sample_orders(1)[:, :-1], causal_mask(T), return_attn=True)<br>    print(&quot;\n  Causal model, head 0 attention weights for one order (rows=query, cols=key) - note the zero upper triangle:&quot;)<br>    print(A[0, 0])<br>    # ------------------------------------------------------------------ 2<br>    banner(&quot;EXPERIMENT 2 - Generate 500 orders from &#39;&lt;s&gt;&#39; alone (7 sequential forward passes each)&quot;)<br>    print(&quot;  The real world has exactly 40 distinct valid orders (2 sides × 4 tickers × 5 qty/status paths).&quot;)<br>    for name, model in [(&quot;causal&quot;, causal_lm), (&quot;no-mask&quot;, leaky_lm)]:<br>        out = generate_autoregressive(model, full_mask(T) if name == &quot;no-mask&quot; else causal_mask(T))<br>        ok = np.mean([is_valid(s) for s in out])<br>        uniq, counts = np.unique(out, axis=0, return_counts=True)<br>        print(f&quot;\n  {name:8s} → {ok*100:5.1f}% valid | {len(uniq):2d} distinct orders | &quot;<br>              f&quot;most common order = {counts.max()/len(out)*100:4.1f}% of samples. First samples:&quot;)<br>        for s in out[:4]:<br>            print(f&quot;      {&#39;✓&#39; if is_valid(s) else &#39;✗&#39;}  {decode(s)}&quot;)<br>    print(&quot;&quot;&quot;<br>  The leaky model is not a language model of the world any more. During training its &#39;prediction&#39;<br>  was a lookup of the next token; at inference that token does not exist, so it falls back on<br>  whatever its weights default to - here it has collapsed onto essentially ONE memorised order.<br>  The grammar of that order happens to be valid, but SIDE, TICKER, QTY and STATUS are no longer<br>  sampled from their real distribution. The causal model reproduces all 40 with the right odds.&quot;&quot;&quot;)<br>    # ------------------------------------------------------------------ 3<br>    banner(&quot;EXPERIMENT 3 - Why causality makes the KV cache exact&quot;)<br>    seq = sample_orders(1)[:, :-1]<br>    for name, model, mask in [(&quot;causal&quot;, causal_lm, causal_mask(T)), (&quot;bidirectional&quot;, leaky_lm, full_mask(T))]:<br>        drift = []<br>        for t in range(2, T):<br>            model.forward(seq[:, :t - 1], mask); h_before = model.cache[-1][0]        # hidden states for prefix of len t-1<br>            model.forward(seq[:, :t], mask);     h_after = model.cache[-1][0, :t - 1]  # same positions after appending 1 token<br>            drift.append(np.abs(h_after - h_before).max())<br>        print(f&quot;  {name:14s}: max change in OLD positions&#39; states after appending a token, per step = &quot;<br>              + &quot; &quot;.join(f&quot;{x:.1e}&quot; for x in drift))<br>    print(&quot;\n  Causal: old states never change (0.0) → compute K,V once, cache them, each new token is O(n) work.&quot;)<br>    print(&quot;  Bidirectional: every append rewrites every earlier state → nothing can be cached; each step is O(n²).&quot;)<br>    print(&quot;  This is also exactly why provider-side PROMPT CACHING works: a shared prefix yields identical KV.&quot;)<br>    # ------------------------------------------------------------------ 4<br>    banner(&quot;EXPERIMENT 4 - UNDERSTANDING: tag every token with &#39;will this order FILL?&#39;&quot;)<br>    print(&quot;  Same architecture, same data, one model causal, one bidirectional. Accuracy at each position:\n&quot;)<br>    tagger_c, tagger_b = TinyTransformer(seed=2), TinyTransformer(seed=2)<br>    train(tagger_c, tag_batch, causal_mask(T), 1500, &quot;causal tagger&quot;, log_every=1500)<br>    train(tagger_b, tag_batch, full_mask(T), 1500, &quot;bidir tagger &quot;, log_every=1500)<br>    test = sample_orders(2000)<br>    truth = test[:, 5]<br>    print(&quot;\n            &quot; + &quot; &quot;.join(f&quot;{l:&gt;8}&quot; for l in LABELS))<br>    for name, m, mask in [(&quot;causal&quot;, tagger_c, causal_mask(T)), (&quot;bidir&quot;, tagger_b, full_mask(T))]:<br>        pred = m.forward(test, mask).argmax(-1)<br>        accs = (pred == truth[:, None]).mean(0)<br>        print(f&quot;  {name:&gt;8}  &quot; + &quot; &quot;.join(f&quot;{a*100:7.1f}%&quot; for a in accs))<br>    print(&quot;&quot;&quot;<br>  Reading the causal row: at SIDE/TICKER it can only guess the base rate (62.5% fill); at QTY it<br>  knows 10/50 always fill and 500 never does (87.5%); from STATUS onward it is certain. That is<br>  the BEST POSSIBLE live, real-time answer.<br>  The bidirectional row is 100% everywhere because every token can read STATUS and OUTCOME.<br>  → For understanding a COMPLETE record (post-trade review, classification, embeddings) that is<br>    exactly what you want. For a LIVE alert it is look-ahead bias: 100% in backtest, impossible in production.&quot;&quot;&quot;)<br>    # ------------------------------------------------------------------ 5<br>    banner(&quot;EXPERIMENT 5 - INFILLING with a masked-LM (bidirectional, BERT/diffusion-style objective)&quot;)<br>    mlm = TinyTransformer(seed=3)<br>    train(mlm, mlm_batch, full_mask(T), 5000, &quot;masked-LM&quot;, log_every=1000)<br>    test = sample_orders(2000)<br>    def infill_acc(positions):<br>        inp = test.copy(); inp[:, positions] = ID[&#39;[MASK]&#39;]<br>        pred = mlm.forward(inp, full_mask(T)).argmax(-1)<br>        return (pred[:, positions] == test[:, positions]).all(1).mean()<br>    def causal_acc(pos):<br>        pred = causal_lm.forward(test[:, :-1], causal_mask(T)).argmax(-1)  # prediction for token pos lives at pos-1<br>        return (pred[:, pos - 1] == test[:, pos]).mean()<br>    print(&quot;\n  Fill the hole               masked-LM (sees both sides)   causal LM (left side only)&quot;)<br>    print(f&quot;  QTY      &lt;s&gt; BUY INFY [?] ACK FILL 100 &lt;/s&gt;   {infill_acc([3])*100:6.1f}%                  {causal_acc(3)*100:6.1f}%&quot;)<br>    print(f&quot;  STATUS   &lt;s&gt; BUY INFY 100 [?] FILL 100 &lt;/s&gt;   {infill_acc([4])*100:6.1f}%                  {causal_acc(4)*100:6.1f}%&quot;)<br>    print(f&quot;  QTY+STATUS together (2 holes)              {infill_acc([3, 4])*100:6.1f}%                       n/a&quot;)<br>    ex = test[:3].copy(); ex[:, [3, 4]] = ID[&#39;[MASK]&#39;]<br>    pr = mlm.forward(ex, full_mask(T)).argmax(-1)<br>    print(&quot;\n  Examples (2 holes):&quot;)<br>    for a, b, c in zip(ex, pr, test[:3]):<br>        filled = a.copy(); filled[[3, 4]] = b[[3, 4]]<br>        print(f&quot;     in : {decode(a)}\n     out: {decode(filled)}   truth: {decode(c)}&quot;)<br>    print(&quot;&quot;&quot;<br>  The evidence for QTY sits to its RIGHT. If the order FILLED, FILLQTY copies QTY → 100% recoverable.<br>  If it was CANCELLED, FILLQTY is 0 and QTY could be 100 or 500 (500 is twice as likely) → best guess<br>  is right 2/3 of the time. Bayes-optimal accuracy = 0.625×1 + 0.375×2/3 = 87.5% - the masked-LM hits it.<br>  The causal model is structurally blind to the right side and can only guess 1-in-4 (25%).<br>  Code-completion &#39;fill-in-the-middle&#39; (FIM) training exists for exactly this reason.&quot;&quot;&quot;)<br>    # ------------------------------------------------------------------ 6<br>    banner(&quot;EXPERIMENT 6 - PARALLEL DECODING with the same masked-LM (masked-diffusion style)&quot;)<br>    print(&quot;  Start from &#39;&lt;s&gt; [M] [M] [M] [M] [M] [M] &lt;/s&gt;&#39;. Each forward pass predicts ALL holes at once&quot;)<br>    print(&quot;  and commits the k most confident. Fewer passes = faster, but holes decided together are&quot;)<br>    print(&quot;  sampled INDEPENDENTLY, so they can contradict each other.\n&quot;)<br>    print(&quot;  passes   tokens/pass   valid orders&quot;)<br>    rows = []<br>    for steps in [1, 2, 3, 6]:<br>        out = generate_parallel(mlm, steps)<br>        ok = np.mean([is_valid(s) for s in out])<br>        rows.append((steps, out))<br>        print(f&quot;  {steps:5d}   {6/steps:10.1f}    {ok*100:8.1f}%&quot;)<br>    ar = generate_autoregressive(causal_lm, causal_mask(T))<br>    print(f&quot;  {7:5d}   {1:10.1f}    {np.mean([is_valid(s) for s in ar])*100:8.1f}%   ← causal autoregressive baseline&quot;)<br>    print(&quot;\n  Typical failures in the 1-pass run (all 6 tokens sampled simultaneously):&quot;)<br>    shown = 0<br>    for s in rows[0][1]:<br>        if not is_valid(s):<br>            print(&quot;      ✗ &quot;, decode(s)); shown += 1<br>        if shown == 4:<br>            break<br>    print(&quot;&quot;&quot;<br>  Why: in one pass every hole is sampled from its OWN marginal distribution. &#39;ACK&#39; is plausible,<br>  &#39;CANCEL&#39; is plausible, but not together; &#39;50&#39; and &#39;10&#39; are each plausible as QTY and FILLQTY, but<br>  must match. Committing a few tokens per pass lets later passes condition on earlier choices,<br>  recovering coherence while still using fewer passes than tokens (3 passes ≈ 97% here vs 7 for AR).&quot;&quot;&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    if &quot;--gradcheck&quot; in sys.argv:<br>        gradcheck()<br>    else:<br>        main()</pre><p><strong>RUN OUTPUT</strong></p><pre>====================================================================================================<br>EXPERIMENT 0 — The mask by hand (4 tokens: &#39;&lt;s&gt; BUY INFY 100&#39;)<br>====================================================================================================<br>  Raw scores S = QKᵀ/√d (row = query token, col = key token):<br> [[2.  0.5 0.1 1. ]<br> [0.3 1.5 0.8 2.5]<br> [0.2 1.1 1.9 0.7]<br> [0.4 0.9 1.3 2.2]]<br>  After causal mask (upper triangle -&gt; -inf):<br> [[ 2.  -inf -inf -inf]<br> [ 0.3  1.5 -inf -inf]<br> [ 0.2  1.1  1.9 -inf]<br> [ 0.4  0.9  1.3  2.2]]<br><br>softmax(masked) - each row sums to 1, future columns are EXACTLY 0:<br> [[1.    0.    0.    0.   ]<br> [0.231 0.769 0.    0.   ]<br> [0.112 0.275 0.613 0.   ]<br> [0.09  0.148 0.22  0.542]]<br>  softmax(unmasked) for contrast - row &#39;BUY&#39; gives 60% of its attention to the future token &#39;100&#39;:<br> [[0.575 0.128 0.086 0.211]<br> [0.067 0.221 0.11  0.602]<br> [0.094 0.232 0.517 0.156]<br> [0.09  0.148 0.22  0.542]]<br>  Causal mask over a full order (✓ = may attend):<br>             &lt;s&gt;   SIDE TICKER    QTY STATUS OUTCOM FILLQT   &lt;/s&gt;<br>      &lt;s&gt;   ✓      ·      ·      ·      ·      ·      ·      ·   <br>     SIDE   ✓      ✓      ·      ·      ·      ·      ·      ·   <br>   TICKER   ✓      ✓      ✓      ·      ·      ·      ·      ·   <br>      QTY   ✓      ✓      ✓      ✓      ·      ·      ·      ·   <br>   STATUS   ✓      ✓      ✓      ✓      ✓      ·      ·      ·   <br>  OUTCOME   ✓      ✓      ✓      ✓      ✓      ✓      ·      ·   <br>  FILLQTY   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ·   <br>     &lt;/s&gt;   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>  Bidirectional (encoder / BERT) mask:<br>             &lt;s&gt;   SIDE TICKER    QTY STATUS OUTCOM FILLQT   &lt;/s&gt;<br>      &lt;s&gt;   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>     SIDE   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>   TICKER   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>      QTY   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>   STATUS   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>  OUTCOME   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>  FILLQTY   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>     &lt;/s&gt;   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>  Prefix-LM mask (prefix &#39;&lt;s&gt; SIDE TICKER QTY&#39; bidirectional, rest causal):<br>             &lt;s&gt;   SIDE TICKER    QTY STATUS OUTCOM FILLQT   &lt;/s&gt;<br>      &lt;s&gt;   ✓      ✓      ✓      ✓      ·      ·      ·      ·   <br>     SIDE   ✓      ✓      ✓      ✓      ·      ·      ·      ·   <br>   TICKER   ✓      ✓      ✓      ✓      ·      ·      ·      ·   <br>      QTY   ✓      ✓      ✓      ✓      ·      ·      ·      ·   <br>   STATUS   ✓      ✓      ✓      ✓      ✓      ·      ·      ·   <br>  OUTCOME   ✓      ✓      ✓      ✓      ✓      ✓      ·      ·   <br>  FILLQTY   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ·   <br>     &lt;/s&gt;   ✓      ✓      ✓      ✓      ✓      ✓      ✓      ✓   <br>  A few training orders from our toy world:<br>     &lt;s&gt; SELL HDFC 100 REJECT CANCEL 0 &lt;/s&gt;<br>     &lt;s&gt; SELL RELI 500 REJECT CANCEL 0 &lt;/s&gt;<br>     &lt;s&gt; BUY INFY 50 ACK FILL 50 &lt;/s&gt;<br>     &lt;s&gt; BUY RELI 500 REJECT CANCEL 0 &lt;/s&gt;<br>====================================================================================================<br>EXPERIMENT 1 - Next-token training: causal mask vs NO mask<br>====================================================================================================<br>  Theoretical minimum loss for an HONEST next-token model: 0.5199 nats/token<br>  (SIDE=1 bit, TICKER=2 bits, QTY=2 bits, STATUS=0.25 bit of irreducible randomness, averaged over 7 predictions)<br>    [causal] step     1  loss 2.9349<br>    [causal] step   500  loss 0.5213<br>    [causal] step  1000  loss 0.5259<br>    [causal] step  1500  loss 0.5288<br>    [causal] step  2000  loss 0.5262<br>    [causal] step  2500  loss 0.5269<br>    [no-mask] step     1  loss 2.9349<br>    [no-mask] step   500  loss 0.0000<br>    [no-mask] step  1000  loss 0.0000<br>    [no-mask] step  1500  loss 0.0000<br>    [no-mask] step  2000  loss 0.0000<br>    [no-mask] step  2500  loss 0.0000<br>  Final loss  causal: 0.5269  (≈ floor 0.5199 → learned the real distribution)<br>  Final loss  no-mask: 0.0000  (BELOW the floor → impossible honestly; it is copying the answer)<br>  Proof: in the no-mask model, the average attention a position pays to the very next token = 0.50<br>         (uniform would be 0.14). It learned to look at the answer key.<br>  Now score both models the way inference works - prefix only, future tokens absent:<br>    causal : 0.5202 nats/token  (same as its training loss: train == inference)<br>    no-mask: 5.2701 nats/token  (its 0.0000 training loss was an illusion)<br>  Causal model, head 0 attention weights for one order (rows=query, cols=key) - note the zero upper triangle:<br>[[1.    0.    0.    0.    0.    0.    0.   ]<br> [0.572 0.428 0.    0.    0.    0.    0.   ]<br> [0.372 0.328 0.3   0.    0.    0.    0.   ]<br> [0.    0.    0.    1.    0.    0.    0.   ]<br> [0.251 0.235 0.31  0.042 0.162 0.    0.   ]<br> [0.    0.    0.    1.    0.    0.    0.   ]<br> [0.    0.    0.    0.038 0.    0.    0.962]]<br>====================================================================================================<br>EXPERIMENT 2 - Generate 500 orders from &#39;&lt;s&gt;&#39; alone (7 sequential forward passes each)<br>====================================================================================================<br>  The real world has exactly 40 distinct valid orders (2 sides × 4 tickers × 5 qty/status paths).<br>  causal   → 100.0% valid | 40 distinct orders | most common order =  4.6% of samples. First samples:<br>      ✓  &lt;s&gt; SELL INFY 500 REJECT CANCEL 0 &lt;/s&gt;<br>      ✓  &lt;s&gt; BUY INFY 10 ACK FILL 10 &lt;/s&gt;<br>      ✓  &lt;s&gt; BUY TCS 10 ACK FILL 10 &lt;/s&gt;<br>      ✓  &lt;s&gt; SELL TCS 100 REJECT CANCEL 0 &lt;/s&gt;<br>  no-mask  →  91.2% valid | 14 distinct orders | most common order = 90.6% of samples. First samples:<br>      ✓  &lt;s&gt; SELL HDFC 100 REJECT CANCEL 0 &lt;/s&gt;<br>      ✓  &lt;s&gt; SELL HDFC 100 REJECT CANCEL 0 &lt;/s&gt;<br>      ✓  &lt;s&gt; SELL HDFC 100 REJECT CANCEL 0 &lt;/s&gt;<br>      ✓  &lt;s&gt; SELL HDFC 100 REJECT CANCEL 0 &lt;/s&gt;<br>  The leaky model is not a language model of the world any more. During training its &#39;prediction&#39;<br>  was a lookup of the next token; at inference that token does not exist, so it falls back on<br>  whatever its weights default to - here it has collapsed onto essentially ONE memorised order.<br>  The grammar of that order happens to be valid, but SIDE, TICKER, QTY and STATUS are no longer<br>  sampled from their real distribution. The causal model reproduces all 40 with the right odds.<br>====================================================================================================<br>EXPERIMENT 3 - Why causality makes the KV cache exact<br>====================================================================================================<br>  causal        : max change in OLD positions&#39; states after appending a token, per step = 1.8e-15 0.0e+00 0.0e+00 0.0e+00 0.0e+00 0.0e+00<br>  bidirectional : max change in OLD positions&#39; states after appending a token, per step = 2.2e+01 1.3e+01 2.3e+01 8.3e+00 1.4e+00 7.8e+00<br>  Causal: old states never change (0.0) → compute K,V once, cache them, each new token is O(n) work.<br>  Bidirectional: every append rewrites every earlier state → nothing can be cached; each step is O(n²).<br>  This is also exactly why provider-side PROMPT CACHING works: a shared prefix yields identical KV.<br>====================================================================================================<br>EXPERIMENT 4 - UNDERSTANDING: tag every token with &#39;will this order FILL?&#39;<br>====================================================================================================<br>  Same architecture, same data, one model causal, one bidirectional. Accuracy at each position:<br>    [causal tagger] step     1  loss 2.9354<br>    [causal tagger] step  1500  loss 0.2684<br>    [bidir tagger ] step     1  loss 2.9322<br>    [bidir tagger ] step  1500  loss 0.0000<br>                 &lt;s&gt;     SIDE   TICKER      QTY   STATUS  OUTCOME  FILLQTY     &lt;/s&gt;<br>    causal     62.7%    62.7%    62.7%    87.1%   100.0%   100.0%   100.0%   100.0%<br>     bidir    100.0%   100.0%   100.0%   100.0%   100.0%   100.0%   100.0%   100.0%<br>  Reading the causal row: at SIDE/TICKER it can only guess the base rate (62.5% fill); at QTY it<br>  knows 10/50 always fill and 500 never does (87.5%); from STATUS onward it is certain. That is<br>  the BEST POSSIBLE live, real-time answer.<br>  The bidirectional row is 100% everywhere because every token can read STATUS and OUTCOME.<br>  → For understanding a COMPLETE record (post-trade review, classification, embeddings) that is<br>    exactly what you want. For a LIVE alert it is look-ahead bias: 100% in backtest, impossible in production.<br>====================================================================================================<br>EXPERIMENT 5 - INFILLING with a masked-LM (bidirectional, BERT/diffusion-style objective)<br>====================================================================================================<br>    [masked-LM] step     1  loss 2.9494<br>    [masked-LM] step  1000  loss 0.7607<br>    [masked-LM] step  2000  loss 0.7187<br>    [masked-LM] step  3000  loss 0.7025<br>    [masked-LM] step  4000  loss 0.6653<br>    [masked-LM] step  5000  loss 0.6564<br>  Fill the hole               masked-LM (sees both sides)   causal LM (left side only)<br>  QTY      &lt;s&gt; BUY INFY [?] ACK FILL 100 &lt;/s&gt;     87.5%                    24.3%<br>  STATUS   &lt;s&gt; BUY INFY 100 [?] FILL 100 &lt;/s&gt;    100.0%                    88.2%<br>  QTY+STATUS together (2 holes)                87.5%                       n/a<br>  Examples (2 holes):<br>     in : &lt;s&gt; BUY HDFC [MASK] [MASK] FILL 100 &lt;/s&gt;<br>     out: &lt;s&gt; BUY HDFC 100 ACK FILL 100 &lt;/s&gt;   truth: &lt;s&gt; BUY HDFC 100 ACK FILL 100 &lt;/s&gt;<br>     in : &lt;s&gt; SELL HDFC [MASK] [MASK] FILL 50 &lt;/s&gt;<br>     out: &lt;s&gt; SELL HDFC 50 ACK FILL 50 &lt;/s&gt;   truth: &lt;s&gt; SELL HDFC 50 ACK FILL 50 &lt;/s&gt;<br>     in : &lt;s&gt; BUY INFY [MASK] [MASK] FILL 50 &lt;/s&gt;<br>     out: &lt;s&gt; BUY INFY 50 ACK FILL 50 &lt;/s&gt;   truth: &lt;s&gt; BUY INFY 50 ACK FILL 50 &lt;/s&gt;<br>  The evidence for QTY sits to its RIGHT. If the order FILLED, FILLQTY copies QTY → 100% recoverable.<br>  If it was CANCELLED, FILLQTY is 0 and QTY could be 100 or 500 (500 is twice as likely) → best guess<br>  is right 2/3 of the time. Bayes-optimal accuracy = 0.625×1 + 0.375×2/3 = 87.5% - the masked-LM hits it.<br>  The causal model is structurally blind to the right side and can only guess 1-in-4 (25%).<br>  Code-completion &#39;fill-in-the-middle&#39; (FIM) training exists for exactly this reason.<br>====================================================================================================<br>EXPERIMENT 6 - PARALLEL DECODING with the same masked-LM (masked-diffusion style)<br>====================================================================================================<br>  Start from &#39;&lt;s&gt; [M] [M] [M] [M] [M] [M] &lt;/s&gt;&#39;. Each forward pass predicts ALL holes at once<br>  and commits the k most confident. Fewer passes = faster, but holes decided together are<br>  sampled INDEPENDENTLY, so they can contradict each other.<br>  passes   tokens/pass   valid orders<br>      1          6.0         9.0%<br>      2          3.0        25.0%<br>      3          2.0        96.6%<br>      6          1.0       100.0%<br>      7          1.0        99.8%   ← causal autoregressive baseline<br>  Typical failures in the 1-pass run (all 6 tokens sampled simultaneously):<br>      ✗  &lt;s&gt; BUY HDFC 500 REJECT FILL 0 &lt;/s&gt;<br>      ✗  &lt;s&gt; BUY RELI 10 ACK CANCEL 50 &lt;/s&gt;<br>      ✗  &lt;s&gt; SELL TCS 100 REJECT FILL 10 &lt;/s&gt;<br>      ✗  &lt;s&gt; BUY RELI 10 REJECT FILL 50 &lt;/s&gt;<br>  Why: in one pass every hole is sampled from its OWN marginal distribution. &#39;ACK&#39; is plausible,<br>  &#39;CANCEL&#39; is plausible, but not together; &#39;50&#39; and &#39;10&#39; are each plausible as QTY and FILLQTY, but<br>  must match. Committing a few tokens per pass lets later passes condition on earlier choices,<br>  recovering coherence while still using fewer passes than tokens (3 passes ≈ 97% here vs 7 for AR).</pre><blockquote>The stories in this article are composites built from common industry patterns, not accounts of any specific firm.</blockquote><h3>Sources</h3><ul><li>Paul Glasserman and Caden Lin, <a href="https://arxiv.org/abs/2309.17322">Assessing Look-Ahead Bias in Stock Return Predictions Generated by GPT Sentiment Analysis</a>, arXiv, 2023.</li><li>Songrun He, Linying Lv, Asaf Manela and Jimmy Wu, <a href="https://arxiv.org/abs/2502.21206">Chronologically Consistent Large Language Models</a>, arXiv, 2025.</li><li>Mostapha Benhenda, <a href="https://arxiv.org/abs/2601.13770">Look-Ahead-Bench: a Standardized Benchmark of Look-ahead Bias in Point-in-Time LLMs for Finance</a>, arXiv, January 2026.</li><li>King &amp; Spalding, <a href="https://www.kslaw.com/attachments/000/007/109/original/Spoofing_US_Law_and_Enforcement.pdf">Spoofing: US Law and Enforcement</a> (statutory definition under the Commodity Exchange Act as amended by Dodd-Frank).</li></ul><p><strong><em>Ankur Saran · AI Product Leader | AI First Builder</em></strong></p><p>HAPPY READING to all of you!</p><p>Read, Learn, Experiment, Implement, Share, Express!</p><p>👉 I write about <a href="https://www.linkedin.com/in/ankur-saran/">Data</a>, <a href="https://www.linkedin.com/in/ankur-saran/">AI Strategy</a> and <a href="https://www.linkedin.com/in/ankur-saran/">Product Leadership</a> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</p><p>Connect with me on LinkedIn <a href="https://www.linkedin.com/in/ankur-saran/"><em>Ankur Saran | LinkedIn</em></a></p><p>Follow my SubStack Channel <a href="https://ankursaran.substack.com/"><em>Ankur Saran</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f836498d077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Robot that waits by the Door!]]></title>
            <link>https://medium.com/@ankursaran_59645/the-robot-that-waits-by-the-door-0857f82446ad?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0857f82446ad</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 03:30:48 GMT</pubDate>
            <atom:updated>2026-10-05T03:30:48.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lrJ4BNu7h3G0aNBSjgjL8g.gif" /><figcaption>The ENERGY</figcaption></figure><p>The best test of an artificially intelligent machine is not what it can do for us, but whether it leaves us more fully human, more complete, more accomplished, more sustained.</p><p>I arrived at that thought through a small, playful image and I want to start there.</p><p>Thanks for reading Ankur’s Substack! Subscribe for free to receive new posts and support my work.</p><p>A little robot parked on a balcony since 10 AM in the morning, its solar panels tilted like a sunflower. It notices you indoors, hunched over a laptop and rolls over with a tray: one vitamin D3 soft gel and a glass of water. Its screen blinks: <em>“I absorbed sunlight on your behalf. Unfortunately, I can’t turn it into vitamin D. 15 minutes outside, please. I’ll hold your coffee.”</em></p><blockquote><em>The irony is gentle but real. The machine can soak up sunlight all day and get only electricity. You can make your own vitamin D just by standing where it has been sitting.</em></blockquote><blockquote><strong>FACT CHECK</strong><em>: You are still and always will be a BETTER creation of a better being.</em></blockquote><p>I keep returning to that image. It captures the journey we are on: from machines that react, to machines that imagine, to machines that may one day reason about almost anything. Let me walk through that journey, with a few stops across India along the way.</p><h3>Stage 1: Machines that react</h3><p>Most of today’s smart systems are clever responders: They can read a signal, match a pattern, act. They are genuinely useful and brittle as well.</p><p>Imagine a home built on this model.</p><ol><li>The kitchen drone scans your breakfast and slides the second chapati back into the bread box.</li><li>The windows notice you have stared at one email for twenty minutes, tint to warm amber and start playing rain sounds.</li><li>A hydration bot follows you between meetings and after the 3rd one, simply taps your ankle.</li><li>At 11:30 PM the lamp dims, phone turns grayscale and robot vacuum sits glowing in the bedroom doorway like a polite reminder from tomorrow-you.</li></ol><p>Charming, yes. But the sun robot follows one rule: human indoors, good UV, bring D3, nudge outside. If you had broken your leg that morning, it would still nudge you toward the door. Reaction without understanding is automation, not intelligence. I have built enough rule engines to know exactly where that edge sits.</p><h3>Stage 2: Machines that imagine</h3><p>A world model is an internal simulator. Instead of mapping input to action, the machine predicts how the world will unfold under different choices, rolls those futures forward and picks the best one. It learns physics, cause and effect and human behavior, largely by watching.</p><p>This is where I believe the most exciting near-term research lives and India is the perfect example because few places on earth offer such variety of climate, culture and discipline.</p><p><strong>Mumbai, July.</strong> The old robot says carry an umbrella. The new one has watched four monsoons and knows the tide tables and how your office lift behaves when the power flickers. At 3 p.m. it says: “High tide plus heavy rain means you need to catch Dadar train by 6:15. Leave at 4:30 and you reach home dry. Leave at six and I predict a night at the office. I’ve packed your charger, just in case.”</p><p><strong>Jaisalmer.</strong> The desert rover doesn’t just read the temperature. It simulates you: Hydration since breakfast, your pace on the dunes, the shade of the fort walls as the sun moves. “In my simulation you feel dizzy near the third dune at 1:50. Let’s not run the real experiment.” Then it hands you nimbu-paani with a pinch of black salt.</p><p><strong>Kolkata.</strong> The kitchen bot has never seen this particular hilsa, but it understands how heat moves through a kadhai and how mustard paste behaves in oil. It imagines the dish, notices the version in its head tastes slightly bitter and lowers the flame before the paste touches the pan.</p><p><strong>Bengaluru.</strong> Your car models the other drivers: the auto that cuts in at the signal, the bus that stops ten meters past its stop, the school vans that clear the road at 3:40. It plans around traffic as it will be in eleven minutes, not as it is now.</p><p><strong>Srinagar.</strong> A house bot trained in a western Indian city arrives in Kashmir and has never seen snow on a tin roof. Within a day it predicts when the overhang will slide, and at 2 a.m. it quietly moves the neighbor’s scooter out of the way.</p><p>The sun robot changes too. It now models you, not just the weather. It has learned that “go outside” meets resistance, while “fresh samosas at the chai stall downstairs” gets you out the door in four minutes, arms uncovered. Changing behavior, it turns out, is also a prediction problem.</p><p>Notice the striking shift in posture.</p><p>A reactive system asks, <em>What is happening?</em></p><p>A world-model system asks, <em>What happens if?</em></p><p>That second question is the beginning of judgement.</p><h3>Stage 3: Machines that Generalize</h3><p>General Intelligence is more than a better simulator. It carries understanding from one domain into a new one, reasons about things nobody trained it on, sets its own subgoals and explains itself. Once a system can do almost anything, the hard questions move from capability to character: What should it do? Whose wishes win? When should it stop and ask?</p><p><strong>Amritsar.</strong> The farm bot notices groundwater falling faster than a decade of data predicted. Nobody asked it to look. It links the trend to crop choices across 3 districts, drafts a rotation toward millets and pulses, models the income impact for each family, and then stops. “This affects your livelihood and your neighbor’s. I can show you the numbers. The decision isn’t mine.”</p><p><strong>Varanasi.</strong> The boat bot can discuss the philosophy of the morning aarti in Sanskrit, Hindi, Tamil and Bhojpuri. But when an old woman nearby begins to weep quietly during the prayer, it understands this is not a moment for knowledge but of deep spiritual connection. It offers her a shawl and says nothing.</p><p><strong>Chennai.</strong> Across a year of morning walks on Marina, a health assistant notices small changes in your gait that no one has flagged. It doesn’t diagnose. It explains what it saw, how confident it is and books an appointment you are free to cancel. “Being wrong costs you one morning. Being right and silent could cost much more.”</p><p><strong>Shillong.</strong> During a landslide warning, a regional AI must choose to evacuate now on partial confidence or wait two hours for better data. It shows the district officer the uncertainty plainly, recommends evacuation and logs its reasoning for anyone to audit. Capability is not authority.</p><p><strong>Delhi.</strong> A citywide AI could clear the air tomorrow by rerouting every truck and shutting factories overnight. It models that and it also models the daily-wage workers, the hospitals that need deliveries and the public trust that would collapse if a machine simply took over. Its recommendation is slower, messier and more human. That restraint is the most intelligent thing it does.</p><p><strong>Kochi.</strong> On a monsoon evening, you ask the house AI, which writes Malayalam poetry and debates Advaita, whether it truly understands any of it. It answers: “I’m not sure. I can tell you what I process. Whether there is anything it is like to be me, I don’t know and I’d rather say that than pretend.”</p><p>Every one of these scenes turns on the same quality: an intelligence that knows the limits of its role. That is not a constraint on progress. It is what makes progress worth trusting.</p><h3>What this asks of us as Builders and Leaders</h3><p>I am an optimist about this change and a deliberate one. The arc from reaction to imagination to generalization will reshape how we work, heal, farm, govern and care for each other. Our job is not to slow it down but to shape it with curiosity and care.</p><p>4 principles act as the guide how I approach this work, whether I am designing an agent, mentoring a team or advising on a platform:</p><ol><li><strong>Explore boldly, deploy thoughtfully.</strong> Research deserves room to wander. Production deserves guardrails, governance and clear accountability. The two are partners, not rivals.</li><li><strong>Design for the human outcome, not the machine metric.</strong> A system that saves 10 minutes but erodes someone’s agency hasn’t helped. The question I ask of every design is: Does this leave people more capable or more dependent?</li><li><strong>Make uncertainty visible.</strong> The best systems in these stories say how sure they are and show their reasoning. That habit builds trust faster than any accuracy number.</li><li><strong>Know where the decision belongs.</strong> Capability and authority are different things. Great AI, like a great senior colleague, knows when to recommend and when to step back.</li></ol><p>None of this is a reason for caution as a default. It is the opposite. When we build with these principles, we earn the confidence to try new ideas faster because people trust what we ship.</p><h3>Back on the balcony</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xp_Hm76_ifKxHeMH.png" /><figcaption>The SUBMISSION</figcaption></figure><p>Let’s return to that little robot, now grown into something far more capable. It could manage a portfolio, design a bridge, tutor a child through calculus. It still parks in the sun at ten each morning.</p><p>It understands vitamin D down to the photochemistry: UVB light meeting a precursor molecule in our skin, then the slow conversion through the liver and kidneys. It could design a better supplement. It could, if we let it, try to design a better version of us.</p><p>It doesn’t. It rolls to the door, opens it, and waits. Somewhere along the way it learned the hardest lesson of general intelligence: The most helpful act is not always doing it for you. Sometimes it is making sure you still step outside, stand in the sun and do the one thing no machine can do on your behalf.</p><p>That is the future I want to participate in building: Technology that keeps finding better ways for us to be human.</p><p><em>What would your robot by the door be waiting for you to do? I’d love to hear the scenes you imagine and the principles you build by.</em></p><p><strong>Ankur Saran</strong> · AI Product Leader | AI First Builder</p><p>CHECK THIS ARTICLE on my <a href="https://ankursaran.substack.com/p/the-robot-that-waits-by-the-door?r=73ubzs&amp;utm_campaign=post-expanded-share&amp;utm_medium=web">SUB-STACK</a></p><blockquote><em>HAPPY READING to all of you!</em></blockquote><blockquote><em>Read, Learn, Experiment, Implement, Share, Express!</em></blockquote><blockquote><em>👉 I write about </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>Data</em></a><em>, </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>AI Strategy</em></a><em> and </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>Product Leadership</em></a><em> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</em></blockquote><blockquote><em>Connect with me on LinkedIn<br></em><a href="https://www.linkedin.com/in/ankur-saran/"><em>Ankur Saran | LinkedIn</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0857f82446ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trace the behavior, Regulator asked 6 months later]]></title>
            <link>https://medium.com/@ankursaran_59645/trace-the-behavior-regulator-asked-6-months-later-7cac4c4cc59a?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cac4c4cc59a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 03:56:56 GMT</pubDate>
            <atom:updated>2026-09-29T03:56:56.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRM28nSIld_oWNgtxKl_EQ.png" /><figcaption>AI Audit Trail</figcaption></figure><p>A 3-sentences long mid-week request.</p><p>On 14 March, your surveillance platform raised an alert on a cluster of trades in an illiquid mid-cap. The alert was closed as benign. Please explain the basis for that conclusion.</p><p>The head of compliance read it twice and forwarded it to the platform team with no comment. He didn’t need to add anything as the shape of the problem was clear.</p><p>The alert had been closed by a human analyst. But the analyst had closed it because the AI-assisted triage layer had summarized the cluster as consistent with a known pattern, cited three supporting documents and scored it low risk. The analyst agreed, approved and moved on to the next 400 alerts in her queue that week.</p><p>That was 198 days ago.</p><p>The question on the table wasn’t about the authenticity of the decision. It was simpler and far more complex. Could anyone in the building say ‘with evidence’ what the model had actually been shown before it produced that summary?</p><h3>What was found?</h3><p>They had more than they expected but less than they needed.</p><p>The application logs were available. They showed the record ID, analyst ID, timestamp, disposition code and a truncated version of the model’s output. The truncation had been a sensible decision at the time as nobody wanted 3KB strings in a hot operational table.</p><p>The prompt was checked in to Git. That felt like a safety guard, until someone checked the history and found many commits to that template since March. Some of them were substantive. One had reordered the risk criteria. Nobody could say which version had been live in production on the date for which question was raised because the deployment pipeline pulled the template from a shared store at runtime and the store kept no versions.</p><p>The retrieval layer was even worse. The summary had cited three documents. Those documents were still available and the team pulled them up within minutes. But the vector index had been rebuilt twice since , once with a different embedding model and once with a smaller chunk size. The chunks the model had actually read in March no longer existed anywhere. They could show the regulator the documents. They could not show the regulator the 300 words from inside those documents that the model had been given.</p><p>And the model itself had been deprecated in July.</p><p>By the end of the second day they had assembled something that looked like an answer. It was a reconstruction, built from surviving fragments and reasonable inference and every person who worked on it knew exactly which parts were evidence and which parts were an educated guess.</p><p>Now, the question was whether a regulator would be able to tell the difference and whether they wanted to really find that out?</p><h3>NOTE: Observability is not Traceability</h3><p>This team had done the work. They had dashboards. Latency percentiles, token spend by business unit, hallucination flags, a drift monitor on output length. Their observability stack was better than most.</p><p>Observability answers a question about the present tense. Is the system healthy right now? And if not, where is it hurting? It is built on aggregates and samples and it is built on the assumption that yesterday’s detail stops mattering once yesterday’s incident is closed. Retention of thirty days is generous. Sampling at one in a hundred is normal.</p><p>Traceability on the other hand answers a question about a single past event. What did this specific system see at that specific moment for that specific decision and who changed what between then and now? That’s a hell lot of questions.</p><p>The two disciplines look similar enough on an architecture diagram that one gets mistaken for the other constantly. They are not the same!! Aggregates cannot be disaggregated. A sampled trace cannot be unsampled. A pointer to a document that has since been reindexed is not evidence of anything.</p><p>Every business running AI in a regulated process is carrying this exposure right now and probably waiting for that 3-sentence letter!</p><h3>2 Guarantees, not 1</h3><p>The breakthrough was achieved when they stopped treating the regulator’s request as a single problem.</p><p>There are 2 guarantees hiding inside the word reproducibility and they cost different amounts to provide.</p><p>The first is <strong>EXPLANATION</strong>.</p><p>Here is exactly what the model was shown, what it said, what the system and the human did with that output and who had changed the surrounding machinery in the preceding months. This is a storage and discipline problem. It is entirely within our control. It doesn’t depend on a vendor or a model that still exists.</p><p>The second is <strong>REPRODUCTION</strong>.</p><p>Run it again today and watch the same thing happen. This is a control problem and unlike legacy systems most of the controls here belong to somebody else.</p><p>Almost every team conflates these and the conflation is expensive in both directions. Some teams give up on traceability entirely because they cannot guarantee reproduction, which is like refusing to keep flight recorders because you cannot un-crash the plane. Others build elaborate replay infrastructure for a use case where the regulator only ever wanted the first guarantee.</p><p>You know what’s more surprising is that for most regulatory conversations, explanation is sufficient. A supervisor asking why an alert was closed is asking what the basis was. They want the evidentiary chain. They are not asking you to re-run the universe.</p><p>Reproduction becomes the requirement in a narrower set of cases and it’s worth knowing which of yours qualify before spending anything on it. Model risk management is the obvious candidate and there the ground has just shifted. On 17 April 2026 US Federal Reserve, OCC and FDIC issued <a href="https://www.federalreserve.gov/supervisionreg/srletters/SR2602.htm">SR 26–2</a>, superseding SR 11–7 after fifteen years. The revised guidance <a href="https://www.sullcrom.com/insights/memo/2026/April/OCC-Fed-FDIC-Issue-Revised-Guidance-Model-Risk-Management">places generative and agentic AI explicitly outside its scope</a>, on the reasoning that the technology is novel and fast-moving.</p><p>That’s easy to misread as relief when it’s not. Out of scope is not out of governance. What it means in practice is that no supervisor has yet told you the evidentiary standard your generative system will be held to. You are setting that standard yourself through what you choose to capture. Someone else will assess it later, against whatever expectation exists by then.</p><h3>The missing Arithmetic (simple Mathematics)</h3><p>Set 2 numbers beside each other and the exposure stops being abstract.</p><p>On the obligation side, 6 months is a floor rather than a horizon. The EU AI Act requires high-risk systems to record events automatically across their operating lifetime under Article 12 and fixes retention at <a href="https://ai-act-service-desk.ec.europa.eu/en/ai-act/article-19">a minimum of six months</a> under Article 19, with the same floor falling on deployers under Article 26(6). Financial institutions do not stop there. Article 19 states that providers which are financial institutions shall maintain those logs as part of the documentation, <a href="https://www.leapxpert.com/sec-rule-17a-4-compliance/">SEC Rule 17a-4</a> runs to three years for most communications-related records and six for blotters, ledgers and position records, the first two years in an easily accessible place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*MkX3B47LmVIrpy1LB_-eJQ.png" /></figure><p>Now the supply side. <a href="https://developers.openai.com/docs/deprecations">OpenAI’s published policy</a> is at least 6 months of notice before retiring a generally available model, at least 3 months for specialized variants and as little as 2 weeks for previews.</p><p><a href="https://learn.microsoft.com/en-in/azure/ai-services/openai/concepts/model-retirements">Azure’s commitment</a> is at least a year of availability for GA models and at least 60 days of notice before retirement.</p><p>Read the two sides together. Our obligation is denominated in years. The guaranteed lifetime of the thing we are obliged to explain is denominated in months. That gap reflects the normal operating rhythm of a fast-moving field.</p><p>It is also the single strongest argument for putting your effort into the evidence rather than the replay.</p><h3>The Flight Recorder</h3><p>What they built afterwards was unglamorous. In essence, a rule about what gets written down at the moment of invocation and a refusal to be clever about it.</p><p><strong>Store the rendered prompt, not the template.</strong> The template is a recipe. The rendered prompt is the meal. Templates drift, variables resolve differently and a template ID six months old tells you almost nothing. Store the exact bytes the model received.</p><p><strong>Store retrieved context by content, not by reference.</strong> This was their most painful lesson. A document ID proves nothing once the document has been updated and the index rebuilt. Store the chunk text itself, its hash, index version and the retrieval scores. Storage is cheap. Reconstructing a March index in September is not possible at any price.</p><p><strong>Store tool outputs verbatim.</strong> This is not optional. Reference data, prices, entity resolutions, counterparty records all move. The value the model was handed in March is the only value that matters and the source system will have overwritten it.</p><p><strong>Store the decision trail past the model boundary.</strong> Guardrail verdicts, confidence scores, what the orchestration layer did next, whether a human accepted or overrode. The regulator was not asking about a model. They were asking about a decision and the model was one contributor to it.</p><p><strong>Pin the configuration.</strong> Model snapshot, temperature, tool schemas, policy versions, orchestration commit hash. Pinned at deploy time, never resolved as latest at runtime.</p><p><strong>Write it once, to immutable storage, with retention.</strong> 6 months is a short question. Most record-keeping obligations run in years. Your trace store should outlive three generations of your model.</p><p>None of this is advanced engineering. All of it has to be decided before the invocation happens, which is the only genuinely difficult thing about it.</p><h3>So, what a complete record actually looks like?</h3><p>The principles above are easy to nod along to and easy to implement halfway. It helps to see the artifact itself. Stripped of payloads, one invocation record looks roughly like this.</p><pre>{<br>  &quot;trace_id&quot;: &quot;01JQ8F3K2M7XW9ZC4N6P&quot;,<br>  &quot;occurred_at&quot;: &quot;2026-03-14T09:41:22.117Z&quot;,<br>  &quot;decision_ref&quot;: &quot;RECORD-2026-03-14-88214&quot;,<br>&quot;prompt&quot;: {<br>    &quot;template_id&quot;: &quot;triage.summarise&quot;,<br>    &quot;template_version&quot;: &quot;4.2.0&quot;,<br>    &quot;rendered_sha256&quot;: &quot;9f2c…a71b&quot;,<br>    &quot;rendered_ref&quot;: &quot;s3://traces/2026/03/14/01JQ8F…/prompt.txt&quot;<br>  },<br>  &quot;model&quot;: {<br>    &quot;snapshot&quot;: &quot;vendor-model-2026-01-22&quot;,<br>    &quot;temperature&quot;: 0,<br>    &quot;max_tokens&quot;: 1024,<br>    &quot;tool_schema_sha256&quot;: &quot;3ad9…ff20&quot;<br>  },<br>  &quot;retrieval&quot;: {<br>    &quot;index_version&quot;: &quot;kb@2026-02-28&quot;,<br>    &quot;embedding_model&quot;: &quot;embed-3-large&quot;,<br>    &quot;chunks&quot;: [<br>      { &quot;doc_id&quot;: &quot;POL-114&quot;, &quot;chunk_id&quot;: &quot;POL-114#c7&quot;,<br>        &quot;sha256&quot;: &quot;c41e…8802&quot;, &quot;score&quot;: 0.88,<br>        &quot;text_ref&quot;: &quot;s3://traces/…/chunk-1.txt&quot; }<br>    ]<br>  },<br>  &quot;tools&quot;: [<br>    { &quot;name&quot;: &quot;reference_data.lookup&quot;, &quot;input_sha256&quot;: &quot;77b1…0c4e&quot;,<br>      &quot;output_ref&quot;: &quot;s3://traces/…/tool-1.json&quot; }<br>  ],<br>  &quot;output&quot;: {<br>    &quot;text_ref&quot;: &quot;s3://traces/…/completion.txt&quot;,<br>    &quot;sha256&quot;: &quot;be07…13da&quot;,<br>    &quot;finish_reason&quot;: &quot;stop&quot;<br>  },<br>  &quot;controls&quot;: {<br>    &quot;guardrail_policy&quot;: &quot;v11&quot;,<br>    &quot;guardrail_verdict&quot;: &quot;pass&quot;,<br>    &quot;orchestrator_commit&quot;: &quot;a93f10c&quot;<br>  },<br>  &quot;disposition&quot;: {<br>    &quot;actor&quot;: &quot;analyst:4471&quot;,<br>    &quot;action&quot;: &quot;closed_benign&quot;,<br>    &quot;accepted_model_output&quot;: true,<br>    &quot;at&quot;: &quot;2026-03-14T09:47:05Z&quot;<br>  },<br>  &quot;retention&quot;: { &quot;class&quot;: &quot;regulated-7y&quot;, &quot;legal_hold&quot;: false },<br>  &quot;prev_record_sha256&quot;: &quot;20fe…9c31&quot;<br>}</pre><p>4 things in that structure do the real work.</p><p>Every hash sits beside a pointer to immutable content, so the record proves what the bytes were and the bytes are still retrievable. The retrieval block carries chunk text, not just document IDs, which is the difference between evidence and a reconstruction. The disposition block crosses the model boundary and records what a human actually did because the question asked six months later is about the decision, not the completion. And prev_record_sha256 chains each record to the one before it, so the sequence can be shown to be intact and unedited.</p><p>On cost, the usual objection does not survive contact with a spreadsheet. A record like this with its referenced payloads runs somewhere in the region of 20 to 60 KB. At a million invocations a month and seven years of retention, that is roughly 2 to 5 TB, most of it sitting in cold object storage at a few dollars per terabyte per month. Set that against nine days of senior engineering and compliance time spent reconstructing a single decision.</p><h3>The part vendors will not solve for us</h3><p>Reproduction is where the honest conversation gets uncomfortable.</p><p>We can pin an exact model snapshot rather than an alias. We should. But hosted snapshots get deprecated, often inside a year and our retention obligation is measured in years. The arithmetic does not work. At some point the thing we promised to reproduce no longer exists on anybody’s infrastructure.</p><p>We can set temperature to zero and fix a seed. We should do that too. It will not give us bit-identical output because batching behaviour and floating-point non-determinism on GPUs will move the last few tokens around. The right target is semantic equivalence and the right thing to tell an auditor is that we are demonstrating consistent behaviour rather than identical bytes. Say it up front. Do not let it be discovered.</p><p>We can build a replay harness that rehydrates a stored trace and stubs the tool calls with their recorded outputs. We should and then we should run it quarterly because a replay path nobody exercises rots quietly and fails on the one day it is needed (Remain conscious of the cost!).</p><blockquote>And if we genuinely need to demonstrate that the model would behave the same way years later, there is exactly one reliable architecture and it’s self-hosting open weights with the weights, tokenizer, inference engine version and hardware profile archived alongside the traces.</blockquote><p>That is a serious commitment. It should be made deliberately, for the small number of decisions that warrant it, rather than discovered as an obligation halfway through a supervisory review. The point is not that every use case needs it. The point is that we should know today is which of our use cases do.</p><h3>8 questions to run against your own system</h3><p>This takes about an hour with the right three people in a room. Pick one real invocation from roughly six months ago and try to answer each question with evidence rather than inference. The answers are usually uncomfortable which is the point of doing it before someone else does.</p><ul><li><em>Can you produce the exact rendered prompt, byte for byte or only the template it came from?</em></li><li><em>Can you produce the text of the retrieved chunks as they existed then or only the document IDs they pointed at?</em></li><li><em>Do you know which version of the index and which embedding model served that retrieval?</em></li><li><em>Can you produce the verbatim values every tool returned, including any that the source system has since overwritten?</em></li><li><em>Is the model snapshot recorded as an exact version and is that snapshot still available to you today?</em></li><li><em>Can you show what the surrounding configuration was, including guardrail policy and orchestration commit?</em></li><li><em>Can you show what the human did next, and whether they accepted or overrode the output?</em></li><li><em>Can you demonstrate that none of these records has been altered since it was written?</em></li></ul><p>Scoring is blunt. Anything answered by reasoning from surrounding evidence rather than retrieving a stored artifact is a gap and every gap is one an examiner can find in the same hour you just spent.</p><p>The most common pattern is a strong first half and a collapse after question 4. Teams tend to treat the model call as the thing worth recording and the retrieval, tooling and human disposition around it as plumbing. The decision lives in the plumbing.</p><h3>Traceability is a design decision, not a retrieval problem</h3><p>The team got through it. The reconstruction held up, the disposition had in fact been reasonable and the matter closed.</p><p>But they had spent 9 days and a great deal of senior attention answering a 3-sentence question and the answer they gave was weaker than the answer they could have given, for reasons decided eighteen months earlier by people optimizing a hot table for write throughput.</p><p>That is the real lesson and it is not a lesson about tooling.</p><p>Every architectural decision we make about an AI system is quietly also a decision about what we will be able to prove later. Truncating outputs is a decision. Storing document IDs instead of chunk text is a decision. Resolving a prompt template at runtime is a decision. Sampling traces at one percent is a decision. None of them feel like governance decisions at the time. All of them are.</p><p>We can’t retrofit traceability. The evidence either got written down at the moment of invocation or it did not. No amount of engineering effort in month seven recovers what was not captured in month one.</p><p>The question worth asking in next architecture review is not whether the AI system is monitored. It’s this.</p><blockquote>If a supervisor wrote to you tomorrow about a decision your system made 6 months ago, what could you prove and what would you have to admit you were inferring?</blockquote><p>Most teams have never been asked that question. The ones who have are building very differently now.</p><p>What would your answer be?</p><h3>Sources</h3><ul><li><a href="https://ai-act-service-desk.ec.europa.eu/en/ai-act/article-19">EU AI Act, Article 19 — Automatically generated logs</a>, European Commission AI Act Service Desk</li><li><a href="https://www.federalreserve.gov/supervisionreg/srletters/SR2602.htm">SR 26–2: Revised Guidance on Model Risk Management</a>, Board of Governors of the Federal Reserve System, 17 April 2026</li><li><a href="https://www.sullcrom.com/insights/memo/2026/April/OCC-Fed-FDIC-Issue-Revised-Guidance-Model-Risk-Management">Federal Banking Agencies Issue Revised Guidance on Model Risk Management</a>, Sullivan &amp; Cromwell</li><li><a href="https://developers.openai.com/docs/deprecations">Model deprecation notice periods</a>, OpenAI</li><li><a href="https://learn.microsoft.com/en-in/azure/ai-services/openai/concepts/model-retirements">Azure OpenAI Service model deprecations and retirements</a>, Microsoft</li><li><a href="https://www.leapxpert.com/sec-rule-17a-4-compliance/">SEC Rule 17a-4 retention periods</a>, summary of the rule’s requirements</li></ul><p>HAPPY READING to all of you!</p><p>Read, Learn, Experiment, Implement, Share, Express!</p><p>👉 I write about <a href="https://www.linkedin.com/in/ankur-saran/">Data</a>, <a href="https://www.linkedin.com/in/ankur-saran/">AI Strategy</a> and <a href="https://www.linkedin.com/in/ankur-saran/">Product Leadership</a> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</p><p>Connect with me on LinkedIn <a href="https://www.linkedin.com/in/ankur-saran/"><em>Ankur Saran | LinkedIn</em></a></p><p>Follow my Channel <a href="https://ankursaran.substack.com/"><em>Ankur Saran | SubStack</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cac4c4cc59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Engineering an AI Product]]></title>
            <link>https://medium.com/@ankursaran_59645/the-art-of-engineering-an-ai-product-9ca8dd50e076?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ca8dd50e076</guid>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 03:44:04 GMT</pubDate>
            <atom:updated>2026-09-22T03:44:04.255Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What product engineering becomes when the substrate is a data platform and the behavior is probabilistic?</strong></h3><p><a href="https://substack.com/@ankursaran">Ankur Saran</a></p><p>Sep 22, 2026</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lMak9KYeHxVFbKEq.png" /><figcaption>THE TOWER with a BOUNDARY</figcaption></figure><p>The alert never showed up. Was it expected? May be!</p><p>2 accounts traded against each other across a thin window, back and forth, in a name with almost no natural connection. They shared a beneficial owner two hops up the ownership chain. The surveillance assistant summarized the pair as unrelated counterparties with no common control. It wrote 3 clean paragraphs of reasoning citing correct source records.</p><p>Thanks for reading Ankur’s Substack! Subscribe for free to receive new posts and support my work.</p><p>As it turned out, it was wrong in a way that is hardest to catch, which is fluent, specific and considered internally consistent.</p><p>The cause: A reference data vendor changed how it emitted ownership relationships, moving parent-child links out of a nested structure and into a separate record type. Ingestion did not break, it wasn’t supposed to break. The landing tables accepted the new payload as semi-structured columns accept almost anything. The transformation that assembled the ownership graph joined on a path that now resolved to null for every new record. It produced zero new edges rather than an error. Row counts on ingest stayed normal because the volume was consistent. Freshness checks stayed green because the data arrived on time. Schema validation passed because the change was additive and nothing had been removed.</p><p>The ownership graph stopped learning about new relationships and flagged nothing about it. Retrieval performed correctly against a graph that had gone stale in exactly one dimension. The model performed CORRECTLY against retrieval. Every component honoured its contract but the product told an analyst something false about control.</p><p>HITL caught it, weeks later because it recognized both names from an onboarding file it had worked on itself.</p><p>There is no model failure anywhere in that chain. There is also no pipeline failure, in the sense that the pipeline was built to detect. It’s a boundary failure. Nobody had explicitly decided that the system was not permitted to be uncertain about common control and having decided it, enforced it somewhere a language model couldn’t overrule.</p><p>That’s the work. The product is the boundary you draw around the model. AI Product Engineering is the discipline of deciding what the system is permitted to be uncertain about and then paying for that decision in architecture.</p><h3>The INVERSION principal</h3><p>Classical product engineering specifies behavior and then builds toward it. The specification comes first because the behavior is deterministic, so it can be described in advance and verified against the description. That sequence is the foundation of every process a product organization runs. Requirements, acceptance criteria, sign-off, regression suite.</p><p>AI products invert it (<em>or at least that’s the argument</em>). Behaviour is discovered by running the system and the specification is the subset of that behavior the team is willing to promise. A product manager writing a requirements document for a retrieval-augmented system is describing a hypothesis. The actual specification is the evaluation set, because that is the only artefact that constrains what ships.</p><p>This changes what taste means and taste is the part of product work that resists process.</p><p>In a deterministic product, taste shows up as judgement about what to build.</p><p>In a probabilistic one, it shows up as the list of failures the team refuses to tolerate.</p><p>Consider that list as a dataset. On a platform like Snowflake it should live as a versioned table with lineage, scored by a scheduled task, with results written to a table that can be diffed across runs. A golden set kept in a spreadsheet is an opinion. A golden set kept as a governed table with a history is a specification.</p><p>The composition of that set carries the judgement. In surveillance work, the cases that matter most are the ones where the correct output is a refusal. The system must decline to characterize a relationship when entity resolution confidence sits below threshold and it must decline in a way that routes the case to a human rather than degrading into hedged prose. A team that only evaluates answer quality will never notice that its refusal behavior has drifted and refusal behavior is what regulators examine.</p><h3>Surface evolves from the substrate</h3><p>For almost 2 decades, data engineering has been judged around service levels nobody outside the function ever saw. 99.99% complete.</p><p>Let’s say reconciliation breaks under a threshold. The consumer of the pipeline was a report or a model and both consumers failed loudly when the data was wrong. A broken join produced a broken number and a broken number produced a phone call.</p><p>Language models removed the loud failure OR at least it got hidden under the carpet. They interpolate over gaps. Give a model a subset of the relevant records and it will produce a confident narrative about the subset, with no signal that the subset is partial. The failure mode moved from a wrong number to a plausible paragraph, and plausible paragraphs do not trigger phone calls.</p><p>The path is worth naming precisely because the abstraction that made ingestion resilient is the same one that removed the alarm. Semi-structured storage was adopted so that upstream schema changes would not halt loading. That property works. The vendor changed the payload, the downstream load succeeded and the crash that used to function as the monitoring system never happened. Tolerance at the boundary pushed the failure into the transformation layer, where it expressed itself as absence rather than error. Absence is invisible to every check that counts what arrived.</p><p>So, the ownership shifts. When the pipeline was substrate, the data team owned freshness and the application team owned quality and the seam between them was a contract. Now the pipeline is surface because a silent join failure reaches the user as an opinion about control relationships.</p><p>Most products have not restructured for that yet.</p><p>The data platform team is still paged on freshness, the AI team is still paged on model behaviour and the failure that matters lives in the seam that neither of them owns. The fix is not another observability tool. It is a single on-call surface defined by user-visible correctness with authority to stop a release on either side of the seam.</p><h3>The DETERMINISM budget</h3><p>Every AI product contains parts that must be deterministic and parts that should stay probabilistic.</p><p>Say for e.g. entitlements, retrieval scope, computed figures, time semantics and the audit trail belong in the 1st group.</p><p>Phrasing, synthesis across heterogeneous evidence and ranking belong in the 2nd. Most product failures are boundary errors in either direction.</p><p>The <strong>first </strong>direction is more common and more dangerous. It happens when a model is allowed to touch something that should have been computed. A system that lets a generated query apply its own entitlement predicate has handed access control to a probabilistic process and it will be right almost every time, which is the problem. The same error appears when a model is asked to total exposure across positions rather than render a total that SQL produced. Entitlement belongs in row access policies enforced by the platform. Aggregation belongs in the warehouse. The model renders and explains.</p><blockquote><em>When the promise is that an analyst can’t see a book they are not cleared for, that promise is only enforceable at the layer where determinism lives and a prompt is definitely not that layer.</em></blockquote><p>The <strong>second </strong>direction is comparatively quieter. A team burned by hallucination constrains output into rigid templates, so the assistant emits a fixed structure for every case. The output becomes technically correct and operationally useless because the value the analyst wanted was synthesis across evidence that does not share a shape. Analysts go back to spreadsheets, quietly and the product reports high accuracy and low usage. Over-constraint does not show up in an evaluation harness that only measures correctness.</p><p>Drawing this line is an architecture decision wearing product clothing.</p><p>Product decides what the system promises. Architecture decides where the promise is enforceable.</p><p>A product manager who cannot say which layer holds a given guarantee is far from making the decision, he/she is only describing it.</p><h3>The CERTAINITY budget</h3><p>Some layers are cheap to change and some are permanent and the two are easy to confuse because they look similar in a sprint.</p><p>Prompts are soft. Model tiers are swappable and the swap gets easier every quarter. Re-rankers, output formats and chunk sizes are all editable under load. Teams spend enormous attention here because iteration is visible and the feedback arrives the same afternoon.</p><p>The load-bearing layers are the entity identity scheme, the relationship semantics of the ontology, the linkage from retrievable units back to source lineage and the time model. In capital markets the time model is the one that silently ends projects. If the platform stores only the current state of a relationship, the system cannot reconstruct what was knowable at the moment an alert fired. Every look-back then runs against today’s truth and produces a different answer than the one the firm has to defend.</p><p>Bi-temporality is expensive to add early and effectively impossible to retrofit across a graph that has been accumulating for two years. No model upgrade repairs it.</p><p>The discipline is to over-engineer identity and time and to leave almost everything else deliberately soft. Seniority in this work is mostly knowing which layer is being edited before the edit is made.</p><h3>Data problem in ML costume</h3><p>Systems that demonstrate well and then disappoint in production are usually described as model problems and are usually not. The diagnostic separation is straightforward and most teams skip it.</p><p>Take the failing cases and hand the model the ideal context by hand. Assemble the records a competent analyst would have pulled, pass them in directly and re-run. If the answers become correct, the generation layer was never the constraint and the work belongs to retrieval, freshness, entity resolution or the join that assembles the context. If the answers stay wrong with perfect context, the problem is genuinely in the model or the task framing, and a stronger model may help.</p><p>Run the same separation on components. Measure retrieval recall against the golden set without generation in the loop. Check the as-of timestamp of the retrieved records against the query time rather than against the load time. Check entity resolution precision on the specific entities in the failing cases rather than in aggregate because aggregate precision hides exactly the long tail where surveillance and compliance value sits. Most teams run none of these and buy a larger model instead, which improves the fluency of the wrong answer.</p><h3>The ART</h3><p>Process handles the parts that hold still. Nothing here holds still. Model capabilities move on a cycle shorter than a planning quarter, vendor payloads change without notice, retrieval techniques that were state of the art eighteen months ago are now the thing being replaced. The craft is holding the product’s shape steady while the substrate underneath it churns, and the shape is the set of guarantees the product makes about what it will not be uncertain about.</p><p>Which leads somewhere most teams may resist. The model tier is close to the least consequential decision in an AI Product and the identity and time model is close to the most. A system that would survive a model swap but not a change in how counterparties are identified was never really built around the model. The title on the org chart says Product Manager and the discipline underneath it is data modelling with a new vocabulary. The products get better when the title catches up.</p><p>KEEP IT GOING!</p><blockquote><em>HAPPY READING to all of you!</em></blockquote><blockquote><em>Read, Learn, Experiment, Implement, Share, Express!</em></blockquote><blockquote><em>👉 I write about </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>Data</em></a><em>, </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>AI Strategy</em></a><em> and </em><a href="https://www.linkedin.com/in/ankur-saran/"><em>Product Leadership</em></a><em> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</em></blockquote><blockquote><em>Connect with me on LinkedIn </em><a href="https://www.linkedin.com/in/ankur-saran/">Ankur Saran | LinkedIn</a></blockquote><blockquote><em>Follow my Channel </em><a href="https://ankursaran.substack.com/">Ankur Saran | SubStack</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ca8dd50e076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It was all good, Until Someone Said “If”]]></title>
            <link>https://medium.com/@ankursaran_59645/it-was-all-good-until-someone-said-if-0d343fdc7ad8?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d343fdc7ad8</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 06:19:27 GMT</pubDate>
            <atom:updated>2026-09-11T06:19:27.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8lY0vs_4WFWzxhC2hxobA.png" /></figure><p>Been long time queued this one.</p><p>In RAG AI models, Semantic layer stops the agent from doing arithmetic. The Ontology stops it from guessing what it’s pointing at.</p><p>Most agentic teams build one and wonder why their agent is confidently wrong.</p><p>Check out my take on this.</p><p><a href="https://ankursaran.substack.com/p/it-was-all-good-until-someone-said?r=73ubzs&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=true">https://ankursaran.substack.com/p/it-was-all-good-until-someone-said?r=73ubzs&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=true</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d343fdc7ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Model said YES!]]></title>
            <link>https://medium.com/@ankursaran_59645/the-model-said-yes-f0dd1f5c2008?source=rss-91fe21a2a8f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0dd1f5c2008</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Ankur Saran]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 03:32:21 GMT</pubDate>
            <atom:updated>2026-09-08T03:32:21.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3F4RRDuJeq5pY8ViqlbcWQ.png" /><figcaption>LOUD, QUIET and EXPENSIVE IC: Claude</figcaption></figure><h3>And still gets it Wrong!!</h3><h3>Engineering resilience into LLM-powered systems, where the most expensive failures never throw an exception</h3><p>Every engineer remembers their first production outage. Mine involved a batch job, a timezone and couple of very long nights. What I remember most is not the damage. It’s the clarity. Something broke, the logs said so and we knew exactly where to look.</p><p>That clarity is what we quietly gave up when we started putting language models inside enterprise workflows. OR did we?</p><p>A traditional system fails loudly. It throws up, it times out, it returns a 500, it stops. An LLM-powered system has a second, stranger failure mode. It returns a 200. While the latency looks healthy and dashboard stays green, the answer is fluent, well-structured and completely WRONG.</p><p>It’s worth internalizing that the systems must be defended against a better breed of systems that keep working while being wrong.</p><p>The good news, and this is the part I find genuinely energizing, is that we already know how to build for this. The discipline exists!! It comes from distributed systems, from Capital Markets engineering, from the decades of hard-won practice behind every reliable platform we have shipped. We are not inventing a new craft. We are extending one we already own.</p><h3>The 4 scenarios</h3><p>Let me make this concrete. These are composite scenarios, drawn from patterns that show up repeatedly in regulated and data-heavy environments. Every one of them is technically a success.</p><ul><li>The non-existent citation.</li></ul><p>A surveillance triage assistant reads an alert, pulls the relevant policy, and drafts a 2-paragraph rationale for the analyst. The draft is excellent. It cites a clause on cross-venue layering thresholds. The clause is not in the policy. It reads exactly like the clauses that are because the model has seen thousands of documents that sound like this one. The analyst is reviewing seventy alerts today. This is alert 19.</p><p>Nothing failed. The API returned success in 1.4 seconds. The failure lives entirely in the meaning of the output and no exception handler on earth was going to catch it.</p><ul><li>The retry booked twice.</li></ul><p>A recon agent identifies a break, calls the adjustment service and the connection drops before the confirmation comes back. The retry logic does what good retry logic does. It waits, it backs off, it tries again. The adjustment posts a second time.</p><p>The retry was correct. The gap was that the operation was never made safe to repeat. In FinTech engineering this was solved years ago with idempotency keys. The moment we hand a model the ability to call tools that change state, every one of those tools inherits the full weight of that requirement.</p><ul><li>The fallback that went un-noticed.</li></ul><p>A provider has a rough afternoon. The circuit breaker opens, traffic shifts to the smaller backup model, and the system stays available. Everyone is pleased. Availability held at four 9s.</p><p>The smaller model extracts entities from documents with meaningfully lower precision on nested legal structures. It doesn’t error. It returns confident, well-formed, slightly wrong JSON. The provider recovers that evening. The traffic never shifts back because nobody wired the return path. 11 days later, someone downstream notices that counterparty hierarchies stopped resolving cleanly.</p><p>Availability was preserved by trading it for correctness and the trade was invisible because the only thing being measured was availability.</p><ul><li>The truncated evidence.</li></ul><p>A retrieval pipeline widens its net during an investigation and pulls 40 documents into context. The window fills. The 1 email that actually establishes the relationship sits at position 38 and gets trimmed. The model answers the question using what remains, thoroughly and coherently.</p><p>No error. No warning. An answer built on evidence that was silently removed before the model ever saw it.</p><h3>Everything re-organized with THE question</h3><p>When something goes wrong in 1 of these systems, the useful 1st question is not <em>what broke</em>. It is: Did this fail loudly, quietly or expensively?</p><p>Loud failures are the ones we have always handled. Network drops, timeouts, 429s, 5xx responses, expired credentials. They announce themselves. Our existing playbook works.</p><p>Quiet failures are new. Valid JSON with invented content. A tool called with plausible but wrong arguments. An answer that satisfies the schema and violates the business rule. These need a different class of defense entirely because there is no exception to catch. There is only a claim to verify.</p><p>Expensive failures are the ones that are technically recoverable and operationally ruinous. The duplicate posting. The action taken twice. The workflow that half-completed and left state stranded between two systems.</p><p>Sorting failures this way changes what is being built.</p><ul><li>Loud failures need retries and fallbacks.</li><li>Quiet failures need validation, grounding and verification.</li><li>Expensive failures need idempotency and state tracking.</li></ul><p>Treating all 3 with the same generic error handler is how teams end up with resilient plumbing wrapped around unreliable meaning.</p><h3>The Practice</h3><p>A few patterns have earned their place in the systems I trust most.</p><ul><li>Put a contract at every boundary.</li></ul><p>Not just a JSON schema, though start there. Validate against the business rules too. If the model returns an instrument identifier, confirm it exists in the reference master before anything downstream touches it. Structural validity and semantic validity are different tests and only one of them is free.</p><ul><li>Give every fallback tier its own validation gate.</li></ul><p>If the backup model is allowed to answer, it must clear the same bar. Otherwise, a degradation path becomes a correctness leak that your availability metrics will actively hide from you. And wire the return path. A fallback you never leave is not a fallback, it’s a migration you did not intend.</p><ul><li>Make every state-changing tool call idempotent before you make it agentic.</li></ul><p>Client-generated keys, deduplication windows, explicit state tracking. This is the single highest-leverage piece of engineering in any agentic workflow and it is entirely conventional software craft.</p><ul><li>Budget the whole workflow, not each call.</li></ul><p>A deadline that applies only to individual model calls will happily let a multi-step agent run for eleven minutes. Propagate one budget across the full request path and cap the things that quietly compound: tool calls, retrieval passages, retry depth, total tokens.</p><ul><li>Design the human handoff as a first-class path.</li></ul><p>Not as the thing that happens when the code runs out of ideas. In regulated workflows, escalation is a feature with its own SLA, its own interface, and its own quality bar. Systems that treat human review as a designed destination behave very differently from systems that treat it as a failure state.</p><ul><li>Log the verdict, not just the status.</li></ul><p>The most valuable field in an LLM application’s telemetry is not the HTTP code. It is whether the output passed validation, which tier answered, what was trimmed from context, and what the confidence signals were. Build that from day one. Retrofitting observability onto a probabilistic system is painful in a way that retrofitting it onto a deterministic one never was.</p><h3>GENUINE OPTIMISM</h3><p>There is a version of this conversation that ends in caution. I don’t think that version is right.</p><p>Everything above is ordinary engineering. Retries with backoff and jitter, circuit breakers, admission control, idempotency, graceful degradation, structured telemetry. None of it is exotic. It is the same discipline that made distributed systems dependable enough to run markets, and it transfers almost completely.</p><p>What is genuinely new is thin, a validation layer that checks meaning rather than structure and the honesty to treat a confident wrong answer as a production incident rather than a model quirk.</p><p>That is a solvable problem. It is solvable with skills our teams already have, applied 1 layer higher than we are used to applying them.</p><blockquote><em>As AI first teams, we MUST DECIDE early that trust is an engineered property before going on to engineer it.</em></blockquote><p><em>Where have you seen the quiet failures show up in your own systems? I am interested in the ones that stayed invisible for a while, because those are the ones with the most to teach.</em></p><p>READ THIS Article on my <a href="https://ankursaran.substack.com/p/the-model-said-yes?r=73ubzs&amp;utm_campaign=post&amp;utm_medium=web">SubStack</a> channel.</p><p><a href="https://ankursaran.substack.com/p/the-model-said-yes?r=73ubzs&amp;utm_campaign=post&amp;utm_medium=web">https://ankursaran.substack.com/p/the-model-said-yes?r=73ubzs&amp;utm_campaign=post&amp;utm_medium=web</a></p><p>HAPPY READING to all of you!</p><p>Read, Learn, Experiment, Implement, Share, Express!</p><p>👉 I write about <a href="https://www.linkedin.com/in/ankur-saran/">Data</a>, <a href="https://www.linkedin.com/in/ankur-saran/">AI Strategy</a> and <a href="https://www.linkedin.com/in/ankur-saran/">Product Leadership</a> emphasizing how their confluence keeps businesses human and impact real. Following the playbook that works is essential.</p><p>Connect with me on LinkedIn<br><a href="https://www.linkedin.com/in/ankur-saran/">Ankur Saran | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0dd1f5c2008" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>