Papa Programmer
Lesson 11 of 36

Tokenisation for training

9 min read

Optional

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.

python
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:

text
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.

python
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:

text
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 11

Only 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.

python
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:

text
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.

  1. The prompt text and the answer appear as you expect, including the chat template markers.
  2. The end marker is present after the answer.
  3. The labels are -100 where you intended, and only there.
  4. 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.

  1. TemplateTurn the messages into text with the model's chat template.
  2. EncodeMap the text to token IDs with the base model's tokeniser.
  3. Mask labelsSet the labels of the prompt to -100 so only the answer is scored.
  4. PadFill short examples to the batch length and set the attention mask.
  5. InspectPrint one batch and check IDs, mask and labels by eye.
One training example, step by step
Use the model's tokeniserThe same text gives different IDs with a different tokeniser.
Score the answerLabels of -100 take the prompt and the padding out of the loss.
Look at a batchPrinting one batch finds format mistakes before they cost a run.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools