Skip to content
mentoor

Topic 5 of 6 · 5 min read

Sampling text from your trained model

Goal: Implement a generation loop and predict how changing temperature and top-k will change the trained model's output.

Generation is a loop: feed the text so far, take the scores for the last position, turn them into probabilities, pick one token, append it, and repeat.

Check yourself · 1 of 3

Which logits does a GPT use to choose the next token during generation?

Choose one answer

Why it matters

This loop is what every chat model runs, one token at a time. Temperature and top-k are the same knobs you meet in API settings. Once you have written them, those settings stop being mysterious.

How to do it

  1. Crop the context. The model only has position embeddings for block_size tokens. Use idx[:, -block_size:] before every forward pass.
  2. Take the last position. Logits have shape (B, T, V). Only logits[:, -1, :] predicts the next token.
  3. Apply temperature. Divide the logits by temperature. Below 1 makes the distribution sharper (safer, more repetitive). Above 1 flattens it (more varied, more errors). Temperature 0 is not allowed as a divisor; treat it as picking the largest score.
  4. Apply top-k. Keep only the k highest scores and set the rest to -inf. This cuts off the long tail of unlikely tokens that cause occasional garbage.
  5. Softmax, then sample with torch.multinomial. Sampling, not always taking the top choice, is what makes outputs differ between runs.
  6. Append the new id to idx and loop. Decode only at the end.

Run under model.eval() and torch.no_grad(). Start with a prompt such as a newline character, or encode a few real words.

Before and after

A weak loop always takes the argmax:

next_id = logits[:, -1, :].argmax(dim=-1, keepdim=True)

A small model then loops: "the king the king the king". Greedy decoding picks the single most likely character every time, and one repeated pattern is self-reinforcing. Sampling with temperature 0.8 and top-k of 40 breaks the loop and gives varied text, while top-k keeps rare characters from appearing.

Why a small model writes fluent nonsense

A model with under a million parameters trained for minutes learns spelling, line breaks, speaker names and the rhythm of verse. It does not learn facts or meaning, because nothing in next-character prediction on one file forces it to. The output looks like Shakespeare from a distance and says nothing up close. Larger models fail the same way less often, not never: they also produce fluent text with no guarantee it is true.

What goes wrong

  • No cropping. Once the text is longer than block_size, the position table is indexed out of range and the loop crashes.
  • Forgetting eval(). Dropout stays on and the output is noisier.
  • Top-k larger than the vocabulary. torch.topk raises an error; use min(k, V).
  • Judging quality from one sample. Sampling is random; read several outputs, and set a seed when comparing settings.

Examples

Generation with temperature and top-k

@torch.no_grad()
def generate(model, idx, max_new_tokens, block_size, temperature=0.8, top_k=40):
    model.eval()
    for _ in range(max_new_tokens):
        logits = model(idx[:, -block_size:])[:, -1, :] / temperature
        if top_k is not None:
            v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
            logits[logits < v[:, [-1]]] = float("-inf")
        probs = F.softmax(logits, dim=-1)
        idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
    return idx

Call it with idx = torch.zeros((1, 1), dtype=torch.long) and print decode(out[0].tolist()). Try temperature 0.3 and 1.5 on the same seed and compare.

Key points

  • Generation is a loop that feeds the last block_size tokens, samples one next token from the last position's logits and appends it.
  • Temperature divides logits: below 1 sharpens the distribution, above 1 flattens it.
  • Top-k keeps only the k most likely tokens, which removes rare garbage tokens while keeping variety.
  • Always taking the argmax makes small models repeat themselves, so sampling with multinomial is the usual choice.
  • A tiny model learns surface form such as spelling and layout, not facts, so fluent output is not evidence of understanding.

Common mistakes

  • Skipping the context crop and crashing once the generated text exceeds block_size.
  • Using argmax and concluding the model is broken when it only repeats a loop.
  • Setting temperature to 0 and dividing by zero.
  • Comparing sampler settings without fixing the random seed.

Check yourself · 2 of 3

You raise temperature from 0.7 to 1.5. What happens to the output?

Choose one answer

Check yourself · 3 of 3

A generation loop works for 200 characters then fails with an index error on the position embedding. What is missing?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic