<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://sohaib-hasan.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://sohaib-hasan.github.io/" rel="alternate" type="text/html" /><updated>2026-12-04T13:17:23+00:00</updated><id>https://sohaib-hasan.github.io/feed.xml</id><title type="html">Sohaib Hasan</title><subtitle>Mathematics, AI Reasoning &amp; PlotLab</subtitle><entry><title type="html">The Blindfolded Hike That Explains How Machines Learn</title><link href="https://sohaib-hasan.github.io/blog/gradient-descent/" rel="alternate" type="text/html" title="The Blindfolded Hike That Explains How Machines Learn" /><published>2026-11-06T00:00:00+00:00</published><updated>2026-11-06T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/gradient-descent</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/gradient-descent/"><![CDATA[<p>Picture this: someone blindfolds you halfway up a hillside and asks you to find the lowest point. You cannot see a thing. All you can do is feel which way the ground tilts under your shoes, take one step, and feel again.</p>

<p>That exact walk is what every machine learning model performs, over and over, while it is being trained. Its hillside is just built out of numbers instead of rocks and grass. By the end of this post you will know how that walk works, why the size of each step can make or break it, and why mathematicians can actually prove, not just hope, that the walk ends at the bottom.</p>

<p><img src="/images/gradient-descent-1-scene.png" alt="A blindfolded figure using a walking stick descends a dark hillside at night, following a trail of footprints toward a glowing marker at the valley floor" />
<em>The same blind walk every learning model performs, just with numbers instead of rocks and grass.</em></p>

<h2 id="what-does-it-mean-for-a-machine-to-get-it-wrong">What does it mean for a machine to “get it wrong”?</h2>

<p>Say you are building a model to guess house prices. You feed it a house, and it spits out a number: maybe $300,000. The real price was $340,000. Your model was wrong by $40,000.</p>

<p>Mathematicians give that wrongness a name: a loss function, sometimes called a cost function. It is simply one number that says how bad the current guess is. Zero would mean a perfect guess. The bigger the number, the worse the guess.</p>

<p>Now stretch that idea out. A model’s guess is controlled by many adjustable numbers inside it, called parameters (you may also hear them called weights). Change the parameters, and the guess changes. Learning means searching for the set of parameters that makes the loss as small as possible, across every house the model has ever seen.</p>

<p>Here is the connection to our hillside. Imagine plotting the loss on a graph, with height representing how wrong the model currently is. Tall places are bad guesses. The lowest point is the best possible guess the model can make. That shape, that imaginary hillside built entirely out of right and wrong guesses, is the hill you are blindfolded on.</p>

<p>So what is the “slope under your feet”? It is called the gradient: a simple measure of which direction makes the loss grow fastest, and by how much. Walking in the opposite direction, downhill, is how you make the loss smaller.</p>

<p>Put that together and you get the whole idea in one sentence. Gradient descent means: feel the slope, step downhill, feel again, repeat, until you cannot go down any further.</p>

<h2 id="why-the-size-of-your-step-decides-everything">Why the size of your step decides everything</h2>

<p>Here is where it gets interesting. Suppose you take tiny, cautious steps down that blindfolded hill. You are completely safe. You will also be out there for a very long time, because each step barely moves you.</p>

<p>Now suppose you take giant, confident strides instead. You might stride right past the lowest point of the valley and land partway up the opposite wall, further from the bottom than when you started. Take another giant stride back, and you might overshoot again, bouncing from wall to wall and never settling anywhere.</p>

<p>Mathematicians call the size of each step the learning rate. Picking it well is one of the most important decisions in training any model.</p>

<p><img src="/images/gradient-descent-2-step-size.png" alt="Line chart comparing three learning rates in gradient descent: a small step size crawling slowly toward zero, a well chosen step size settling quickly, and a large step size bouncing to larger and larger values with each step" />
<em>The exact same hill, three different step sizes, three very different endings.</em></p>

<p>I generated the chart above from a real, computed example, starting five units from the bottom in each case. With a step size of 0.05, the walker is still almost two units away after ten whole steps: safe, but painfully slow. With a step size of 0.30, it settles close to the bottom in about five steps. With a step size of 1.05, it does not settle at all. It swings from one side of the valley to the other, and each swing is bigger than the last.</p>

<p>That last line is the surprising part. A step size that is too large does not just fail to help. It can leave your model in a worse spot than before it ever started learning.</p>

<style>
.gd{margin:2.2rem 0;padding:1.15rem 1.15rem 1.25rem;border:1px solid var(--line);border-radius:var(--r);background:linear-gradient(180deg,rgba(243,238,226,.05),rgba(243,238,226,.018));color:var(--chalk-dim);font-size:1rem;line-height:1.5}
.gd-title{font:400 1.12rem/1.2 var(--f-caps);text-transform:lowercase;letter-spacing:.07em;color:var(--ink);margin-bottom:.2rem}
.gd-sub{font-size:.93rem;color:var(--chalk-faint);margin-bottom:.85rem}
.gd canvas{display:block;width:100%;border-radius:8px;background:var(--bg-deep);border:1px solid var(--line)}
.gd-row{display:flex;flex-wrap:wrap;align-items:center;gap:.6rem 1rem;margin-top:.95rem}
.gd label{font:400 1rem/1 var(--f-caps);text-transform:lowercase;letter-spacing:.07em;color:var(--ink)}
.gd output{min-width:2.6em;color:var(--gold);font:500 1.05rem/1 var(--f-body);font-variant-numeric:tabular-nums}
.gd input[type=range]{flex:1 1 180px;min-width:150px;height:28px;accent-color:#ecb44e}
.gd button{padding:.6rem .85rem;border:1px solid var(--line-strong);border-radius:7px;background:transparent;color:var(--chalk);font:500 .88rem/1 var(--f-body);cursor:pointer;transition:border-color .2s,color .2s,background-color .2s}
.gd button:hover{border-color:var(--gold);color:var(--gold)}
.gd button[aria-pressed=true]{border-color:var(--gold);color:var(--gold);background:rgba(236,180,78,.08)}
.gd button.go{border-color:var(--gold);background:linear-gradient(180deg,var(--gold-hi),var(--gold));color:#1a1405}
.gd button.go:hover{color:#1a1405;filter:brightness(1.06)}
.gd button:disabled{opacity:.5;cursor:default}
.gd-read{min-height:3.2em;margin-top:.95rem;font-size:.97rem;color:var(--chalk-dim)}
.gd-read b{color:var(--chalk);font-weight:600}
</style>

<div class="gd" id="gd">
<div class="gd-title">Try it yourself</div>
<div class="gd-sub">The same hill as the chart above, with the walker starting five units from the bottom. Drag the step size and watch where each step lands.</div>
<canvas id="gd-cv" role="img" aria-label="A bowl-shaped hill with the walker's twelve steps marked as dots. The path changes as the step size changes."></canvas>
<div class="gd-row"><label for="gd-lr">Step size</label><output id="gd-out" for="gd-lr">0.30</output><input id="gd-lr" type="range" min="0.01" max="1.2" step="0.01" value="0.30" /></div>
<div class="gd-row"><button type="button" data-lr="0.05">0.05 · slow</button><button type="button" data-lr="0.3">0.30 · just right</button><button type="button" data-lr="1.05">1.05 · too big</button><button type="button" class="go" id="gd-walk">Walk it</button></div>
<div class="gd-read" id="gd-read" role="status" aria-live="polite"></div>
</div>
<script>
(function(){
  var cv=document.getElementById('gd-cv');
  if(!cv||!cv.getContext)return;
  var lr=document.getElementById('gd-lr'),out=document.getElementById('gd-out'),read=document.getElementById('gd-read'),walk=document.getElementById('gd-walk');
  var box=document.getElementById('gd'),btns=box.querySelectorAll('button[data-lr]'),ctx=cv.getContext('2d');
  var reduce=window.matchMedia&&matchMedia('(prefers-reduced-motion: reduce)').matches;
  var N=12,X0=5,R=6.5,YM=42,shown=N,timer=0,W=0,H=0;
  var css=getComputedStyle(document.documentElement);
  function tok(n,d){return (css.getPropertyValue(n)||'').trim()||d;}
  var GOLD=tok('--gold','#ecb44e'),BLUE=tok('--blue','#58c4dd'),DIM=tok('--chalk-faint','#97a89d'),LINE=tok('--line-strong','rgba(243,238,226,.22)'),CHALK=tok('--chalk','#f3eee2'),FONT=getComputedStyle(box).fontFamily;
  if(reduce)walk.hidden=true;
  function path(a){var p=[X0],x=X0,i;for(i=0;i<N;i++){x=x-a*2*x;p.push(x);}return p;}
  function size(){
    var d=window.devicePixelRatio||1;
    W=Math.round(cv.getBoundingClientRect().width)||320;
    H=Math.max(210,Math.round(W*.46));
    cv.style.height=H+'px';cv.width=Math.round(W*d);cv.height=Math.round(H*d);ctx.setTransform(d,0,0,d,0,0);
  }
  function px(x){return 16+(x+R)/(2*R)*(W-32);}
  function py(y){return H-28-Math.min(y,YM)/YM*(H-46);}
  function out_(x){return Math.abs(x)>R;}
  function draw(){
    var a=+lr.value,p=path(a),k=Math.min(shown,N),i,x;
    ctx.clearRect(0,0,W,H);
    ctx.strokeStyle=LINE;ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(16,py(0)+.5);ctx.lineTo(W-16,py(0)+.5);ctx.stroke();
    ctx.strokeStyle=GOLD;ctx.lineWidth=2.4;ctx.beginPath();
    for(i=0;i<=120;i++){x=-R+i*2*R/120;if(i)ctx.lineTo(px(x),py(x*x));else ctx.moveTo(px(x),py(x*x));}
    ctx.stroke();
    ctx.fillStyle=DIM;ctx.font='13px '+FONT;ctx.textAlign='center';ctx.fillText('bottom',px(0),H-8);
    ctx.strokeStyle=BLUE;ctx.lineWidth=1.6;ctx.setLineDash([5,4]);ctx.beginPath();
    for(i=0;i<=k;i++){
      if(i&&out_(p[i-1])&&out_(p[i]))break;
      if(i)ctx.lineTo(px(p[i]),py(p[i]*p[i]));else ctx.moveTo(px(p[i]),py(p[i]*p[i]));
    }
    ctx.stroke();ctx.setLineDash([]);
    for(i=0;i<=k;i++){
      if(out_(p[i]))continue;
      var X=px(p[i]),Y=py(p[i]*p[i]);
      ctx.beginPath();ctx.arc(X,Y,i===k?6.5:4.5,0,6.2832);
      if(i===0){ctx.fillStyle='#0a1310';ctx.fill();ctx.strokeStyle=CHALK;ctx.lineWidth=1.8;ctx.stroke();}
      else{ctx.fillStyle=i===k?GOLD:BLUE;ctx.fill();}
    }
    if(!out_(p[0])){ctx.fillStyle=CHALK;ctx.font='13px '+FONT;ctx.textAlign='left';ctx.fillText('start',px(X0)+10,py(X0*X0)-8);}
    if(out_(p[k])){ctx.fillStyle=GOLD;ctx.font='600 13px '+FONT;ctx.textAlign=p[k]>0?'right':'left';ctx.fillText(p[k]>0?'off the hill →':'← off the hill',p[k]>0?W-18:18,24);}
  }
  function say(){
    var a=+lr.value,p=path(a),r=Math.abs(1-2*a),k=Math.min(shown,N),d=Math.abs(p[k]),dist,v;
    dist=d>=10000?'more than 10,000':d>=100?d.toFixed(0):d<.005?'0.00':d.toFixed(2);
    if(r<.02)v='This step size lands exactly on the bottom in a single step.';
    else if(r>=.999&&r<=1.001)v='The walker bounces between two spots forever and never settles.';
    else if(r>1)v='Every step lands farther away than the last. The walker never settles.';
    else if(r>.8)v=a>.5?'It bounces from side to side and shrinks very slowly.':'Safe, but slow. Twelve steps are not enough to get close.';
    else if(a>.5)v='It overshoots the bottom every time, but each bounce is smaller, so it does settle.';
    else v='It settles close to the bottom within a few steps.';
    read.innerHTML='After <b>'+k+'</b> '+(k===1?'step':'steps')+' the walker is <b>'+dist+'</b> units from the bottom. '+v;
  }
  function stop(){if(timer){clearInterval(timer);timer=0;}walk.disabled=false;}
  function update(){
    stop();shown=N;out.textContent=(+lr.value).toFixed(2);
    for(var i=0;i<btns.length;i++)btns[i].setAttribute('aria-pressed',Math.abs(+btns[i].getAttribute('data-lr')-lr.value)<.005?'true':'false');
    draw();say();
  }
  lr.addEventListener('input',update);
  for(var b=0;b<btns.length;b++)btns[b].addEventListener('click',function(){lr.value=this.getAttribute('data-lr');update();});
  walk.addEventListener('click',function(){
    if(reduce)return;
    stop();shown=0;walk.disabled=true;draw();say();
    timer=setInterval(function(){shown++;draw();say();if(shown>=N)stop();},420);
  });
  function resize(){size();draw();}
  if('ResizeObserver' in window)new ResizeObserver(resize).observe(cv);else window.addEventListener('resize',resize);
  size();update();
})();
</script>

<h2 id="when-my-own-students-could-not-picture-this-hill-i-built-one">When my own students could not picture this hill, I built one</h2>

<p>I teach advanced mathematics and statistics, and gradient descent is one of those ideas that sounds simple on a whiteboard and still leaves students stuck. No matter how carefully I wrote out the equations, some of them could not picture an actual hillside made of numbers, a walker feeling their way down it, or what a “proof” about that walk even looks like.</p>

<p>So I animated it. Using Manim, the same animation engine behind 3Blue1Brown’s videos, I built a full visual proof of exactly how fast gradient descent is guaranteed to converge, worked through on a real example from start to finish.</p>

<p><img src="/images/gradient-descent-3-proof.png" alt="PLACEHOLDER: a frame from the Manim animation showing the walker descending the valley, captured by Sohaib from his own render" />
<em>A frame from the full animated proof below.</em></p>

<p>Watch the full explanation: Gradient Descent Convergence Explained, Why Does It Actually Converge?</p>

<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;max-width:100%;">
<iframe src="https://www.youtube.com/embed/kzVR-1mnQOI" title="Gradient Descent Convergence Explained: Why Does It Actually Converge?" loading="lazy" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allowfullscreen=""></iframe>
</div>

<h2 id="for-those-who-like-the-math">For those who like the math</h2>

<p>This part is optional. If you are happy knowing “feel the slope, step downhill, repeat,” skip straight to the next section.</p>

<p>In the video above, the walker starts exactly 4 units from the bottom of the valley. The hill has a special property mathematicians call smooth: its slope never changes more sharply than a fixed rate, called L. Here, L happens to equal 1, so the step size that is mathematically guaranteed to be safe is also 1.</p>

\[\text{next guess} = \text{current guess} - (\text{step size}) \times (\text{slope at current guess})\]

<p>Walk it out with real numbers, and the walker’s position goes 4, then 3, then 2, then 1, then 0: the very bottom, reached in exactly four steps. After each step, here is how far above the bottom (how wrong the model still is) the walker stood: 2.5, then 1.5, then 0.5, then 0.</p>

<p>Here is the part that turns this from an observation into a guarantee. Because the hill is smooth, and shaped like a single bowl with only one lowest point (a property called convex), mathematicians can prove a hard ceiling on the mistake after any number of steps k. For this starting point, that ceiling is 8 divided by k.</p>

\[\text{mistake after } k \text{ steps} \;\le\; \frac{8}{k}\]

<p><img src="/images/gradient-descent-4-guarantee.png" alt="Chart showing the guaranteed error bound of eight divided by k as a smooth gold curve, with the four actual error values from the worked example, 2.5, 1.5, 0.5 and 0, plotted as dots safely underneath it at each step" />
<em>The guarantee holds exactly as promised, in every single step of the real example above.</em></p>

<p>Notice the shape of that ceiling. It decays like “one over k,” which has a plain-language meaning worth sitting with: to make your mistake ten times smaller, you generally need about ten times more steps. Early steps buy you a lot of improvement cheaply. Later steps buy you less and less for the same effort, the same way the first few hours of practicing a new skill improve you faster than the hundredth hour does.</p>

<p>This is not a new invention, either. The French mathematician Augustin-Louis Cauchy described this exact walk in a short note in 1847, while trying to calculate the orbit of a star using algebra instead of solving much harder equations by hand. Almost two centuries later, a direct descendant of that same walk, called stochastic gradient descent, has become the basic method used to train most of today’s deep learning models: feel the slope, take a safe-sized step, repeat.</p>

<h2 id="what-this-walk-cannot-promise-you">What this walk cannot promise you</h2>

<p>To keep this honest: real machine learning hills are rarely as tidy as the one in our example.</p>

<p>Many real loss functions are not shaped like one clean bowl. They can have several dips, and a model can wander into a shallow one, call it “the bottom,” and stop there, even though a deeper valley exists somewhere else. Mathematicians call a dip like this a local minimum, and escaping one is a hard problem even for experienced engineers.</p>

<p>Picking the perfect step size the way we did above, using a clean formula, only works because our example was simple enough to compute L exactly. Real models usually cannot do that, so the learning rate is chosen through testing and experience rather than a formula.</p>

<p>And a real model’s hill is not one dimensional. It has one direction for every parameter inside the model, sometimes millions of them. Plain gradient descent still works in that setting, but most modern training uses smarter cousins of this idea, built to handle that scale more quickly and stably.</p>

<h2 id="back-on-the-hillside">Back on the hillside</h2>

<p>Picture that blindfolded walk one more time. Whatever hill you are standing on, predicting a price, recognizing a face in a photo, finishing a sentence, the walk never changes. Feel the slope. Take a step sized carefully enough to be safe. Feel again. Repeat.</p>

<p>Every model that has ever learned anything has done nothing more than take small, careful steps downhill until it could not go any lower.</p>

<p><strong>Words used in this post</strong></p>

<ul>
  <li><strong>Gradient descent:</strong> a method for finding the lowest point of a hill of numbers by repeatedly stepping downhill.</li>
  <li><strong>Loss function (cost function):</strong> a single number that measures how wrong a model’s current guess is.</li>
  <li><strong>Parameter (weight):</strong> one of the adjustable numbers inside a model that changes its guesses.</li>
  <li><strong>Learning rate:</strong> how big a step the model takes downhill at each try.</li>
  <li><strong>Local minimum:</strong> a dip in the hill that looks like the bottom but is not the lowest point overall.</li>
  <li><strong>Convergence:</strong> the point where the steps stop improving the guess by any meaningful amount, because the model has reached (or is very close to) the bottom.</li>
  <li><strong>Convex:</strong> shaped like a single smooth bowl, with exactly one lowest point.</li>
</ul>

<p><strong>Need an idea like this explained visually?</strong> If your thesis defense, research paper, or machine learning course has a concept like gradient descent that keeps losing people on a static slide, I build clear Manim animations like the one in this post, every symbol explained, every step visible, nothing rushed. The video above is an example of exactly that kind of work. Send me the idea, who will watch it, and where it will be shown, through my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page, and I will tell you how I would animate it.</p>

<hr />

<p><strong>About the author</strong></p>

<p>I’m Sohaib Hasan. I have 9+ years of teaching experience in advanced mathematics and statistics, and I’m currently a section leader for Stanford’s Probability for AI course, selected out of more than 2,700 participants from over 70 countries to teach students from around the world. After each class, I explain the same ideas again through Manim animations, and I’m glad that Stanford professors and fellow section leaders have appreciated them.</p>

<p>I share these animations on my YouTube channel, <a href="https://www.youtube.com/@PlotLabAlgorithms">PlotLab Algorithms</a>, where I teach data science, machine learning, cryptography, math, DSA and statistics visually, in the style made popular by 3Blue1Brown. Shorter clips live on <a href="https://web.facebook.com/plotlab1/reels/">Facebook</a> (85K+ followers) and <a href="https://www.instagram.com/plotlab01/">Instagram</a> (15K+ followers).</p>

<p><strong>Want an animation like this for your own work?</strong> If you have a project, a research article, a thesis defense, a YouTube video, or any idea that is hard to explain with slides alone, I can turn it into a clear, professional animation. Reach out through my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page and tell me what you are working on. If you would rather learn to build animations yourself, start with my <a href="https://plotlab1.gumroad.com/l/manim_guide_handbook">Manim CE Beginner’s Handbook</a>.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Picture this: someone blindfolds you halfway up a hillside and asks you to find the lowest point. You cannot see a thing. All you can do is feel which way the ground tilts under your shoes, take one step, and feel again.]]></summary></entry><entry><title type="html">Every AI Answer Is a Bet: What I Learned Teaching Stanford’s Probability for AI</title><link href="https://sohaib-hasan.github.io/blog/every-ai-answer-is-a-bet-teaching-stanford-probability-for-ai/" rel="alternate" type="text/html" title="Every AI Answer Is a Bet: What I Learned Teaching Stanford’s Probability for AI" /><published>2026-10-24T00:00:00+00:00</published><updated>2026-10-24T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/every-ai-answer-is-a-bet-teaching-stanford-probability-for-ai</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/every-ai-answer-is-a-bet-teaching-stanford-probability-for-ai/"><![CDATA[<p>Ask an AI a question and watch the words arrive, one after another. It feels like the machine is looking something up. It is not. At every step, the model is placing a bet. Given everything written so far, it assigns a probability to each possible next word, picks one, and moves on. The paragraph you finally read is a chain of weighted guesses, and the quality of the whole answer depends on how well those guesses were calibrated. It is also why asking the same question twice can give you two different answers.</p>

<p>If that sounds strange, it should. We are used to computers being certain. A calculator never hesitates over 7 times 8. But the systems now writing our emails, reading our medical scans and ranking our search results work differently. They live inside uncertainty, and the mathematics of living inside uncertainty is probability.</p>

<p>That is why a Stanford course called Probability for AI exists, and why I am proud to be a small part of it.</p>

<h2 id="the-course-in-one-paragraph">The Course in One Paragraph</h2>

<p><a href="https://pai.stanford.edu">Probability for AI</a> is a free online course created by Chris Piech, an Assistant Professor (Teaching) of Computer Science at Stanford and a Faculty Affiliate of Stanford HAI, the university’s institute for human-centered AI (<a href="https://profiles.stanford.edu/christopher-piech">his Stanford profile</a>). Piech describes it as a course that teaches you “the math language that AI speaks.” Stanford HAI describes it as a <a href="https://x.com/StanfordHAI/status/2099882630418485584">six-week program</a> for anyone who wants to understand how AI works, not just how to use it, with no prerequisites and no experience needed.</p>

<p>I like that framing, because “not just how to use it” is the whole point. Anyone can type a prompt. Understanding why an answer came out the way it did, why it is sometimes confidently wrong, and how much to trust it, requires the language of probability. And although the course welcomes beginners, it does not stay shallow. In my section, we go deep into how probability actually does its work inside AI.</p>

<h2 id="how-i-ended-up-in-the-room">How I Ended Up in the Room</h2>

<p>I was selected as a section leader out of more than 2,700 participants from over 70 countries. A section is a small group where students work through the week’s ideas together and get to ask questions. Mine is made up of working professionals and technologists from around the world.</p>

<p>I will be honest about what this takes. I do it alongside a full-time job and all the usual weight of daily responsibilities, and it asks for real effort every single week. But I am enjoying this journey seriously, and being trusted to teach in a Stanford course is an honor I do not take lightly.</p>

<h2 id="one-question-that-shows-why-probability-matters">One Question That Shows Why Probability Matters</h2>

<p>Before I tell you about the weeks themselves, try this one. It is the kind of question the course trains you to answer correctly.</p>

<p>A medical screening test catches 95 percent of people who have a certain condition. It also gives a false alarm for 5 percent of healthy people. The condition affects 1 percent of the population. You take the test and it comes back positive. What is the chance you actually have the condition?</p>

<p>Most people say about 95 percent. The real answer is about 16 percent.</p>

<p>Here is why. Imagine 10,000 people. Of them, 100 have the condition and 95 of those test positive. Of the 9,900 healthy people, 5 percent, which is 495, also test positive. So among the 590 people with a positive result, only 95 are truly sick. That is roughly one in six.</p>

<p>Nothing in that calculation is advanced. Yet our intuition gets it badly wrong, and the same mistake hides inside AI systems that flag fraud, detect disease or screen applicants. Learning to think this way is not a luxury for mathematicians. It is basic literacy for anyone who will live alongside AI.</p>

<h2 id="week-1-same-prompt-twice">Week 1: Same Prompt, Twice</h2>

<p>Week 1 opened with something every AI user has quietly noticed: ask the same question twice and you may get two different answers. Why?</p>

<p>In our section, we explored it with a toy language model small enough to hold in your head. Give it the prompt “A sleepy robot dreams about” and it has exactly five possible outputs: electric sheep (44 percent), counting stars (20), sample spaces (14), counting outcomes (13) and robot puppies (9). Each call picks one at random, independently of the last.</p>

<p>So what is the chance that two calls give two different outputs? Three simple rules are enough: NOT, OR and AND. The chance that both calls give the same output is the sum of each output’s probability squared, which comes to 0.2782. The chance of two different outputs is 1 minus that, about 72 percent. Even a model with a clear favorite disagrees with itself most of the time.</p>

<p>Then came a question that catches almost everyone. “Robot puppies” appears with a 9 percent chance on each call. How many calls until you are more likely than not to see it at least once? The tempting answer adds the chances: six calls, 6 times 9 percent, is 54 percent. But those chances overlap, so adding them overcounts. The right way is to ask for the chance of never seeing it. That is 0.91 on each call, so 0.91 multiplied by itself n times. After six calls the real chance is only 43 percent. It takes eight calls to pass 50 percent.</p>

<p>Finally, we met the dial that every AI tool hides behind a slider: temperature. It raises each probability to the power 1/T and rescales them so they add up to 1. Look at the first word the model writes. “Electric” starts at 44 percent. Turn the temperature down to 0.5 and it climbs to about 59 percent, while “robot” shrinks from 9 percent to about 2.5 percent. Two calls now start with the same word about 46 percent of the time, up from 33 percent. Turn the temperature up to 2 and the chances even out: “electric” falls to about 35 percent, “robot” rises to about 16 percent, and two calls match only about 27 percent of the time.</p>

<p>The randomness setting in an AI tool is not magic. It is probability, rescaled.</p>

<p>I turned this section into a detailed solutions PDF with every step worked out, and a Manim animation so that students could revisit the ideas at their own pace, long after the live session ended.</p>

<h2 id="week-2-the-palpatine-poll">Week 2: The Palpatine Poll</h2>

<p>In Week 2, our section centered on a problem called the Palpatine Poll, and it was my favorite kind of problem: simple mathematics wrapped around a clever idea.</p>

<p>The question is how you measure something people will not say out loud. Suppose you want to know what fraction of people hold an unpopular or embarrassing opinion. If you ask directly, many will hide the truth. The trick is called a list experiment. Split people into two groups. Show the first group a list of a few harmless statements and ask only how many they agree with, never which ones. Show the second group the same list with one sensitive statement added, and ask the same question. Nobody reveals a single individual answer, yet the second group’s average count comes out higher, and that gap estimates how many people agree with the sensitive statement.</p>

<p>Underneath this trick sit two of the most useful ideas in probability. A single yes or no answer is a Bernoulli random variable, the simplest random event there is. Add up many of them and you get a binomial distribution, which tells you not only the expected count but also how much it is likely to wobble from one group of people to the next. That wobble is what separates a trustworthy estimate from a lucky one.</p>

<p>Here is where AI enters. Every time a team reports that a model is “90 percent accurate,” they are reporting a binomial experiment: run the model on n test examples and count how many it gets right. Treat each test example as an independent trial with a 90 percent chance of success. On 100 examples, the number correct will land anywhere from about 84 to 96 in roughly 97 out of 100 runs. On 10,000 examples, the same model will land within about 0.6 of a percentage point of 90 percent, about 95 percent of the time.</p>

<p>Same model, same skill, wildly different certainty. Whether a headline number deserves your trust depends on a calculation most people never see.</p>

<h2 id="making-the-hard-parts-visible">Making the Hard Parts Visible</h2>

<p>After each week, I do something extra. I write a detailed solutions PDF, and I build a Manim animation that shows the idea moving, not just written down. After Weeks 1 and 2, I shared both with my students and posted them on the section leaders’ forum so that every section leader could use them too.</p>

<p>The reaction was the best surprise of the whole experience. Prof. Chris Piech replied to my post, calling a Manim video for Week 2 a real gift to students and to every section leader in the course, and a fellow section leader added kind words as well.</p>

<!-- ADD YOUR SCREENSHOT: save the image as /images/chris-piech-comment.png in your site folder (crop to the post and comments, blur anyone else's name or photo if you prefer). The line below will then display it. -->
<p><img src="/images/chris-piech-comment.png" alt="Prof. Chris Piech's reply to my Manim animation for Week 2 of Probability for AI" /></p>

<p>I mention this less to celebrate than to make a point about how hard ideas actually get learned. A formula on a slide asks you to trust it. An animation lets you watch the reason. When a binomial distribution widens and narrows as you change the number of trials, it stops being a symbol and becomes something you have seen. That has been true in my own classroom as well, and it is why I animate everything I can.</p>

<p>If you want to explore the material yourself:</p>

<ul>
  <li><strong>Detailed PDFs for Week 1 and Week 2:</strong> <a href="https://drive.google.com/drive/folders/1iwzGMDo9XQ4w8h1BXhQzgaGV9Zx0O4pO?usp=sharing">open the folder</a></li>
  <li><strong>The animation playlist:</strong> <a href="https://www.youtube.com/playlist?list=PLUR1g6hiXfoQ">Stanford Probability for AI on YouTube</a></li>
</ul>

<h2 id="what-i-am-taking-away">What I Am Taking Away</h2>

<p>Teaching this course has changed how I read AI headlines. When I see that a model is “accurate,” I ask how many examples it was tested on. When a system is described as “confident,” I ask whether that confidence is calibrated. When someone says an AI “knows” something, I remember that it placed a bet.</p>

<p>That habit of asking is worth more than any single formula, and you do not need to be a mathematician to build it. You need a good teacher, a few well chosen examples, and the patience to look at an idea until it moves. If you want to see where this course lives, it is at <a href="https://pai.stanford.edu">pai.stanford.edu</a>.</p>

<hr />

<p><strong>About the author</strong></p>

<p>I’m Sohaib Hasan. I have 9+ years of teaching experience in advanced mathematics and statistics, and I turn the ideas I teach into Manim animations, the kind that Prof. Chris Piech and fellow section leaders of Stanford’s Probability for AI have appreciated.</p>

<p>I share these animations on my YouTube channel, <a href="https://www.youtube.com/@PlotLabAlgorithms">PlotLab Algorithms</a>, where I teach data science, machine learning, cryptography, math, DSA and statistics visually, in the style made popular by 3Blue1Brown. Shorter clips live on <a href="https://web.facebook.com/plotlab1/reels/">Facebook</a> (85K+ followers) and <a href="https://www.instagram.com/plotlab01/">Instagram</a> (15K+ followers).</p>

<p><strong>Want an animation like this for your own work?</strong> If you have a project, a research article, a thesis defense, a YouTube video, or any idea that is hard to explain with slides alone, I can turn it into a clear, professional animation. Reach out through my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page and tell me what you are working on. If you would rather learn to build animations yourself, start with my <a href="https://plotlab1.gumroad.com/l/manim_guide_handbook">Manim CE Beginner’s Handbook</a>. And I’d like to hear what you think of this post, drop a comment.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Ask an AI a question and watch the words arrive, one after another. It feels like the machine is looking something up. It is not. At every step, the model is placing a bet. Given everything written so far, it assigns a probability to each possible next word, picks one, and moves on. The paragraph you finally read is a chain of weighted guesses, and the quality of the whole answer depends on how well those guesses were calibrated. It is also why asking the same question twice can give you two different answers.]]></summary></entry><entry><title type="html">The One Idea Quietly Running Every Prediction App On Your Phone</title><link href="https://sohaib-hasan.github.io/blog/four-dots-one-line-secret-behind-ai/" rel="alternate" type="text/html" title="The One Idea Quietly Running Every Prediction App On Your Phone" /><published>2026-10-18T00:00:00+00:00</published><updated>2026-10-18T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/four-dots-one-line-secret-behind-ai</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/four-dots-one-line-secret-behind-ai/"><![CDATA[<p>Open your phone right now and check three things. The weather app telling you tomorrow will be 34 degrees. A real estate app showing you what a plot in your area is roughly worth before you even call the agent. Careem or Uber quoting you a fare before the ride has even started.</p>

<p>None of these three apps are guessing. All three are quietly running the exact same two hundred year old idea. It is called linear regression, and once you understand it, in plain words, no formulas needed, you will start noticing it everywhere, every single day.</p>

<h2 id="you-already-do-this-yourself-you-just-never-gave-it-a-name">You Already Do This Yourself, You Just Never Gave It a Name</h2>

<p>Think about the last time you sold an old phone on OLX. You did not pull out a calculator. You looked at what three or four similar phones, same model, similar condition, sold for, and you landed on a number in between. You did the same thing if you ever guessed what a plot of land was worth from nearby sales, or guessed how a student would perform on a final exam after watching how they did on the first two tests.</p>

<p>In every one of these moments, your brain did something specific. It looked at a handful of known examples, noticed the pattern connecting them, and then stretched that pattern forward to guess something it had never actually seen. That instinct, draw a line through what you know and use it to predict what you do not, is the entire idea behind linear regression. You already had it. Computers just do it with numbers instead of a gut feeling.</p>

<h2 id="where-this-exact-idea-is-quietly-running-your-life">Where This Exact Idea Is Quietly Running Your Life</h2>

<p>Once you know what to look for, it shows up almost everywhere a company needs to predict a number.</p>

<p>A property website estimates the price of a house by looking at thousands of past sales and finding the pattern between size, location, and price, then applying that same pattern to your house. A ride hailing app quotes your fare before you move an inch by finding the pattern between distance, traffic, and past fares. A bank deciding whether to approve your loan is, underneath the paperwork, running a version of this same pattern between income, history, and repayment. A shopkeeper who orders more stock before Eid because sales always climb in the two weeks before it is doing the same thing by instinct that a supermarket chain’s software does with millions of receipts.</p>

