Contents Working with Large Language Models Code Course home

Chapter 20Steering LLMs: Decoding and Prompting

After this chapter you will be able to

  • explain why greedy decoding can miss the best sequence and how beam search recovers it;

  • compute the effect of temperature, top-kk and top-pp on a distribution by hand;

  • say why top-pp replaced top-kk;

  • write zero-shot, few-shot and chain-of-thought prompts for one task and say what each costs;

  • choose the cheapest level of the steering hierarchy for a failure.

This chapter builds on Chapter 19, whose trained models produce the distribution this chapter turns into text.

A distribution is not an answer

Part IV ends with a trained model which, given a context, produces a probability distribution over the next token. This is Chapter 10’s task at transformer scale. A distribution is not an answer, though, so something has to choose.

That choice is decoding, and it is made outside the model after training is over, since nothing in this chapter changes a single weight. Two levers exist at that point, where decoding decides how a token is picked from the distribution and prompting decides what the distribution is conditioned on. Both are cheap, both are reversible, and both change the output more than most people expect.

Decoding: from distribution to token

Greedy, and where it fails

The obvious rule is to take the highest-probability token at every step, and it fails in a way that is easy to construct. Take a tiny model whose whole next-token tree is written out.

prefix choices greedy takes
(start) the 0.40, a 0.35, one 0.25 the
the cat 0.55, dog 0.45 cat
the cat sat 0.60, ran 0.40 sat

Greedy returns the cat sat, with probability 0.40×0.55×0.60=0.13200.40 \times 0.55 \times 0.60 = 0.1320. Rank every three-word sequence the model can produce.

rank sequence probability
1 a bird sang 0.2992
2 the cat sat 0.1320
3 the dog sat 0.0900
4 the dog ran 0.0900
5 the cat ran 0.0880
Figure 20.1. The next-token tree behind the greedy example. Greedy follows the heavy arrows and returns the cat sat at 0.13200.1320. The best sequence, a bird sang at 0.29920.2992, starts with the lower first choice.

The best sequence is more than twice as likely as the one greedy found, and greedy went wrong at the very first step. It took the at 0.400.40 over a at 0.350.35 and could not see that a leads to bird at 0.900.90 and then sang at 0.950.95.

This is the general shape of the failure. A high-probability token can sit in front of a low-probability continuation, and a rule that looks one step ahead cannot know.

Beam search

Beam search keeps the best ww partial sequences at every step instead of one.

width best found probability optimal?
1 the cat sat 0.1320 no
2 a bird sang 0.2992 yes
3 a bird sang 0.2992 yes
5 a bird sang 0.2992 yes

Width 11 is greedy by definition, width 22 already finds the optimum here, and wider beams cost more for nothing. Beam search is not guaranteed to find the best sequence, because it searches more of the space than greedy and less than all of it.

It also has a known bias, since optimising total probability favours short, safe, generic output. This is acceptable in translation where there is a right answer, and it is a problem in open-ended generation where the safest continuation is usually the dullest.

Temperature

Sampling introduces variety and temperature controls how much of it. Divide the logits by TT before the softmax, the same as raising each probability to the power 1/T1/T and renormalising.

TT the a one some any entropy
0.0 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000
0.5 0.9903 0.0067 0.0022 0.0005 0.0001 0.0904
0.8 0.9239 0.0408 0.0202 0.0085 0.0036 0.5235
1.0 0.8500 0.0700 0.0400 0.0200 0.0100 0.9094
1.5 0.6585 0.1246 0.0858 0.0541 0.0341 1.7069
2.0 0.5211 0.1495 0.1130 0.0799 0.0565 2.1524
Figure 20.2. Temperature on the seven-token distribution of this chapter. The probability of the top token falls from 11 to about 0.520.52 as TT rises to 22, and the entropy rises from 00 to about 2.152.15 bits. The two curves are drawn on one axis to show that the entropy crosses the probability near T=1T = 1.

The distribution has seven tokens and the table shows the largest five, so a row sums to 0.990.99 and not 11, with each and every holding 0.0050.005 apiece at T=1T = 1. The entropy column counts all seven.

T=1T = 1 leaves the model’s own distribution alone, below 11 it sharpens, and at T=0T = 0 it is greedy with zero entropy because nothing is left to choose, while above 11 it flattens. Both ends have a characteristic failure, since low temperature gives repetitive, safe text while high temperature gives varied text that drifts off topic and eventually stops making sense.

Top-kk, top-pp, and why the second replaced the first

Sampling from the full distribution has a problem, because a vocabulary of 50,00050{,}000 tokens holds a great many implausible options and their combined tail probability is not negligible. Top-kk keeps the kk most likely tokens and renormalises, while top-pp, or nucleus sampling, keeps the smallest set whose probability mass reaches pp. The difference shows the moment you try both on two distributions of different shape.

