Tokenisation for training
9 min read
From text to IDs
TokenizationConverting text into tokens and their numeric IDs for a particular model and tokenizer. splits text into pieces from a fixed vocabulary and maps each piece to an integer. The model sees only the integers. Always use the tokeniser that belongs to the base model, because a different one would map the same text to different numbers and the model's learned weights would no longer match. Tokens and tokenisers explains how the pieces are chosen.
The program below uses a toy vocabulary with one piece per word, so the steps are easy to read. A real tokeniser splits rarer words into smaller pieces.
vocab = {"<pad>": 0, "<end>": 1, "label": 2, "the": 3, "message": 4, ":": 5,
"i": 6, "cannot": 7, "sign": 8, "in": 9, "access": 10, "billing": 11}
def encode(text):
return [vocab[word] for word in text.lower().replace(":", " : ").split()]
prompt = encode("Label the message : I cannot sign in :")
answer = encode("access") + [vocab["<end>"]]
print("prompt ids:", prompt)
print("answer ids:", answer)It prints:
prompt ids: [2, 3, 4, 5, 6, 7, 8, 9, 5]
answer ids: [10, 1]Each example is a prompt followed by an answer and an end marker. The end marker teaches the model when to stop. Without it, a tuned model may keep generating.
Labels and the -100 convention
For a language model, the labels are the same IDs shifted so that each position predicts the next token. The LossOne number that says how wrong a model's predictions were. For LLMs it is usually cross-entropy: the negative logarithm of the probability the model gave to the true next token. compares those predictions with the labels. Many libraries skip any position whose label is -100, so you can choose which parts of the sequence count.
For an instruction example, you usually want the loss on the answer only. The prompt is given at use time, so there is nothing to learn from predicting it. Setting the prompt labels to -100 puts all the learning signal on the answer.
prompt = [2, 3, 4, 5, 6, 7, 8, 9, 5]
answer = [10, 1]
input_ids = prompt + answer
labels = [-100] * len(prompt) + answer
scored = sum(label != -100 for label in labels)
print("input ids:", input_ids)
print("labels: ", labels)
print(f"scored positions: {scored} of {len(labels)}")It prints:
input ids: [2, 3, 4, 5, 6, 7, 8, 9, 5, 10, 1]
labels: [-100, -100, -100, -100, -100, -100, -100, -100, -100, 10, 1]
scored positions: 2 of 11Only 2 of 11 positions count here. For a short classifier answer that is the point: the model is judged on the label and the end marker. For longer replies, the answer is most of the sequence and the share is much higher.
Padding, truncation and the attention mask
A batch is a rectangle, so short examples are padded to a common length. An attention mask marks real positions with 1 and padding with 0, so the model ignores the padding. The padded positions also get the label -100, so they add nothing to the loss.
batch = [
([2, 3, 4, 10, 1], [-100, -100, -100, 10, 1]),
([2, 3, 4, 5, 6, 7, 10, 1], [-100, -100, -100, -100, -100, -100, 10, 1]),
]
longest = max(len(ids) for ids, _ in batch)
for ids, labels in batch:
gap = longest - len(ids)
print("ids: ", ids + [0] * gap)
print("mask: ", [1] * len(ids) + [0] * gap)
print("labels:", labels + [-100] * gap)It prints:
ids: [2, 3, 4, 10, 1, 0, 0, 0]
mask: [1, 1, 1, 1, 1, 0, 0, 0]
labels: [-100, -100, -100, 10, 1, -100, -100, -100]
ids: [2, 3, 4, 5, 6, 7, 10, 1]
mask: [1, 1, 1, 1, 1, 1, 1, 1]
labels: [-100, -100, -100, -100, -100, -100, 10, 1]Padding to the longest example in each batch wastes less compute than padding everything to one global length. Sorting or grouping examples by length reduces the waste further.
Truncation is the other side of the same problem. If an example is longer than the maximum length, the end is cut, and the answer may be cut with it. Check the longest examples before training, and either shorten the prompt or raise the limit. An answer that is cut off teaches the model to stop mid-sentence.
Inspect one real batch
Before a long run, print one batch from your real pipeline: the decoded text, the IDs, the mask and the labels. Look for four things.
- The prompt text and the answer appear as you expect, including the chat template markers.
- The end marker is present after the answer.
- The labels are -100 where you intended, and only there.
- The padding is on the side the model expects. Some models need left padding for generation.
A data collator is the code that builds these padded batches. The Hugging Face causal language modeling guide shows how to set one up with a real tokeniser.
- TemplateTurn the messages into text with the model's chat template.
- EncodeMap the text to token IDs with the base model's tokeniser.
- Mask labelsSet the labels of the prompt to -100 so only the answer is scored.
- PadFill short examples to the batch length and set the attention mask.
- InspectPrint one batch and check IDs, mask and labels by eye.
Why does the tokeniser matter for training?
A fine-tuned model must read the same token ids it saw in pre-training.
The embeddings are tied to a specific vocabulary, so use the tokeniser that came with the model.
What does truncation do?
An example is 3,000 tokens and the maximum length is 2,048.
Check that the part you cut is not the target reply.
What should the loss ignore in chat tuning?
A record has a user message and a reply.
Masking the prompt focuses learning on the output you want.
Your reading position is saved
0 of 36 complete
Lesson complete
Tokenisation for training
Up next