<p>Even in my own classroom, when I notice a pattern between how much a student revises and how they score on tests, and I use that pattern to tell a new student roughly what to expect, I am doing exactly this. By hand, with far less data, but the same underlying idea.</p>

<h2 id="why-this-simple-idea-actually-needed-math">Why This Simple Idea Actually Needed Math</h2>

<p>Here is the honest question worth asking. If people have been doing this by instinct for centuries, why did it need to become a formal piece of mathematics at all?</p>

<p>Because instinct breaks the moment the problem gets big or the stakes get real. Ask ten different people to guess the price of a plot from the same five examples, and you will get ten different numbers, because every person draws the pattern through the data slightly differently in their head. That is fine when the cost of being wrong is small. It is not fine when a bank is deciding on a loan for ten thousand people a day, or a property website is pricing a million homes at once, or a hospital is estimating risk for every patient that walks in.</p>

<p>Math solves this by removing the guesswork entirely. Instead of “roughly in between,” it gives one exact rule for finding the single best line through any set of data, the one that keeps the total mistake, across every example, as small as it can possibly be. That rule does not change depending on who is using it, does not get tired, does not have a bad day, and does not care whether the data set has five points or five million. A computer can run that exact same rule on a tiny spreadsheet or on the sales history of an entire country, in the same amount of time it takes to blink. That is the actual power math adds here. Not a smarter guess. A guess that can be trusted, repeated, and scaled, without a single person having to eyeball a chart.</p>

<h2 id="why-this-one-idea-is-the-grandparent-of-modern-ai">Why This One Idea Is the Grandparent of Modern AI</h2>

<p>Here is the part that surprised me the first time I properly understood it. The same core idea, find the pattern that keeps your mistakes as small as possible, is not just used for simple things like house prices. It is the foundation that every modern AI model, including the one writing the text you are reading right now, is built on top of. A giant neural network with billions of parameters is, underneath an enormous amount of extra complexity, still doing a version of the exact same thing a simple line does: adjusting itself, step by step, to make its mistakes smaller, until it finds the pattern that fits best.</p>

<p>Learn this one idea properly, and you have genuinely understood the seed that the entire field of artificial intelligence grew out of.</p>

<h2 id="for-the-curious-few-who-want-to-see-the-actual-math">For the Curious Few Who Want to See the Actual Math</h2>

<p>Most of you reading this do not need to see a single formula to use what you just learned. But a few of you are students, or simply curious people, who want to actually watch how that “best line” gets calculated by hand, with real numbers, step by step, instead of just taking my word for it.</p>

<p>I built a complete animated walkthrough of exactly that, using a tiny four point example you can follow with nothing more than a pen and paper:</p>

<p><strong><a href="https://www.youtube.com/watch?v=MQzgPcSX0Wc">Watch: Linear Regression, animated</a></strong></p>

<p>It walks through why the mistakes get measured the way they do, what the resulting pattern actually looks like once you plot it, and the exact two numbers that pin down the one honest line through any set of points, worked out from scratch.</p>

<h2 id="the-next-time-you-see-a-prediction">The Next Time You See a Prediction</h2>

<p>The next time an app on your phone quotes you a price, a fare, or an estimate before you have given it much information at all, you will know what is actually happening behind that number. Somewhere in its code is the same idea you already use without thinking: look at what happened before, find the pattern, and stretch it forward to guess what happens next.</p>

<p>It is not magic. It never was. It is just a very old, very patient idea, trusted enough to run quietly behind almost everything that predicts anything, including, in its own distant way, the very phone in your hand.</p>

<hr />

<p>I lead the Mathematics Department at my college, and PlotLab is where I turn ideas like this one into animation. If this kind of explanation helped something click, there is more where it came from on <a href="https://web.facebook.com/plotlab1/reels/">Facebook</a> (85K+ followers) and <a href="https://www.instagram.com/plotlab01/">Instagram</a> (15K+ followers). If you’re a teacher, student, or researcher who needs an idea explained visually like this, reach out through my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page. I’d like to hear what you think, drop a comment.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Open your phone right now and check three things. The weather app telling you tomorrow will be 34 degrees. A real estate app showing you what a plot in your area is roughly worth before you even call the agent. Careem or Uber quoting you a fare before the ride has even started.]]></summary></entry><entry><title type="html">How I Got 40,000 Facebook Followers in Just Two Months</title><link href="https://sohaib-hasan.github.io/blog/how-i-got-40k-facebook-followers/" rel="alternate" type="text/html" title="How I Got 40,000 Facebook Followers in Just Two Months" /><published>2026-09-01T00:00:00+00:00</published><updated>2026-09-01T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/how-i-got-40k-facebook-followers</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/how-i-got-40k-facebook-followers/"><![CDATA[<p>Two months ago, my Facebook page had a small, quiet following. Today, more than 40,000 people follow it. I did not expect this to happen so fast, and I do not believe there is a secret trick behind it. But I do understand why it happened, and I want to explain it honestly, because the reason is actually more useful than a trick would be.</p>

<h2 id="what-i-actually-post">What I Actually Post</h2>

<p>My page is called PlotLab. I use it to turn mathematics into animation, using a tool called Manim, the same tool used to build the diagrams in my other blog posts. A definition that feels dry on a whiteboard becomes something a student can actually watch happen. A limit is not just a symbol anymore. You see a point moving closer and closer, step by step, until the idea makes sense on its own.</p>

<p>This is not a new idea. Channels like 3Blue1Brown made this style popular for a general audience. What I do is narrower and, I think, more practical: I build these animations for the exact topics that undergraduate and school-level students struggle with the most, the ones I see them struggle with in my own classroom, every single semester.</p>

<h2 id="why-it-actually-worked">Why It Actually Worked</h2>

<p>Here is the part I think matters most. I do not build an animation and then hope it is useful. I teach first, in a real classroom, with real students in front of me. When I notice the same confusion coming up again and again, on the same topic, I build the animation for that exact topic. Only after that does it go on Facebook or Instagram.</p>

<p>So the content was never designed for social media first. It was designed for my own students first, and social media is simply where it happens to travel well too. I believe this order matters. It means every animation already solved a real confusion for a real student before a single stranger on the internet ever saw it.</p>

<h2 id="what-people-actually-tell-me">What People Actually Tell Me</h2>

<p>The most encouraging part of the last two months has not been the follower count. It has been the messages. Almost every day, someone writes to me in the comments or in my inbox to say that a concept they had struggled with for a long time finally made sense after watching one of these animations. Some are students preparing for exams. Some are people revisiting mathematics years after leaving school, just out of curiosity. The message is almost always some version of the same thing: this is the first time this idea actually made sense.</p>

<p>That kind of feedback is why I keep making these, far more than the follower count itself.</p>

<h2 id="where-to-find-these-animations">Where to Find These Animations</h2>

<p>The main page is on Facebook, <a href="https://web.facebook.com/plotlab1/reels/">web.facebook.com/plotlab1</a>, where the 40,000+ follower community lives. The same animations are also on Instagram, <a href="https://www.instagram.com/plotlab01/">instagram.com/plotlab01</a>, which has grown to 15,000+ followers of its own.</p>

<h2 id="two-things-i-built-because-of-this">Two Things I Built Because of This</h2>