distribution top four entropy
peaked the 0.85, a 0.07, one 0.04, some 0.02 0.9094
flat red 0.14, blue 0.13, green 0.13, black 0.12 2.9977

Apply a fixed kk to both.

kk peaked: kept mass kept flat: kept mass kept
1 1 0.8500 1 0.1400
2 2 0.9200 2 0.2700
5 5 0.9900 5 0.6400
8 7 1.0000 8 1.0000

Read the k=5k = 5 row. On the peaked distribution it admits four tokens the model had all but ruled out, and on the flat one it discards three tokens that were as good as the ones it kept. The same kk is too loose on one shape and too tight on the other, because kk cannot see the shape. Top-pp can.

pp peaked: kept mass flat: kept mass
0.50 1 0.8500 4 0.5200
0.90 2 0.9200 8 1.0000
0.95 3 0.9600 8 1.0000
0.99 5 0.9900 8 1.0000

At p=0.9p = 0.9 the peaked distribution keeps two tokens while the flat one keeps eight, so the candidate set now follows the model’s own confidence, which is what a fixed kk could not do. For that reason, nucleus sampling became the default.

All of it, on one distribution

strategy the a tokens kept entropy
greedy 1.000 0.000 1 0.0000
temperature 0.7 0.954 0.027 7 0.3467
pure sampling, T=1T=1 0.850 0.070 7 0.9094
temperature 1.5 0.658 0.125 7 1.7069
top-kk, k=3k = 3 0.885 0.073 3 0.6219
top-pp, p=0.9p = 0.9 0.924 0.076 2 0.3882

Every row is the same model and none of them changed a weight. Which row to use follows from the task, since a factual answer wants a low-entropy row while a story wants one of the middle ones.

Run it. code/worked_examples/decoding.py produces every table here. --beam shows greedy losing and beam recovering, --temp sweeps the temperature, --truncate contrasts top-kk with top-pp on both shapes, and --compare prints the last table.

Run it

A next-token distribution flattening and sharpening with temperature, then truncated by top-p
Decoding settings reshape the model's distribution before a word is drawn. Temperature sharpens or flattens it, and top-p cuts off the unlikely tail.
A probability tree where greedy picks the cat sat and beam search of width 2 finds a bird sang
The most likely word at each step does not always lead to the most likely sentence. Beam search keeps several candidates alive and can find a better whole sentence than greedy decoding.

Prompting: programming without weights

The second lever changes what the model is conditioned on. Chapter 19 noted that at sufficient scale a model can perform a task from a description in its input with no gradient update (Brown et al. 2020), and that capability is what makes prompting a technique and not a formatting detail.

Three settings

Zero-shot gives an instruction and nothing else, few-shot adds a handful of worked examples in the prompt (each example is a “shot”), and chain-of-thought asks the model to produce its reasoning before its answer (Wei et al. 2022). The third is the interesting one, and its mechanism is not mysterious.

A model produces one token at a time, each conditioned on what came before. Asking for an answer directly gives it one forward pass to reach the conclusion. Asking for the steps first gives it many, with each step becoming context for the next. Chain-of-thought is therefore not the model thinking harder but the model being given room to compute.

A prompt, taken apart

Take the task a train leaves at 9:40 and the trip takes 2 hours 35 minutes, so when does it arrive? The right answer is 12:1512{:}15, and that gives us something no model can argue with, a checker. The three settings of this section are three ways of writing the same request.

setting prompt
zero-shot Answer with a time in HH:MM only. A train leaves at 9:40 and the trip takes 2 hours 35 minutes. When does it arrive?
few-shot Answer with a time in HH:MM only. Then two worked pairs, such as leaves 8:10, takes 1 hour 20 minutes: 09:30, then the question.
chain-of-thought Work out the arrival step by step, then give the final time on a line starting with “Answer:”.

Each prompt names the output format, which is the first rule below, and each can be scored by one line of code. The zero-shot prompt costs the fewest tokens and gives the model one forward pass to do the addition. The few-shot prompt spends tokens on demonstrations that fix the format. The chain-of-thought prompt spends tokens on room to compute, and it needs a parser for the final line. Run all three on the same model on twenty variants of the problem and the comparison is an experiment, not an opinion, which is what the last problems ask.

What actually helps

Four things help, in rough order of reliability. Be specific about the output, naming the format, the length and the allowed values, because most prompt failures are underspecification, not model failure. Give examples, not adjectives, since two demonstrations of the format you want beat a paragraph describing it. Ask for steps on multi-step problems, which is free and helps most where the task is arithmetic or logical. And put the constraints last, because the instruction nearest the generation point tends to dominate, which is a property of the architecture rather than a rule of style.

What prompting cannot do

