# Chapter 3: Tokens and next-token guessing

Part of the course “AI from Zero to Autonomous Agents” (https://llm.yoga/en). Page for humans: https://llm.yoga/en/03-tokens

*A language model doesn’t write, it guesses, piece by piece. Once you understand the guessing, you understand sampling, hallucinations and speed.*

About 30 min to read · about 20 min hands-on exercise

**Start with the missions**

This chapter also comes as 3 short missions with a case, a decision and feedback, about 10 minutes each:

- [3.1 Why does our German chatbot cost more?](https://llm.yoga/en/einsatz-3-1.md)
- [3.2 Why does it answer differently every time?](https://llm.yoga/en/einsatz-3-2.md)
- [3.3 The bot made up a source](https://llm.yoga/en/einsatz-3-3.md)

For agents, this page is split into 4 parts so that each part can be fetched in full. Read the parts the question needs.

## Parts

### Part 1: https://llm.yoga/en/03-tokens-1.md

- **Getting started**: Say “The sky is …” to a group and let the others finish the sentence.
- **What a token is**: A neural network computes with numbers, not letters.
- **How a tokenizer is built: byte pair encoding**: Most of today’s tokenizers are built with a method called byte pair encoding (BPE).
- **Next-token guessing: predicting the next token**: Now to the core. A language model receives a sequence of token IDs and returns a long list of numbers: for each of the 151,936 tokens in the vocabulary, a score for how well it would fit next.

### Part 2: https://llm.yoga/en/03-tokens-2.md

- **From logits to probabilities: softmax**: Logits are arbitrary numbers, negative ones included.
- **Picking: greedy, sampling, temperature**: Exactly one token has to come out of the distribution.
- **Cutting off the tail: top-k and top-p**: Temperature bends the distribution but removes nothing.
- **What you can still set with cloud APIs**: If you work locally, you hold all the dials.

### Part 3: https://llm.yoga/en/03-tokens-3.md

- **Why models hallucinate**: With what you’ve learned so far, you can understand where hallucinations come from.
- **The second meaning: token rate**: In everyday use, “token rate” has a second meaning: how fast does a model produce tokens?
- **Exercise: watch the model guess**: Goal: you see the probabilities with which a model picks the next token, convert logprobs into percent, and watch how temperature and seed change the result.
- **Common misconceptions**: A token is a word.

### Part 4: https://llm.yoga/en/03-tokens-4.md

- **Review questions**: 1. Three candidates have the logits 2, 1 and 0.
- **Go further**: Sennrich, Haddow, Birch: Neural Machine Translation of Rare Words with Subword Units (2015), BPE for language models.