<p>Once people started asking for more than just short videos, I built two things to answer that.</p>

<p>The first is for people who want to learn to build animations like these themselves. I wrote everything I know about getting started with Manim into a single guide, from installing it correctly to the mistakes that waste the most time when you’re new to it. It’s called the <a href="https://plotlab1.gumroad.com/l/manim_guide_handbook">Manim CE Beginner’s Handbook</a>, and it’s written the same way I’d explain it to a student sitting next to me, not the way the official documentation explains it.</p>

<p>The second is for students specifically preparing for IGCSE, O-Level, and GCSE exams. I built a complete set of notes covering the full syllabus, where every topic that’s genuinely hard to picture from text alone is paired with a scannable code linking straight to the matching Manim animation. Alongside the theory, each topic includes worked examples, exam tips, the mistakes students make most often, and practice problems with a formula sheet for quick revision before an exam. You can find the full set on <a href="https://plotlab1.gumroad.com">my Gumroad page</a>.</p>

<h2 id="the-result-i-did-not-expect">The Result I Did Not Expect</h2>

<p>The most useful outcome of the last two months was not on Facebook at all. Researchers preparing for conference presentations started reaching out, asking if I could build an animation to explain a concept from their own research, the kind of concept that is genuinely hard to present clearly in a short talk using only slides and text. I said yes, and it turned into something I now offer properly: custom Manim-built explainers for research talks, thesis defenses, conference presentations, or coursework, built in the same style as PlotLab, with a fast turnaround.</p>

<p>If that sounds like something you need, whether it’s a concept from your own research, a topic for your students, or anything else where an idea needs to be seen and not just read, you can see how this works and reach out on my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page.</p>

<h2 id="what-i-take-from-this">What I Take From This</h2>

<p>I did not grow this page by studying growth tactics. I grew it by solving a real problem for real students first, and only sharing the result afterward. If there is a lesson in that for anyone building an audience around their own work, I think it’s this one: build for the person in front of you first. The audience online tends to follow, not the other way around.</p>

<hr />

<p>I lead the Mathematics Department at my college, and PlotLab is where I turn what I teach into animation. If you’d like to see more of the work, follow along on <a href="https://web.facebook.com/plotlab1/reels/">Facebook</a> (40,000+ followers) or <a href="https://www.instagram.com/plotlab01/">Instagram</a> (15,000+ followers). If you’re a researcher, teacher, or student who needs something explained visually, reach out through my <a href="https://sohaib-hasan.github.io/work-with-me.html">Work With Me</a> page. I’d like to hear from you, drop a comment.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Two months ago, my Facebook page had a small, quiet following. Today, more than 40,000 people follow it. I did not expect this to happen so fast, and I do not believe there is a secret trick behind it. But I do understand why it happened, and I want to explain it honestly, because the reason is actually more useful than a trick would be.]]></summary></entry><entry><title type="html">I Built My Students an AI Assistant That’s Not Allowed to Make Things Up</title><link href="https://sohaib-hasan.github.io/blog/classroom-ai-system-grounded-teaching-assistant/" rel="alternate" type="text/html" title="I Built My Students an AI Assistant That’s Not Allowed to Make Things Up" /><published>2026-08-19T00:00:00+00:00</published><updated>2026-08-19T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/classroom-ai-system-grounded-teaching-assistant</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/classroom-ai-system-grounded-teaching-assistant/"><![CDATA[<p>Ask a generic AI chatbot a question about your course, and it will answer confidently, using its own notation, its own conventions, and occasionally its own facts. It doesn’t know that you define a term slightly differently than the textbook does, or that a particular proof technique hasn’t been covered yet, or that the “obvious” shortcut it just suggested isn’t one your students are allowed to use on the exam. It will still answer. That’s the problem.</p>

<p>I teach undergraduate mathematics, and every semester the same pattern repeats: a handful of students ask sharp, specific questions in office hours, while dozens more ask ChatGPT the same questions late at night, when I’m not there to catch the moment an AI politely gets something wrong. So I built something that only answers from my own course notes, refuses to guess when it doesn’t know, and, as a side effect, shows me exactly where an entire class is actually getting stuck. It’s called <strong>Classroom AI System</strong>, and the code is public: <a href="https://github.com/Sohaib-Hasan/classroom_ai_system">github.com/Sohaib-Hasan/classroom_ai_system</a>.</p>

<h2 id="grounded-not-generic">Grounded, Not Generic</h2>

<p>The technical name for what makes this different is retrieval-augmented generation, RAG for short. Instead of asking a language model to answer from everything it was trained on, the system first retrieves the exact passage from my own LaTeX course notes most relevant to a student’s question, then instructs the model to answer strictly from that passage and nothing else. Right now the knowledge base covers Calculus, Discrete Mathematics, and Number Theory, chunked chapter by chapter from the same notes I hand out in class.</p>

<p>The system is two separate apps sharing one brain:</p>

<ul>
  <li>A <strong>student assistant</strong>, PIN-gated, where students type a question and get an answer grounded in the actual notes.</li>
  <li>A <strong>teacher dashboard</strong>, password-gated, where I see what’s being asked across the whole class: which topics come up again and again, which questions the cache is already handling, and where the same confusion is repeating across different students.</li>
</ul>

<h2 id="how-a-question-actually-gets-answered">How a Question Actually Gets Answered</h2>

<p><img src="/images/classroom-ai-pipeline-diagram.svg" alt="Diagram showing the Classroom AI System's two-stage pipeline: course notes are chunked, cleaned, and embedded into a knowledge base offline, then at runtime a student question is matched against that knowledge base and answered by Gemini, with every question logged for the teacher dashboard." /></p>

<p>Getting from “.tex notes” to “trustworthy answer” happens in two stages. The first, indexing, happens once, offline, whenever my notes change:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python3 chunk_notes.py      # .tex notes  -&gt;  raw chunks (one per definition/example/theorem/proof)
python3 clean_chunks.py     # strips decorative LaTeX, keeps the real math
python3 embed_chunks.py     # embeds every cleaned chunk into knowledge_base.json
</code></pre></div></div>

<p>The second stage happens live, every time a student asks something: the question gets embedded and compared against the knowledge base by cosine similarity, the closest matching chunks get pulled out, and only those chunks, together with the question, get sent to Gemini for an answer.</p>

<h2 id="the-step-that-almost-broke-everything">The Step That Almost Broke Everything</h2>

<p>The middle step, <code class="language-plaintext highlighter-rouge">clean_chunks.py</code>, sounds like the least interesting part of the pipeline. It’s the one that mattered most.</p>

<p><code class="language-plaintext highlighter-rouge">chunk_notes.py</code> extracts each definition, example, or theorem box straight out of the raw <code class="language-plaintext highlighter-rouge">.tex</code> source, decorative markup and all: color commands, tables, diagram code, spacing macros. That raw text becomes part of the prompt the model sees for every question. Skip the cleaning step, and the model will occasionally echo a fragment of that raw markup straight back to a student, so instead of a clean explanation they see broken LaTeX code on their screen. <code class="language-plaintext highlighter-rouge">clean_chunks.py</code> strips all of that decoration out while leaving the real <code class="language-plaintext highlighter-rouge">$...$</code> math completely untouched, so the model only ever sees the content, never the formatting noise around it. It’s a small, unglamorous script, and the whole system’s credibility depends on it running before every embedding pass.</p>

<h2 id="making-it-work-on-a-budget-of-exactly-0">Making It Work on a Budget of Exactly $0</h2>

<p>This runs entirely on Gemini’s free tier, which means every question costs quota, and quota is the actual scaling limit. A few decisions keep that from becoming a wall:</p>

<ul>
  <li><strong>Multi-key rotation.</strong> Gemini’s rate limits apply per Google Cloud project, not per key, so keys from separate accounts draw from independent quota pools. The system supports up to three keys and falls through to the next one only if a call fails, invisibly to the student asking the question.</li>
  <li><strong>Caching.</strong> A SQLite-backed cache means a rephrased version of a question someone already asked skips the generation call entirely, which matters a lot in a class where dozens of students hit the same handful of confusing topics.</li>
  <li><strong>Local embeddings.</strong> Every question needs an embedding call, even on a cache hit, which makes it the single biggest quota consumer in the whole system. Swapping the embedding provider to a free local model removes that cost entirely, at the price of having to rebuild the knowledge base once, since Gemini and local embeddings aren’t compatible with each other.</li>
  <li><strong>A per-session rate limit.</strong> Eight questions per rolling 60 seconds per browser session, mostly as a safety net against an accidental double-submit rather than a real constraint on normal use.</li>