Prompting selects from what the model already has, so it does not add knowledge the model lacks and it does not reliably remove behaviour the model learned. Two consequences follow, and they set up two of the chapters that follow. If the model does not know a fact then no prompt will supply it, which is Chapter 22. And if the model’s default behaviour is wrong then prompting patches it case by case and never fixes it, which is Chapter 21.

The steering hierarchy

There are four ways to change what a model does, cheapest first.

method changes cost when
decoding the sampling rule none always available
prompting the conditioning none first thing to try
retrieval the context low missing knowledge
fine-tuning the weights high wrong default behaviour

Work down that list instead of up it, because a great deal of expensive fine-tuning has been spent on problems a decoding parameter would have solved. The order also has a diagnostic use, since if prompting cannot get close then the problem is usually knowledge or behaviour, not phrasing, and that tells you which chapter to read next.

Summary

A trained model produces a distribution over the next token, and decoding turns it into text. Greedy decoding takes the top token at each step and can miss a better sequence whose first token was less likely. Beam search keeps several partial sequences and recovers the optimum in the example, at the price of a bias to short, generic output. Temperature divides the logits before the softmax, sharpening below one and flattening above. Top-kk keeps a fixed number of tokens, and top-pp keeps the smallest set with a given mass, so the candidate set follows the model’s confidence. Prompting changes what the model is conditioned on. Zero-shot, few-shot and chain-of-thought prompts trade tokens for format and room to compute. Most prompt failures are underspecification. The cheapest level that works is chosen first, and a failure that prompting cannot fix points to knowledge or behaviour.

Key terms

greedy decoding. taking the highest-probability token at every step.

temperature. a divisor on the logits that sharpens or flattens the distribution.

nucleus sampling. sampling from the smallest set of tokens whose probability mass reaches pp.

few-shot prompting. giving worked examples in the prompt.

chain-of-thought. asking the model for its reasoning before its answer.

Further reading.

Brown et al. (2020) report in-context learning. Wei et al. (2022) introduce chain-of-thought prompting. Holtzman et al. (2020) is the nucleus sampling paper. Its account of why pure sampling degenerates is the clearest available. Jurafsky and Martin (2025) cover decoding alongside machine translation, where beam search has its longest history. Every strategy here is an argument to transformers’ generate, and its LogitsWarper classes are the operations of this chapter written out one per file, which makes them unusually easy to read.

Practice problems

20.1 Break greedy. Construct a next-token tree of depth three in which greedy decoding is at least three times worse than the optimal sequence. State the general property your construction relies on.

20.2 Beam width. On the tree in this chapter, find the smallest beam width that recovers the optimum. Then modify the tree so that width 22 is not enough, and say what you had to change.

20.3 Temperature by hand. Take the distribution (0.6,0.3,0.1)(0.6, 0.3, 0.1) and compute the result at T=0.5T = 0.5, 11 and 22. Confirm each sums to one, and compute the entropy of each.

20.4 Where kk fails. Construct one distribution where k=5k = 5 is far too permissive and another where it is far too restrictive. Then find a single value of pp that behaves sensibly on both, and explain why one parameter can serve both shapes.

Build and measure

20.5 Chain-of-thought, mechanically. Explain why asking a model for its reasoning before its answer changes what it can compute, in terms of tokens and forward passes. Then name a task where it should not help, and say why.

20.6 Pick a level. For each of these, name the cheapest level of the steering hierarchy that could work, and justify it: (a) output is too repetitive; (b) the model does not know your company’s refund policy; (c) the model answers in American spelling and you need British; (d) the model refuses a legitimate request in your domain.

20.7 Check the library against the table. Put this chapter’s peaked and flat distributions through transformers.TopPLogitsWarper at p=0.5p = 0.5 and p=0.9p = 0.9 and count how many tokens survive each time. All four cells agree with the table above, which is worth confirming and not assuming. Then find min_tokens_to_keep in the signature and describe the distribution on which it would change the answer, and why a library needs it when the definition does not.

20.8 Score the three prompts. Write twenty variants of the train problem with known answers. Run the three prompts of this chapter on one model, parse each answer with a one-line checker, and report accuracy and tokens used for each. Say which prompt you would deploy and what would change your mind.

20.9 Predict the temperature. Before running, predict whether accuracy of the zero-shot prompt rises or falls as the temperature goes from 00 to 1.51.5. Then run it with five samples per variant and compare.

20.10 The same question, differently phrased. Rewrite the zero-shot prompt in three ways that mean the same, and measure the spread of accuracy. Say what a spread of that size implies for claims that one prompt is better than another.

In practice

20.11 Which setting? A support team wants a model to extract an order number from an email. Choose decoding settings and a prompt style, and justify each. Name the failure that each choice protects against.

20.12 A story generator that repeats. A story generator returns the same phrase in a loop. Name two decoding settings you would change, in which direction, and what each would cost in quality.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.