Decoding Strategies for Controlled Text Generation
An LLM generates text by predicting the next token from the current context, and the process repeats to extend that context.
Try it: Text Vectorization: Tokens to Vectors
The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.
How it works
- Standardize: lowercase and delete punctuation.
- Split on whitespace into tokens.
- Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
- Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
- Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.
Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.
Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.
Loading the simulation…
Running a Generation Call First
This article starts with behavior rather than theory. You run a simple text generation call that continues a short starting phrase, observe what it prints, and then work out the rule that explains the result. The call takes the starting phrase, converts it into a sequence of token IDs, extends those IDs with new tokens, and converts the result back into text for printing. Each stage of that pipeline matters for the questions later in this article.
The source assumes that the model, the configuration GPT_CONFIG_124M, the functions text_to_token_ids and token_ids_to_text, and the tiktoken library already exist from earlier in the course. This article does not redefine them. Treat them as given inputs to a single call. Notice that the starting phrase enters the call as a sequence of token IDs produced by text_to_token_ids, not as raw text.
What do you think happens?
Suppose you run this exact generation call three times in a row, with the same model, the same starting phrase, and the same settings. Will the printed text be the same each time, or will it change?
Reveal answer
The printed text is the same each time
The default strategy is greedy decoding, which always selects the single highest-scoring token. For the same starting context, that rule picks the same tokens every time, so the same output repeats. Keep this prediction in mind, because it becomes the basis for the debugging questions later on.
Tracing the Next-Token Loop
A large language model generates text one token at a time. At each step, the model produces a set of output scores over its vocabulary, and a rule must turn those scores into one actual choice. The source describes generation as a sequence of steps, one for each new token. The generation call takes a parameter that sets how many new tokens to produce. In the call described in the source, that parameter is max_new_tokens=25.
The step that matters most is what happens after a token is chosen. Each selected token becomes part of the context that informs the next prediction. This is why the output extends the starting phrase instead of being a fixed reply. The loop is: score the vocabulary, select one token, append it to the context, and repeat until the token budget is used up. The source describes this behavior but does not show the internal code of the loop, so the diagram below summarizes behavior, not an implementation.
Following a toy context through three steps
A toy vocabulary has four tokens: the, a, cat, sat. The starting context is the phrase 'The'. Greedy decoding is used, and three new tokens are requested. Trace how the context grows.
- 1Step 1
The model scores all four vocabulary tokens for the context The. Greedy decoding picks the highest-scoring token, which is cat. The context becomes The cat.
- 2Step 2
The new context The cat is passed back to the model. Its scores differ from step 1 because the context has changed. The highest-scoring token is sat. The context becomes The cat sat.
- 3Step 3
The context The cat sat produces new scores. Suppose the highest-scoring token is the. The context becomes The cat sat the, and the token budget of three is used up.
The output extends the starting phrase by three tokens: cat, sat, the. Each choice was made from the context that included all earlier choices.
Choosing the Top-Scoring Token
The source gives the selection rule precisely. At each generation step, the model assigns a probability score to every token in its vocabulary, and the generated token is the one with the largest probability score among all of them. The choice is not a random draw from the distribution. It is always the top-scoring candidate. This single rule decides which word-piece comes next under the default strategy.
This procedure is called greedy decoding. Greedy decoding converts model outputs into probability scores and selects the token with the highest score. The source states that, by default, the next token is generated using greedy decoding. Unless a different strategy is specified, the model therefore takes the top-scoring candidate at every step, and the selection rule contains no randomness.
Tracing Unexpected Output to Its Inputs
Because greedy decoding always picks the same token for the same context, repeated runs on the same starting context produce the same outputs. This gives you a debugging rule. If a generation result changes between runs, the cause is in the inputs, not in randomness inside the selection rule. The source names the inputs to check: the starting context, the generation settings, the model, and the tokenizer.
When an output surprises you, write down the exact starting phrase, the token IDs it produced, the settings, the model, and the tokenizer before you change anything. Comparing these inputs between a matching run and a non-matching run usually shows where the difference came from.
Sampling and Temperature Reshape the Choices
Greedy decoding is not the only option. Probabilistic sampling is a different decoding strategy that works from the same probability scores but does not fix the choice to the single highest one. The source gives its purpose: using probabilistic sampling, along with temperature scaling, we can influence the diversity and coherence of the generated text. The two techniques are presented together because they are applied as a pair when shaping how the model writes.
Greedy Decoding Compared With Sampling
| Aspect | Greedy decoding | Probabilistic sampling |
|---|---|---|
| Selection rule | Always the top-scoring token | Chooses according to probability scores rather than fixing the top one |
| Repeated runs on same context | Same output every run | Not fixed to a single choice, so output can vary |
| Diversity of text | Lower, since the same token is always picked | Can be shaped together with temperature scaling |
| Default | Yes, applies unless another strategy is specified | Used when specified |
Greedy decoding and probabilistic sampling both start from the same probability scores but differ in the token they select.
The choice of strategy matters because two very different outputs can come from the same model simply because the decoding rule differs. The model's scores can be identical while the written text is predictable under greedy decoding and varied under sampling. Knowing which rule is in effect is therefore part of explaining any generated result.
Judging Quality With Training and Validation Losses
Choosing a decoding strategy raises a practical question: how do you know whether the generated text is good? The source gives one approach. Training and validation set losses can be used to gauge the quality of text generated by an LLM during training. The losses measured on the training and validation data serve as a signal about how well the model is producing text while it is being trained.
The two halves of the topic connect here. Decoding strategies determine how text is produced from the scores, while loss measurements give a way to gauge the quality of the text the model generates. The source presents these as separate pieces of information, so keep the decoding rule and the quality signal distinct when you reason about a result. The source does not describe a specific pattern in the loss curves that indicates good generalization, so this article does not claim one.
Common Mistakes With Decoding
Common mistake Assuming sampling is the default decoding strategy
What it looks likeExpecting a different completion each time you rerun a call without changing any setting.
Why it failsThe source states that by default the next token is generated using greedy decoding.
Do this insteadAssume greedy decoding unless the call specifies a different strategy.
Common mistake Expecting different outputs from identical greedy runs
What it looks likeRunning the same starting phrase three times under greedy decoding and waiting for three different results.
Why it failsGreedy selection always picks the same top-scoring token for the same context, so the outputs repeat.
Do this insteadIf the output changes, look for a changed input such as the starting context, settings, model, or tokenizer.
Common mistake Passing raw text where token IDs are expected
Why it failsThe source passes the starting phrase through
text_to_token_ids, so the generation function receives token IDs.Do this insteadConvert the starting phrase to token IDs first, and convert the output back to text with token_ids_to_text.
Common mistake Treating temperature scaling as a standalone strategy
Why it failsThe source presents temperature scaling as a technique used in conjunction with probabilistic sampling.
Do this insteadThink of temperature as an adjustment applied alongside sampling.
Common mistake Reading a loss value as the generated text itself
Why it failsLosses are a signal about generation quality measured during training, not a sample of the output.
Do this insteadUse training and validation losses to gauge quality, and read the generated text separately.
Predicting Output From the Inputs
A colleague runs a generation call with greedy decoding twice on the same starting phrase. The first run prints one continuation, and the second run prints a different continuation. List the inputs you would check first, in order, and explain what each check would tell you.
Hints
- Under greedy decoding, the same context always selects the same top-scoring tokens.
- The source names the starting context, generation settings, model, and tokenizer as the inputs that determine the output.
- Start with the inputs that changed between the two runs before looking at the model or tokenizer.
Key Takeaways
- An LLM generates text one token at a time, and each chosen token is appended to the context that informs the next prediction.
- By default, the next token is generated with greedy decoding, which selects the token with the largest probability score in the vocabulary.
- Because greedy selection is deterministic for a given context, repeated runs produce the same output, and a changed result points to a changed input such as the starting context, settings, model, or tokenizer.
- Probabilistic sampling and temperature scaling are used together to influence the diversity and coherence of generated text.
- Training and validation set losses are one way to gauge the quality of text generated by an LLM during training.