Tokenwerk · The LLM textbook

Chapter 21 · IV · Training and evaluating · 6 minutes

From scores to text

The model delivers percentages, but who decides which word actually gets written? Always the most likely, or roll the dice a little? This is where boring, creative and completely incoherent part ways.

From the next word to a whole text

The model can compute a probability distribution for the next token. A text only comes out of it when we repeatedly choose a token, append it and ask the model again, just like in the guessing game from chapter 1. This chapter is about how we choose. The choice changes the character of the text enormously: from monotonous to chaotic.

A detail: the model delivers logits for every position in the text. For writing on, we only care about the last position, because it predicts the token after the entire text so far. Choose a token, append it, compute again.

python
with torch.inference_mode():
    logits = model(ids[:, -cfg.context:])[:, -1, :]
    next_id = torch.argmax(logits, dim=-1, keepdim=True)
    ids = torch.cat([ids, next_id], dim=1)

The weights don't change while doing this; writing isn't learning. In this simple version the whole text is recomputed at every step. Slow, but easy to check. How to save the duplicate work (with a KV cache) is shown in the chapter on efficiency.

Greedy: always the best

The simplest rule is called greedy: always take the token with the highest score. Same model, same beginning: same text, every time.

Sounds sensible, but it has pitfalls. The best next word each time doesn't necessarily lead to the best whole sentence, like hiking where the steepest path downhill can end in a dead end. And small models like to get stuck in loops with greedy: “and then and then and then…”. A little randomness can break such loops. But careful: if a model really rates “and and and” highly, that is a weakness of the model that you can't roll away with dice.

Rolling the dice with temperature

Instead of always taking the best, you can draw according to the probabilities: a token with 60 percent comes up in 6 out of 10 cases, one with 10 percent in one out of 10. That is called sampling.

The temperature sets how boldly the dice are rolled. The logits are divided by the temperature before softmax. Low temperature (for example 0.3): the favorites are preferred even more strongly; the text becomes cautious and predictable. High temperature (for example 1.5): outsiders get a chance too; the text becomes surprising, or incoherent.

python
logits = logits / temperature
probs = torch.softmax(logits, dim=-1)
next_id = torch.multinomial(probs, num_samples=1)

In the project, --temperature 0 simply means greedy (of course there is no division by zero). A fixed seed makes the same “randomness” repeatable. A different seed doesn't mean different knowledge, just different dice rolls.

Top-k: only the best go into the lottery drum

When rolling dice, a completely unsuitable token can get drawn now and then; at 0.1 percent it is rare, but with a thousand words it does happen. Top-k prevents that: only the k tokens with the highest scores are allowed into the lottery drum at all. All others get −∞, so zero percent. With k = 1 that is greedy again.

python
k = min(top_k, logits.size(-1))
threshold = torch.topk(logits, k).values[..., -1, None]
logits = logits.masked_fill(logits < threshold, float('-inf'))

Small k: less nonsense, but also less variety.

Top-p: as many as needed

Top-p (also nucleus sampling) is more flexible. Instead of a fixed number, you take top candidates until together they make up at least p of the probability.

Example with the probabilities [0.6,0.25,0.1,0.05] and p = 0.8: the first two give 0.85, which is enough, so two stay in the drum. With p = 0.95 it is three. The clever part: if the model is sure, few candidates remain. If it is unsure, more get to play. At least one always remains.

Top-k and top-p can also be combined. Then the order matters; in the project it is documented.

When does the model stop?

During training the model saw the EOS token after every document, and later after every answer. So it has learned when a text is over. When generating, we stop as soon as EOS is drawn, or at the latest after a set maximum number of tokens. Without EOS training the model would never stop sensibly but just keep babbling.

Other special tokens like PAD, BOS or the role markers shouldn't show up in the middle of an answer. That is why our sampler blocks them when drawing; EOS stays allowed.

The context window forgets

If the text gets longer than the context window, our simple sampler only sees the last tokens. Whatever came before (maybe the original question!) is gone for the model. That is why chatbots sometimes “forget” the beginning of long conversations.

In the learning project it is best to keep prompts and answers short. Real chat applications need a well-thought-out strategy for which old messages get shortened.

Testing generation

In step 6 of part VII you build exactly this loop yourself, with temperature and top-k. Then try the same prompts with greedy and two different temperatures. Pay attention to readability, repetition, whether and where it stops, and the format. And don't only show the nicest result! With a small training text, the model will repeat some things from memory; that is to be expected.

In the experiment

Draw a token several times from a distribution with three candidates. After a few draws the frequencies often don't match the percentages at all. Only after many draws do they get close. That is exactly why a single generated text says so little about how good a model is.

Key points

  • Text is produced token by token: compute the distribution, choose one, append, repeat.
  • Greedy always takes the best. Sampling rolls dice by probability; the temperature sets how bold.
  • Top-k and top-p throw out unlikely candidates. EOS says when to stop.