</ul>

<h2 id="two-apps-one-shared-brain">Two Apps, One Shared Brain</h2>

<p>The student assistant and the teacher dashboard are deployed as two separate Streamlit Cloud apps, on two different URLs, each running in its own isolated container. That last part turned into the trickiest infrastructure problem in the whole project: a local SQLite file that one container writes to simply doesn’t exist for the other one.</p>

<p><img src="/images/classroom-ai-architecture-diagram.svg" alt="Diagram showing the student assistant and teacher dashboard as two separate, isolated Streamlit Cloud deployments that both read the shared knowledge_base.json and both read and write to a shared Turso database for the question log." /></p>

<p>The fix is <a href="https://turso.tech">Turso</a>, a free, hosted, SQLite-compatible database that both apps point to instead of their own local files. Two details in that setup cost real debugging time and are worth writing down: the connection string has to use <code class="language-plaintext highlighter-rouge">https://</code>, not <code class="language-plaintext highlighter-rouge">libsql://</code>, because the WebSocket handshake <code class="language-plaintext highlighter-rouge">libsql://</code> relies on can fail inside Streamlit Cloud’s sandboxed environment, and the secret key has to be named exactly <code class="language-plaintext highlighter-rouge">TURSO_AUTH_TOKEN</code>. Get either of those wrong and there’s no crash, no error message, just a dashboard that stays quietly empty with nothing to explain why.</p>

<h2 id="what-the-teacher-actually-sees">What the Teacher Actually Sees</h2>

<p>This is the part that matters most to me as a teacher, and it’s the part a generic AI chatbot can never give you. Office hours show me the questions the handful of students who show up are willing to ask out loud. The dashboard shows me every question the whole class actually had: which topic keeps coming back, which confusion is repeating across students who’ve never spoken to each other, what the cache is already absorbing versus what’s genuinely new. It’s the difference between a handful of anecdotes and an actual signal.</p>

<h2 id="built-to-not-break-quietly">Built to Not Break Quietly</h2>

<p>The business logic lives in <code class="language-plaintext highlighter-rouge">core.py</code>, which deliberately has no dependency on Streamlit at all, so it can be tested completely independently of the app itself. Right now it’s backed by 91 automated tests, and every one of them exists because a specific bug was found and fixed, not because of abstract coverage targets. One example I’m particularly fond of: the system’s <code class="language-plaintext highlighter-rouge">verify_computation()</code> check samples the negative, positive, <em>and</em> near-zero domains of a function, not just the positive ones, specifically because a positive-only check would miss domain-sensitive errors like treating <code class="language-plaintext highlighter-rouge">sqrt(x**2)</code> as equal to <code class="language-plaintext highlighter-rouge">x</code>, which only holds when <code class="language-plaintext highlighter-rouge">x</code> is non-negative. That’s the kind of bug that looks fine in a quick demo and quietly produces wrong math for a student six weeks later.</p>

<h2 id="where-its-still-rough">Where It’s Still Rough</h2>

<p>A few honest limitations, because a system that grades student proofs owes its builder the same standard: nested LaTeX boxes of the same type (a definition box inside another definition box) aren’t parsed cleanly yet, though a safety check flags this loudly the moment it happens rather than letting it reach a student silently. The automated cleaning handles the large majority of decorative LaTeX but not all of it: roughly 3% of chunks, mostly color commands sitting inside real math, still need a manual look. And there’s an optional third-party fallback provider for when every Gemini key is exhausted that I’ve built but haven’t yet stress-tested in production, so for now it’s a safety net I wouldn’t lean on.</p>

<h2 id="whats-next">What’s Next</h2>

<p>The next thing I’m building on top of this is a guided answering mode: instead of jumping straight to a full solution, the system will offer a hint first, then a guiding question, and only give the complete answer if the student actually wants it. The goal was never to hand out finished proofs faster. It’s to get a student unstuck without doing their thinking for them.</p>

<p>That’s really the whole premise behind this project, and behind the broader direction I want to take my teaching: AI that’s useful specifically because it’s constrained, not despite it.</p>

<hr />

<p>I lead the Mathematics Department at my college and build tools like this one alongside my Manim animation work as PlotLab. If you teach and are curious whether something like this could work for your own courses, or if you’d like help building it, reach out. I write more like this at <a href="https://sohaib-hasan.github.io">sohaib-hasan.github.io</a>, and if you want to see the kind of animated explanations I build separately from this project, they’re on <a href="https://web.facebook.com/plotlab1/reels/">Facebook</a> (35K+ followers) and <a href="https://www.instagram.com/plotlab01/">Instagram</a> (15K+ followers). I’d like to hear what you think, drop a comment.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Ask a generic AI chatbot a question about your course, and it will answer confidently, using its own notation, its own conventions, and occasionally its own facts. It doesn’t know that you define a term slightly differently than the textbook does, or that a particular proof technique hasn’t been covered yet, or that the “obvious” shortcut it just suggested isn’t one your students are allowed to use on the exam. It will still answer. That’s the problem.]]></summary></entry><entry><title type="html">AI Just Posted a Perfect Score at the Real Math Olympiad. I Spent Months Building One of These Systems. Here’s What It Actually Takes</title><link href="https://sohaib-hasan.github.io/blog/inside-aimo3-parallel-self-consistency-pipeline/" rel="alternate" type="text/html" title="AI Just Posted a Perfect Score at the Real Math Olympiad. I Spent Months Building One of These Systems. Here’s What It Actually Takes" /><published>2026-08-07T00:00:00+00:00</published><updated>2026-08-07T00:00:00+00:00</updated><id>https://sohaib-hasan.github.io/blog/inside-aimo3-parallel-self-consistency-pipeline</id><content type="html" xml:base="https://sohaib-hasan.github.io/blog/inside-aimo3-parallel-self-consistency-pipeline/"><![CDATA[<p>In July 2026, in Shanghai, something happened that mathematicians had been debating for two years: AI systems from Huawei and Xiaohongshu were each reported to have solved all six problems of the International Mathematical Olympiad, a perfect 42 out of 42. Several other labs reported matching results on their own. It followed a 2025 breakthrough where Google DeepMind’s Gemini Deep Think, officially graded by IMO coordinators, and an OpenAI experimental model both reached the gold-medal threshold of 35/42.</p>

<p>Headlines called it AI “beating” the world’s best teenage mathematicians. I want to tell you what’s actually behind a headline like that, not as a journalist, but as someone who spent the past several months building a much smaller, much less glamorous version of exactly this kind of system.</p>

<p>My teammate Samuel Koh and I entered AIMO3, the third AI Mathematical Olympiad Progress Prize, hosted on Kaggle. We scored 42 out of 50, placing 495th out of 4,138 teams, the top 12% globally. Here’s the honest, unglamorous story of how we got there, what we tried that failed, and what the finished system actually looks like under the hood.</p>

<h2 id="what-aimo-actually-is-and-why-its-not-the-imo">What AIMO Actually Is (And Why It’s Not the IMO)</h2>

<p>First, an important distinction, because the acronyms get confusing fast: AIMO is not the IMO.</p>

<p>The AI Mathematical Olympiad is a $10 million prize fund, created in 2023, that exists specifically to close the gap between what the closed, proprietary models at OpenAI and Google can do and what the open community can build. Its grand prize, $5 million, goes to the first team that publicly shares a model capable of gold-medal-equivalent performance at the actual IMO. Along the way, Kaggle hosts periodic “Progress Prize” competitions to measure how far the open field has come.</p>

<p>AIMO1 was won by Project Numina in 2024. AIMO2 was won by NVIDIA’s team, NemoSkills, who solved 34 of 50 problems. AIMO3, the one we entered, raised the difficulty again: 110 entirely original problems, ranging from national-olympiad level up to full IMO standard, spanning algebra, combinatorics, geometry, and number theory. “Entirely original” matters enormously here: it means no amount of memorization from training data helps you. Every problem has to be reasoned through, not recalled.</p>

<p>Competitors were also given access to H100 GPUs, roughly double the compute of AIMO2, which meant we could run larger open-weight models than previous years: models like GPT-OSS-120B and Qwen3-Next became viable for the first time.</p>

