0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Hook: same question, different answers
Ask Brightcart's assistant for a tagline for the new kettle, three times, and you get three different answers. Dev wants to know: is it broken? No. At every step, the model doesn't choose the next word. It computes a probability for every possible next token and then, usually, samples one, like rolling a weighted die. That's why answers vary. And there's a dial that controls how adventurous those dice rolls are. Turn it down and the answers become predictable and safe. Turn it up and they become creative, and eventually nonsensical.
Today: exactly how sampling works, the settings that control it, and how to force a model to produce perfectly structured output. Season Three, Module Eleven, stop four: sampling.
1:01From logits to probabilities
At each step, the model's final layer gives a raw score, called a logit, to every token in its vocabulary. After "Your parcel will arrive", the top candidates might be "tomorrow" with three point zero, "today" with two point two, "soon" with one point eight, "late" with zero point five, and, way down, "purple" with minus two. Softmax, from Season One, turns these into probabilities: fifty-four percent "tomorrow", twenty-four percent "today", sixteen "soon", under five "late", and less than half a percent "purple". Now we have a choice.
Greedy decoding always takes the most likely token: "tomorrow", every time. Sampling rolls a die weighted by these probabilities: usually "tomorrow", sometimes "today" or "soon", and very rarely something strange.
1:59Temperature
The famous dial is called temperature. Before softmax, we divide every logit by a number T. With T below one, say zero point five, the differences between logits get bigger, so the distribution gets sharper: "tomorrow" jumps to seventy-seven percent, and the unlikely options nearly vanish. As T approaches zero, sampling becomes the same as greedy. Now, a prediction. At temperature two, the logits are squeezed closer together. Does "purple" become more likely, or less?
More likely: from under half a percent to over three percent, nearly nine times as likely. At temperature two, "tomorrow" drops to thirty-nine percent and every other option rises. Higher temperatures give more varied and surprising text, and more nonsense. The name comes from physics, where higher temperature means more random motion. For factual answers, like Brightcart's delivery questions, a low temperature is sensible. For brainstorming taglines, a higher one can help.
3:11Why not always greedy?
If greedy always picks the most likely word, why not use it everywhere? Because always choosing the single safest word can lead to strange behaviour in long text: bland, generic phrasing, and sometimes loops, where the model repeats the same phrase over and over. That said, for tasks with one correct answer, like extracting an order number or some coding tasks, a temperature near zero is often exactly what you want. And the beam search we met in episode thirty-four is still popular for translation. The right setting depends on the job.
3:51Top-k and top-p sampling
Even at a sensible temperature, there's a hidden risk. A vocabulary has tens of thousands of tokens, each with a tiny probability, and together that long tail adds up. Sample enough tokens and eventually you'll pick a terrible one. Two popular fixes cut off the tail. Top-k keeps only the k most likely tokens. With k equals two, only "tomorrow" and "today" survive, and their probabilities are rescaled to add up to one: sixty-nine and thirty-one percent. Top-p, also called nucleus sampling, keeps the smallest set of tokens whose probabilities add up to at least p.
With p of zero point nine: "tomorrow" gives fifty-four percent, add "today" for seventy-nine, add "soon" for ninety-five. We've passed ninety, so those three are kept, and rescaled. The advantage of top-p is that it adapts. When the model is confident, the nucleus might be just one or two tokens. When many continuations are reasonable, it widens automatically. Top-k always keeps the same number, whatever the situation.
5:02Other controls: stop sequences, penalties, seeds
Real systems offer a few more controls. A maximum number of tokens caps the length. Stop sequences end generation when a particular string appears. Repetition penalties lower the scores of tokens that have already been used, to discourage loops. A random seed, where supported, makes the dice rolls repeatable, though results can still vary between model versions or hardware. And you can ask for several samples at once, then choose the best one, an idea we'll build on next episode. Keep in mind that details like these change fast.
They were correct when this video was published, so treat them as a snapshot, not a permanent fact.
5:45Why sampling explains inconsistent answers
Sampling also explains some behaviour that surprises people. If a model is somewhat unsure about a fact, say Brightcart's return window, it might give the right number most of the time, and occasionally a wrong one, simply because a lower-probability answer got sampled. That's one reason the same question can get inconsistent answers. It also suggests a useful trick: ask the same question several times, and if the answers disagree, the model is probably uncertain. We'll use this when we discuss hallucinations next episode.
6:23Structured outputs: constrained decoding
Often, software needs the model's output in an exact format, like a JSON object with an order number and a status. Prompting for it usually works, but not always: sometimes the model adds a friendly sentence, or misses a bracket, and the program reading it breaks. The most reliable fix is constrained decoding. At every step, a grammar, such as a JSON schema, determines which tokens are allowed next, and every other token's probability is set to zero before sampling. At the very start of an object, only an opening brace is allowed.
After it, only a quote to begin a key name. The model still chooses the content, but it physically can't break the format. Many platforms now offer this as a "structured output" feature. Alongside clear prompts, examples and validation with a retry, it's how dependable AI systems talk to other software, something we'll rely on heavily in Seasons Four and Five.
7:26Choosing settings by task
So how should Brightcart set these dials? For extracting facts or classifying tickets, use a low temperature, and structured output where possible. For customer replies, a low to moderate temperature keeps them natural but reliable. For brainstorming taglines, turn it up, with top-p to keep out the nonsense. For code, use a low temperature for a single answer, or generate several candidates at a higher temperature and let automated tests pick the best. These are starting points, not rules. Start from your provider's defaults, and adjust while measuring the results, the evaluation skills of Season Four.
8:09Try it yourself: a very low temperature
Let's push the temperature down to a quarter. Dividing by a quarter means multiplying every logit by four. What happens to "tomorrow"? Pause. It jumps to about ninety-five percent. "Today" falls to four percent, "soon" to under one percent, and the others almost vanish. At a temperature of one, "tomorrow" had fifty-four percent. As the temperature approaches zero, sampling turns into greedy decoding: the top token every time.
8:47Predict: top-p with p = 0.75
Top-p keeps the smallest set of tokens whose probabilities add up to at least p. With p at zero point seven five, which tokens survive? And at zero point eight? Pause. "Tomorrow" plus "today" add up to zero point seven nine, which clears zero point seven five, so just those two survive, renormalised to sixty-nine and thirty-one percent. But zero point seven nine falls just short of zero point eight, so at p equals zero point eight, "soon" joins them too. A tiny change in the setting can change the choices.
9:29Min-p: a threshold that adapts
Newer methods keep appearing. One, called min-p, keeps any token whose probability is at least a fraction of the top token's probability. With min-p at zero point one, the threshold here is about zero point zero five four, so "tomorrow", "today" and "soon" survive, and "late" just misses. The nice property: when the model is confident, the threshold rises and fewer tokens pass; when it's uncertain, more are allowed. The cut-off adapts to the situation.
10:06A repetition penalty, by hand
Here's a repetition penalty in numbers. Suppose "tomorrow" has already appeared in the reply, and the penalty lowers its logit by a half. Its probability drops from fifty-four percent to about forty-two, and the alternatives rise. That helps break loops like "Your parcel will arrive tomorrow" repeated over and over. But be careful: too strong a penalty forces awkward synonyms and can even stop the model repeating things it must repeat, like a customer's name or an order number.
10:39Reproducibility in the real world
Can you get exactly the same answer twice? With the same prompt, seed, model version and software, usually yes. But outputs can still change: a model update, different hardware, or even how a server batches requests together can create tiny numerical differences, and when two tokens are nearly tied, a tiny difference can flip the choice. Then everything after it changes. So log the model version and settings, and when testing, sample several times and look at the spread, not just one answer.
11:16Common sampling mistakes
Some common mistakes. Using a high temperature for structured output, like JSON, which breaks the format. Believing a temperature of zero means correct: it only means most likely, and the most likely answer can still be wrong. Setting the maximum length so low that the output is cut off halfway through. And tuning settings by staring at a single example instead of measuring across a proper test set, which we'll do in Season Four.
11:46Sampling Sana's product descriptions
Sana needs thirty fresh descriptions for a new range of mugs. At a temperature of zero point two, they come out almost identical: "A stylish mug for your morning coffee", again and again. At zero point nine with top-p, they're varied and still on brand. At one point eight, the word choices get strange and the descriptions drift off topic. So Brightcart's rule is simple: low temperatures for factual replies, moderate ones for creative copy, and a human review either way.
12:19Why chat models don't use beam search
Remember beam search from episode thirty-four? It finds high-probability sequences, so why don't chat models use it? Because for open-ended writing, the most likely sequences tend to be bland and repetitive: "Thank you for your message", over and over. Researchers found that human writing is often less predictable than what beam search produces. Beam search is still useful where there's essentially one right answer, like translation or speech recognition, but for open-ended text, careful sampling usually reads better.
12:55Myth vs Fact
Myth: setting the temperature to zero makes a model accurate. Fact: it makes it consistent. You'll mostly get the same, most likely answer each time, but if the model's most likely answer is wrong, you'll get the same wrong answer, reliably.
13:13Recap
Let's recap. At each step, a model turns logits into probabilities with softmax and then picks a token. Greedy always takes the top one, and sampling rolls a weighted die. Temperature sharpens or flattens the probabilities. Top-k and top-p cut off the long tail of unlikely tokens, with top-p adapting to the model's confidence. Stop sequences, length limits, penalties and seeds give further control. And constrained decoding guarantees valid structured output. One sentence to remember: temperature sets how bold the dice are, and top-p decides which faces are on the die.
13:56Next: hallucinations and reasoning models
Mission complete. Dev now controls how predictable or creative Brightcart's assistant is, and its order data comes out in perfect JSON every time. But Sana has a bigger worry. The assistant just told a customer about a sixty-day return policy that doesn't exist, stated with complete confidence. Why do language models make things up? And what are the new "reasoning" models doing differently? Next episode. See you on the map.