Chapter 02
Text, Tokens, and the Prediction Objective
On this page
To train a language model, we need examples of what should come next and a numerical measure of how well the model predicts it. Tokenization and cross entropy provide those two ingredients.
From a string to a sequence¶
A model's vocabulary associates each allowed token with an integer ID. Tokenization divides text into vocabulary entries and emits their IDs; decoding reconstructs text from those entries. A token need not coincide with a word. A common word might occupy one position, a rare identifier several positions, and a space part of the same token as the text that follows it.
Model work depends on token count, not page count. A page of prose and a page of unfamiliar source-code identifiers can produce different sequence lengths. The same document can also have different lengths under two tokenizers. A summarization service must therefore measure the actual encoded input before deciding whether a document fits. This requirement follows from the representation, regardless of what the generated text will be used for.
There are several ways to construct a vocabulary. Byte-pair encoding learns a ranked list of merges between adjacent pieces. In a deliberately small example, merging l with o and then lo with w turns the bytes of low low into [low, space, low]. Encoding a new string applies the learned merge ranks; it does not relearn the vocabulary for each request. The subword BPE paper develops this segmentation approach. Unigram tokenization instead chooses a segmentation using probabilities over candidate pieces; SentencePiece describes implementations that can learn directly from raw sentences.
Real tokenizers also define normalization, reserved symbols, and message boundaries. The model and tokenizer are a pair. Swapping two token IDs without swapping their corresponding model rows changes the meaning of every affected input, even though the tensor shapes still match. Version the tokenizer and chat template with the weights.
Make one training example¶
Consider the sequence [BOS, A, B, EOS], where BOS and EOS mark its beginning and end. The model is asked to predict A after BOS, B after BOS followed by A, and EOS after the complete prefix. Inputs and targets are offset by one position:
| Input prefix ends with | Target to predict |
|---|---|
| BOS | A |
| A | B |
| B | EOS |
Each input position predicts the following token. During training the complete example is known, but a prediction must not read its target or any later position.
Training supplies the known prefix for each prediction. This is called teacher forcing. The predictions can be computed together because all input tokens are already known. Generation cannot use that shortcut: after the prompt, it must first select a token before it knows the next prefix.
The probability assigned to a complete sequence is the product of these conditional probabilities. Taking logarithms turns the product into a sum:
Each factor predicts one token from the preceding tokens; S is sequence length.
This factorization does not specify how the model summarizes the prefix. A bigram model can use only the preceding token; a transformer can use a much longer context. Both can be trained on next-token targets. Architecture determines the information available to each prediction; the objective determines how that prediction is scored.
Score a prediction with cross entropy¶
At one position, suppose the model emits logits [0, 0] for two possible tokens. A logit is an unnormalized score. Softmax exponentiates the scores and divides by their sum, giving probabilities [0.5, 0.5]. Adding the same constant to both logits changes neither probability; their relative values matter.
If the observed target is the first token, its loss is -log(0.5), approximately 0.693 using the natural logarithm. Assigning it probability 0.9 reduces that loss to about 0.105. Assigning it probability 0.1 increases the loss to about 2.303. Minimizing this loss therefore rewards probability on the target rather than merely rewarding whether the target ranks first.
For valid target positions with probabilities 0.5, 0.25, 0.5, the mean loss is (0.693 + 1.386 + 0.693)/3, approximately 0.924 nats. Perplexity is the exponential of that mean, about 2.52. It summarizes predictive loss in token units. It is not the fraction of correct answers to user questions.
Implement the calculation through log-sum-exp rather than directly exponentiating arbitrary large logits. Subtracting the largest logit before exponentiation avoids overflow while preserving the probabilities. The repository's masked_token_loss reference makes the calculation explicit. Later, the training chapter will differentiate the loss and use it to update weights.
Decide which positions count¶
In supervised training for summarization, an example can contain an instruction, a source document, and a target summary. The whole sequence provides context, while only the summary may contribute prediction targets to the chosen loss. This distinction explains why three different masks appear in implementations:
| Mask | Question it answers |
|---|---|
| Attention mask | Which input positions may this prediction read? |
| Padding mask | Which positions contain actual sequence data? |
| Loss mask | Which target positions contribute to the training objective? |
For a causal model, the attention mask prevents a position from reading future input positions. Otherwise a prediction could see the answer it is being trained to predict. A loss mask has a different purpose. Excluding the source document from the loss does not hide it from attention: the model still needs that document to predict the summary.
Padding equalizes tensor sizes for batches of unequal sequences. A padded position should not become an ordinary training target or an eligible key by accident. Some APIs represent an ignored target with a sentinel such as -100; that value is not a vocabulary token. Its meaning depends on the loss implementation. Inspect one short example with its decoded tokens, shifted targets, and mask values before trusting a larger pipeline.
The same care applies when packing documents together. Concatenating two unrelated documents and allowing attention across their boundary creates a different training example from treating them independently. If independence is intended, use a block-diagonal causal mask and exclude artificial boundary targets. Part II develops this into a reproducible data transformation.
The tokenizer also changes cost¶
Let the vocabulary have V entries and the model's hidden vectors have width D. An embedding table contains V*D parameters. The output projection converts a hidden vector back into vocabulary logits and has the corresponding dimensions. Some models share these weights, but sharing storage does not remove the output computation.
For D=4096, increasing a tied vocabulary from 32,000 to 128,000 entries adds 96,000*4096, or about 393 million parameters: roughly 786 MB at two bytes each. The larger vocabulary may shorten sequences enough to offset some computation elsewhere. Whether it helps depends on the actual text, including languages and identifiers that fragment differently.
That is also why per-token perplexity is not directly comparable across different tokenizers. The prediction units have changed. Compare on the same raw text, use a compatible byte-normalized likelihood when appropriate, and evaluate the tasks the application needs. Lower predictive loss is evidence about the objective; whether a summary preserves key facts or generated code passes its tests requires additional evaluation.
From prediction to computation¶
We now know the model's input, output, and objective. What remains hidden is the function between token IDs and logits. The next chapter opens that function: embeddings provide vectors, attention exchanges information across positions, and feed-forward layers transform it. Keep the shifted-target example in mind. Every operation at a position must respect the same restriction on which prefix it can see.
Exercises and worked answers¶
- A user prompt has no loss targets. Can changing it change the training gradient? Yes. It remains context for the supervised response, so it can change response predictions and their gradients.
- Why can a model improve loss without improving top-choice accuracy? Raising the target probability from 0.1 to 0.2 reduces cross entropy even if another token remains the most probable.
- What should a packing test compare? Two examples processed separately against their packed, independently masked form. Compare valid-position logits and total supervised loss with matching position conventions and numerical tolerance.
- Why must a restored checkpoint use the same tokenizer? Token IDs select learned rows. Shape compatibility alone does not preserve those meanings.