<p>So when you read that an AI “scored a perfect IMO,” understand what’s actually being claimed. In 2026, most of those results, including the ones from Huawei and Xiaohongshu, were the companies’ own self-reported submissions, run after the human competition window closed, evaluated against the same problems and time limit but not scored live by IMO coordinators. Only a small number of 2025 and 2026 results have been independently, officially graded. That’s not a reason to dismiss the progress; it’s real, and it’s fast, but it’s worth knowing the difference between “officially certified” and “self-administered” when you see the next big claim.</p>

<h2 id="two-rules-that-shaped-every-decision-we-made">Two Rules That Shaped Every Decision We Made</h2>

<p>Before I describe what we built, you need to understand the two constraints that made this hard, because they killed almost every “obvious” idea we had.</p>

<p><strong>Rule one: five hours of GPU compute, total, per problem set.</strong> Not per problem. Per set. That immediately rules out anything computationally greedy.</p>

<p><strong>Rule two: binary scoring, no partial credit.</strong> A problem is either fully correct or fully wrong. This sounds simple, but it has a brutal implication: a system that produces a plausible, confident-sounding, but wrong answer is worse than a “generic” wrong answer, because it’s confidently wrong. Under this rule, knowing when your system is unsure is almost as valuable as getting the right answer.</p>

<p>I handled the mathematical side: interpreting problems, checking whether a given line of reasoning was actually valid, and sourcing harder test cases beyond the standard dataset to stress-test our system. Samuel handled the engineering: building and running the inference pipeline under that fixed compute budget. Neither role alone was enough. The problems weren’t purely mathematical, and they weren’t purely a systems problem either.</p>

<h2 id="four-ideas-we-killed-before-writing-a-line-of-the-final-system">Four Ideas We Killed Before Writing a Line of the Final System</h2>

<p>Here’s what we considered and rejected and why each one matters as a lesson, not just a footnote:</p>

<ul>
  <li><strong>Supervised fine-tuning.</strong> The obvious first instinct. Rejected immediately: it needs massive GPU clusters and months of runway, not a fixed five-hour, competition-scale budget.</li>
  <li><strong>Fully agentic search</strong>, a system that breaks a problem into steps, calls tools, verifies intermediate results, and loops back on itself. Conceptually, this is the closest thing to how a human mathematician actually thinks. We rejected it anyway, because Kaggle’s environment has no outbound internet access, and an open-ended agentic loop risked silently burning our entire compute budget before ever producing a final answer.</li>
  <li><strong>Monte Carlo Tree Search.</strong> Not used.</li>
  <li><strong>Long, verbose chain-of-thought prompting.</strong> We tested it. Concise prompting consistently outperformed it.</li>
</ul>

<p>The pattern across all four rejections is the same one that ended up defining our whole approach: under a fixed, non-negotiable compute budget, a simpler system you can actually trust beats a theoretically more powerful one you can’t fully control.</p>

<h2 id="the-architecture-a-parallel-self-consistency-pipeline">The Architecture: A Parallel Self-Consistency Pipeline</h2>

<p>What we actually built and submitted, we called a <strong>Parallel Self-Consistency Pipeline</strong>. Here’s how a single problem moves through it, end to end:</p>

<p><img src="/images/aimo3-pipeline-diagram.svg" alt="Diagram of the Parallel Self-Consistency Pipeline: an AIMO problem enters as LaTeX, passes through a prompt constructor into GPT-OSS-120B, fans out into 8 parallel reasoning attempts each paired with a Python REPL, and converges into an entropy-weighted aggregator that selects the final answer." /></p>

<ol>
  <li><strong>The problem</strong> arrives written in LaTeX and gets converted into a structured prompt.</li>
  <li><strong>The base model</strong>, GPT-OSS-120B (OpenAI’s open-weight mixture-of-experts model, around 120 billion total parameters but only about 5 billion active per token, which is exactly why it fits on a single H100 despite its size), generates a reasoning attempt at temperature 0.8.</li>
  <li><strong>The Parallel Sampler</strong> does this eight times, independently, all at once. This is the “self-consistency” idea, and it’s built on a real insight from a 2022 paper by Wang et al.: a single reasoning chain can silently go wrong at any step with no way to catch it, but across eight independent attempts, correct reasoning tends to converge on the same answer while failure modes tend to scatter in different directions.</li>
  <li><strong>Tool-Integrated Reasoning.</strong> Each of those eight attempts is paired with a live Python interpreter. The moment a reasoning chain hits a calculation it can’t reliably do purely in text, it hands that calculation off to Python instead of guessing, a small design choice that removes an entire category of careless arithmetic errors.</li>
  <li><strong>The Entropy-Weighted Aggregator.</strong> This is the part I’m proudest of. Instead of a simple majority vote across the eight candidate answers, each one is scored by:</li>
</ol>

\[\text{score} = \frac{1}{H} + 8.0 \cdot V\]

<p>Here, <em>H</em> is the mean generation entropy of that attempt, how “confident” the model was, token by token, while producing it, and <em>V</em> is a verifier score. Because the formula uses 1/H, a low-entropy, confident attempt scores higher than a scattered, uncertain one, even if it wasn’t the majority answer. There’s also an early-stopping rule: if any single answer already has four or more votes, the aggregator stops and submits it immediately, saving compute for the next problem instead of waiting out the clock.</p>

<p>I actually animated this entire pipeline in Manim, every arrow, every fan-out, every step of the aggregation so you can watch it play out visually instead of just reading a static diagram:</p>

<p><strong><a href="https://youtu.be/qOPH9anSiw4">Watch the animation: AIMO3 Pipeline, visualized</a></strong></p>

<h2 id="from-850-to-4250-what-the-climb-actually-looked-like">From 8/50 to 42/50: What the Climb Actually Looked Like</h2>

<p>Our first working version of this pipeline scored 8 out of 50. The final version scored 42. That climb didn’t come from one clever trick; it came from three unglamorous things, repeated over and over: systematically diagnosing bugs in the pipeline itself, upgrading the base model as better open-weight options became available, and steadily refining the few-shot prompts feeding into step one.</p>

<p>There’s one more data point that told us we were on the right track, and it came after the competition closed. The eventual first-place team’s public writeup also centered on GPT-OSS-120B, and their approach was also built around entropy-weighted self-consistency. They refined it further with things like adaptive runtime scheduling, but directionally it was the same idea we’d arrived at independently. When a team with more resources converges on the same core mechanism you did, without either of you seeing the other’s work, that’s a stronger signal than any single benchmark score.</p>

<h2 id="the-one-lesson-id-give-anyone-building-ai-under-real-constraints">The One Lesson I’d Give Anyone Building AI Under Real Constraints</h2>

<p>Every rejected idea, fine-tuning, agentic search, tree search, and verbose prompting failed for a version of the same reason: it added complexity we couldn’t fully control inside a budget we couldn’t negotiate. The thing that actually worked was the opposite: precision and reliability over architectural cleverness.</p>

<p>That’s not a lesson specific to Kaggle competitions. It’s true anywhere you’re building an AI system against a real constraint, a latency budget, a cost ceiling, a compliance requirement. The fanciest architecture on paper is worth nothing if you can’t trust what it does when the clock is running.</p>

<p>As for the “AI beat the Olympiad” headlines, they’re not wrong, exactly. The field genuinely moved from silver-medal level in 2024 to officially certified gold in 2025 to multiple perfect-score claims in 2026 in about two years. I watched a smaller version of that same curve happen inside my own project, going from 8/50 to 42/50 in a few months of iteration. The trend is real. Just read the fine print on “official” versus “self-reported” before you decide how impressed to be by any single claim.</p>

<hr />

<p><em>I teach undergraduate mathematics, and I build Manim-animated math content as PlotLab. If you want to learn the exact animation workflow used in the diagram above, from your first <code class="language-plaintext highlighter-rouge">Scene</code> to a full multi-step pipeline animation. I wrote a complete, copy-paste-ready guide to it: <a href="https://plotlab1.gumroad.com/l/manim_guide_handbook">Manim CE Beginner’s Handbook</a>. I’d genuinely like to hear what you think of the pipeline above.</em></p>]]></content><author><name></name></author><summary type="html"><![CDATA[In July 2026, in Shanghai, something happened that mathematicians had been debating for two years: AI systems from Huawei and Xiaohongshu were each reported to have solved all six problems of the International Mathematical Olympiad, a perfect 42 out of 42. Several other labs reported matching results on their own. It followed a 2025 breakthrough where Google DeepMind’s Gemini Deep Think, officially graded by IMO coordinators, and an OpenAI experimental model both reached the gold-medal threshold of 35/42.]]></summary></entry></feed>