Key takeaways
- At every step the model hands us a table of probabilities; picking one word from it is called decoding or sampling. Greedy decoding takes the top word each time: deterministic, but prone to repetition and short-sighted. Random sampling draws by probability, which gives the output variety.
- Temperature divides the scores by T. Small T sharpens the distribution, and T→0 is greedy; large T flattens it. It changes how big the lead is, never the ranking.
- Truncation cuts off the unreliable tail: top-k fixes the number of candidates, top-p fixes the cumulative probability, and min-p sets the bar as a fraction of the top word. Temperature controls how random the pick is; truncation controls how big the pool is.
- Sampling and argmax are step functions, so they block the gradient. Gumbel-Max moves the randomness into noise, and Gumbel-Softmax then swaps the argmax for a softmax with a temperature.
- The straight-through estimator (STE) uses the real function going forward and pretends it's the identity going backward. It suits monotonically increasing operations like rounding and quantization.
Same question, two answers
Ask a chatbot the same question twice and you often get two different answers. The model hasn't changed and neither has the question, so where does the difference come from?
Think back to episode 0: at each step the model doesn't hand you a word, it hands you a table of probabilities. After "The weather is so", for example: nice 0.61, good 0.22, cold 0.14, hot 0.03. Once you have this table, how do you pick one word out of it? That step is called decoding, or sampling. It looks like a tiny final step, but it has a huge effect on the quality of what comes out.
This episode has two halves. The first covers the common ways to pick: greedy, random sampling, temperature, top-k, top-p and min-p. The second asks: what if the network has to make a random choice like this in the middle of training? Can the gradient still get through?
The simplest way to pick: greedy
The most obvious idea: pick whichever word has the highest probability. This is greedy decoding:
next token=argimax pi
Its one real advantage is that it's completely deterministic: the same input always gives the same output. But it has two problems.
Problem one: it easily gets stuck repeating itself. Ask it to continue "My favorite animal is", and greedy might write: the cat. My favorite animal is the cat. My favorite animal is the cat… and on and on. Once a sentence has shown up in the text, the model tends to think saying it again is perfectly natural, and every repeat makes the next one a little more likely. Greedy always takes the top choice, so once it falls into this loop it can never climb out.
Problem two: it's short-sighted. Picking the best word at every step doesn't guarantee the best sentence overall.
- After "He opened the", "door" has probability 0.5 and "fridge" 0.4, so greedy picks "door".
- But after "door", even the best next word only gets 0.3, whereas after "fridge", "door" jumps to 0.9.
A sentence's probability is the probabilities of its steps multiplied together: 0.5×0.3=0.15, but 0.4×0.9=0.36, which is far higher.
One fix is beam search: keep several of the best candidates at each step, and at the end pick the one with the highest total probability. It's popular in machine translation, but in open-ended writing and chat it also tends to come out repetitive and bland, which is why chat models usually use random sampling.
Drawing lots by probability
Random sampling means drawing lots using the probability table: a word with probability 0.61 gets picked about 61 times out of 100.
How do we draw? Cut the line from 0 to 1 into pieces by probability: "nice" gets 0.61 of it, "good" 0.22, "cold" 0.14 and "hot" 0.03. Pick a random number between 0 and 1, say 0.73. It lands in the "good" piece, so this time we pick "good". Draw 20 times and most land on "nice", some on "good" and "cold", and once in a while one lands on "hot" (say 12 / 5 / 2 / 1).
That's why the same question can get a different answer each time, which solves our opening puzzle. In PyTorch the function that does this is torch.multinomial.
Watch out: Pure random sampling has a long-tail problem. A real vocabulary has tens of thousands of tokens, and almost all of them would be absurd in any given spot, each with a tiny probability. But tens of thousands of tiny probabilities add up to something that isn't tiny. If the tail adds up to 20%, then on average one step in five pulls a weird word out of it. And once a weird word is written, everything after has to build on it, so the passage can drift further and further off track.
So we need two kinds of knobs: one reshapes the distribution, making it sharper or flatter (temperature); the other simply cuts off the tail (truncation).
Temperature: sharpen or flatten the distribution
First, where does the probability table come from? At the very end the model gives every token a score called a logit, written z. Say the four words score 2, 1, 0.5, −1. Softmax turns scores into probabilities:
pi=∑jezjezi
The exponential makes every result positive, and dividing by the sum makes them add up to 1. Here that gives 0.61, 0.22, 0.14 and 0.03.
Temperature does exactly one thing: before taking the exponential, divide every score by the same number T:
pi=∑jezj/Tezi/T
| T |
scores z/T |
probabilities |
| 0.5 |
4,2,1,−2 |
0.84,0.11,0.04,0.00 |
| 1 |
2,1,0.5,−1 |
0.61,0.22,0.14,0.03 |
| 2 |
1,0.5,0.25,−0.5 |
0.43,0.26,0.21,0.10 |
- T=0.5: dividing by 0.5 is multiplying by 2, so the gaps get stretched; "nice" climbs from 0.61 to 0.84 and the others get pushed down.
- T=2: the scores are halved, the gaps shrink, and the distribution flattens out.
Slide T smoothly: the smaller it gets, the sharper the distribution, with more and more probability piling onto the top word; the bigger it gets, the flatter, until the four words are close to an even split. Set T back to 1 and you're back to the model's original distribution.
The math behind temperature
Why does dividing by T do this? Look at the ratio of any two words' probabilities. Both share the same denominator S, which cancels; and dividing exponentials means subtracting their exponents:
pjpi=ezj/T/Sezi/T/S=ezj/Tezi/T=e(zi−zj)/T
The scores for "nice" and "good" differ by exactly 1, so their ratio is e1/T:
| T |
e1/T |
| 0.5 |
7.39 |
| 1 |
2.72 |
| 2 |
1.65 |
Dividing by T stretches or squeezes the gap between scores. So:
- T→0: every gap is blown up toward infinity and the top word takes all the probability. That's just greedy decoding.
- T→∞: every gap is squashed toward zero and all words become equally likely, like picking from the vocabulary with your eyes closed.
- Temperature changes how big the lead is, but never the ranking: first place always stays first. T=1 is the original distribution.
The name comes from physics: the hotter a system, the more evenly its particles spread across all kinds of states; the colder, the more they crowd into the lowest-energy state.
In practice, for writing code or solving math problems, people often turn the temperature down to keep things steady (more deterministic, more conservative). For poetry or brainstorming you can turn it up for variety (more random, more "creative").
Watch out: Turn it up too high and the words in the tail get lifted too. In a real vocabulary most of what gets lifted is nonsense, and the output turns into gibberish. Temperature controls how random things are, but it can't deal with the tail; for that we need truncation.
Cutting off the tail: top-k
Top-k is blunt: keep only the k most likely words and throw away the rest.
Example: the 8 candidates after "Today I want to eat": pizza 0.40, pasta 0.25, sushi 0.15, tacos 0.08, salad 0.05, burgers 0.04, rocks 0.02, keyboards 0.01.
With k=3 we keep pizza, pasta and sushi, and the other five are gone, absurd ones like rocks and keyboards included. The three survivors add up to only 0.40+0.25+0.15=0.80, so we renormalize by dividing each by 0.8: 0.5, 0.31, 0.19, which add up to 1 again.
In code, the usual trick is to set the discarded words' scores to −∞. Since e−∞=0, their probability after softmax is exactly zero.
The trouble with top-k is that k is fixed, yet depending on the context there may be only one sensible candidate, or a whole crowd:
- "The capital of France is": really only Paris (0.92). With k=3, Versailles and Lyon still get in, so there's about a 5% chance of a wrong answer.
- "She picked up a": novel, magazine, comic, notebook… eight options of about the same height, all sensible. k=3 chops away most of them.
Could the number of candidates adjust to the distribution? That's what top-p does.
Cutting by cumulative probability: top-p
Top-p, also called nucleus sampling, fixes a total amount of probability p instead of a count, say 0.9. Sort the words from most to least likely, then add them up one at a time until the total just passes p:
| Word |
Prob. |
Running total |
| pizza |
0.40 |
0.40 |
| pasta |
0.25 |
0.65 |
| sushi |
0.15 |
0.80 |
| tacos |
0.08 |
0.88 |
| salad |
0.05 |
0.93 |
Salad takes us past 0.9, so we keep these five words (including salad, the one that just crossed the line), cut off the rest of the tail, and renormalize.
Back to the two examples:
- "The capital of France is": Paris alone is 0.92, already past 0.9, so only Paris is kept.
- "She picked up a": we have to add all the way to the seventh word before passing 0.9, so seven are kept.
Intuition: With the same p, a confident model keeps just one or two words and an unsure one keeps more. The number of candidates is dynamic, adjusting to the distribution automatically. That's what makes it smarter than top-k.
Top-p comes from a 2019 paper on what its authors called neural text degeneration. Today you'll find this setting in the APIs of most large language models.
More knobs: min-p and repetition penalties
Min-p is a newer method whose threshold moves with the top word: keep a word only if its probability is at least the top word's probability times some fraction.
keep if pi ≥ 0.1×pmax
With the fraction set to 0.1:
- "Today I want to eat": the top word has 0.4, so the bar is 0.04. Burgers just make the cut; rocks and keyboards are trimmed.
- "The capital of France is": the bar rises to 0.092, leaving only Paris.
- "She picked up a": the bar drops to 0.016, and all eight stay.
The more confident the model, the harder it trims; the more hesitant, the more it keeps. Plenty of open-source inference engines support it.
There's also a knob aimed squarely at the repetition problem from the start: the repetition penalty. If a token has already appeared, push its score down, say by 1 for every time it has shown up. "Cat" has appeared twice, so its score drops by 2 and its probability falls from 0.86 to 0.44. That makes the model far less likely to go around in circles.
Chaining the knobs together
The knobs can be combined. A typical order:
logits → ÷T → top-k → top-p → softmax → sample
This code from the notes follows exactly that order:
def sample(logits, temperature=1.0, top_k=None, top_p=None):
logits = logits / temperature
if top_k is not None:
values, indices = torch.topk(logits, top_k)
logits = torch.full_like(logits, float('-inf'))
logits.scatter_(-1, indices, values)
if top_p is not None:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative prob above threshold
sorted_mask = cumulative_probs > top_p
sorted_mask[..., 1:] = sorted_mask[..., :-1].clone()
sorted_mask[..., 0] = False
indices_to_remove = sorted_mask.scatter(-1, sorted_indices, sorted_mask)
logits = logits.masked_fill(indices_to_remove, float('-inf'))
probs = F.softmax(logits, dim=-1)
return torch.multinomial(probs, num_samples=1)
Piece by piece:
- Temperature: divide every score by
temperature.
- Top-k:
torch.topk grabs the k largest scores and their positions; fill the whole row with −∞, then scatter_ puts those k scores back where they were.
- Top-p: sort the scores from largest to smallest, apply softmax, and keep a running total with
cumsum. Any position where the total goes past top_p is marked for removal.
- The small but important detail:
sorted_mask[..., 1:] = sorted_mask[..., :-1].clone() shifts every mark one place to the right, and sorted_mask[..., 0] = False means the top word is never removed. That way the word that just crosses the threshold gets to stay (salad, in our example). The sorted marks are then mapped back to the original positions and filled with −∞.
- Sample: softmax turns the scores into probabilities, and
torch.multinomial draws one token accordingly.
Intuition: In one sentence: temperature controls how random the pick is, while top-k and top-p control how big the pool of candidates is.
Sampling blocks the gradient
So far sampling has only happened while generating text, where we never need derivatives. Now switch to training. Suppose that somewhere in the middle, the network picks one of a few options, uses that choice in later computations, and ends up with a loss:
z → softmax → sample → y → ⋯ → L
To train everything before the choice we need the gradient of the loss with respect to the scores z, passed back from the loss by backpropagation. But when it reaches the sampling step, the chain breaks.
Why? Take the simplest case: two words, A and B. A's score is z, B's is fixed at 0:
pA=ez+e0ez
Freeze the random number at, say, 0.6: whenever pA>0.6 we pick A, otherwise B. Now slowly turn z up: the output stays B, until at one point (z≈0.41) it suddenly jumps to A and stays A.
That's a step function. Each step is perfectly flat, so the derivative there is zero, and right at the jump it doesn't even exist. A derivative of zero tells you that nudging z either way makes no difference, so the network gets no learning signal at all. Argmax is exactly the same kind of step.
How do we get around it? Three tools: Gumbel-Max, Gumbel-Softmax and the straight-through estimator. (Another route, policy gradients, is saved for episode 18.)
Gumbel-Max: moving the randomness into noise
Here's a strange way to draw lots: instead of sampling by probability directly, add a little random noise to every score, then pick the largest:
k=argimax (zi+gi),gi∼Gumbel(0,1)
Each gi is drawn independently from the Gumbel distribution. Generating it is easy: take a uniform random number u between 0 and 1 and compute
g=−log(−logu)
The Gumbel distribution peaks around zero, with a long tail trailing off to the right, so every now and then it spits out a fairly large positive number.
Try it on the four scores from the temperature section, 2, 1, 0.5, −1:
- First draw: the noise gives every score a random shove; afterwards the biggest is "nice".
- Second draw: "good" gets lucky, is shoved a long way, and overtakes "nice".
- Third draw: "nice" wins again.
Higher scores win more often, but lower scores still have a shot at an upset. Repeat a thousand times and count the wins: the shares match the softmax probabilities almost exactly, 0.61, 0.22, 0.14 and 0.03.
That's no coincidence. You can prove rigorously that adding Gumbel noise and taking the max is exactly equivalent to sampling from the softmax probabilities (that is, from the corresponding categorical distribution).
Intuition: So what's the point? All of the randomness has moved into the noise g, which has nothing to do with z; the scores just get something added to them, and addition is differentiable. Now the only thing still blocking the gradient is the argmax on the outside.
Gumbel-Softmax: swapping argmax for softmax
We've already met a softened argmax: softmax with a temperature, which gets closer to argmax the lower the temperature. So swap the argmax for a softmax and divide by a temperature τ. That's Gumbel-Softmax:
argimax(zi+gi)⟶y=softmax(τz+g)
Freeze the noise from the second draw and watch the output y as τ changes:
- tiny τ: y is almost a one-hot vector (a single 1, zeros everywhere else), matching what Gumbel-Max picked;
- larger τ: y gets smoother, a soft blend of several options mixed in proportion.
Whatever τ is, y is a smooth function of z, since softmax is differentiable everywhere. The gradient passes through the softmax and the addition, all the way back to z.
Watch out: This is easy to get wrong. The point of Gumbel-Softmax is not to make things differentiable; plain softmax already is. The point is to make the output random, something you can sample, while keeping it differentiable.
Compare three approaches:
plain softmax:true sampling:Gumbel-Softmax:y=softmax(z)y=one_hot(sample(softmax(z)))y=softmax((z+g)/τ)
| Approach |
Random |
Discrete |
Differentiable |
| Plain softmax |
no |
no |
yes |
| True sampling |
yes |
yes |
no |
| Gumbel-Softmax |
yes |
~ at low τ |
yes |
Plain softmax is deterministic, giving the same soft blend every time. True sampling is random and discrete, but not differentiable. Gumbel-Softmax gives you random exploration and gradients at once.
The temperature τ is a trade-off. With a large τ the gradients are smooth and stable, but the output is far from a true discrete choice; with a small τ the output is close to discrete, but the gradients become very unstable. So in practice people often anneal τ, lowering it slowly: play it safe at first, then creep closer to a true discrete choice.
Straight-through: pretend it's the identity going backward
The last tool is even more blunt: the straight-through estimator (STE).
- Forward pass: play it straight and apply the non-differentiable function, y=f(x).
- Backward pass: pretend f is the identity function (a function that does nothing) and pass the upstream gradient that y received straight to x, untouched:
∂x∂L=∂y∂L
Example: rounding
Rounding's graph is a staircase, so its derivative is zero everywhere except at the jumps, where it doesn't exist. In the backward pass STE uses the slope of the dashed line y=x instead: 1.
- Let x=1.8, so y=2 after rounding. The target is 3 and the loss is L=(y−3)2=1.
- ∂y∂L=2(y−3)=−2. The true derivative would multiply this by 0, so nothing gets back; STE hands the −2 straight to x.
- Gradient descent steps against the gradient. With a learning rate of 0.15:
x←x−0.15×(−2)=x+0.3
So x goes from 1.8 to 2.1 to 2.4. Throughout, y stays at 2, so it looks like nothing is happening, but x is quietly moving in the right direction. Once it reaches 2.7 it rounds to 3, and the loss drops to zero.
Why the cheat works
Rounding is monotonically increasing: when x grows, y stays the same or grows too. So the direction is right, even if the size is off.
Watch out: If f were decreasing, then as x grows y would shrink, and STE would point in exactly the wrong direction. That's why it's mostly used on increasing step functions like rounding and quantization.
The code trick
In code there's a neat trick, where detach means "treat this term as a constant during backpropagation":
y=x+detach(f(x)−x)
- Forward: y=x+f(x)−x=f(x).
- Backward: the detached term is a constant with zero derivative, so ∂x∂y=1+0=1.
The same trick works with Gumbel-Softmax: a hard one-hot vector going forward, the soft gradient going backward. That's straight-through Gumbel-Softmax:
y=yhard−detach(ysoft)+ysoft
STE is used all the time in model quantization; we'll meet it again in episode 16.
Recap
How you pick words shapes what comes out. Greedy decoding is deterministic but repeats itself and is short-sighted; random sampling adds variety but needs protection from the long tail. Temperature stretches or squeezes score gaps (pi/pj=e(zi−zj)/T), tuning randomness without changing the ranking. Top-k, top-p and min-p cut the tail with different thresholds, a repetition penalty pushes down tokens already used, and in code the pipeline runs "÷T → top-k → top-p → softmax → multinomial". During training, sampling and argmax are step functions that block the gradient: Gumbel-Max moves the randomness into noise that doesn't depend on z, Gumbel-Softmax replaces the argmax with softmax((z+g)/τ) to get randomness and gradients together, and STE uses the real function forward and the identity backward, which works for monotonically increasing operations like rounding and quantization. All episode we generated one token at a time, rerunning the whole model for each one. Can we save work we've already done instead of redoing it? That's the KV cache, next episode.