Concepts / Tokenizing Text Messages with tiktoken

Tokenizing Text Messages with tiktoken

Padding works on token IDs, not on text. The message is first encoded into a list of integers, and then the integer 50256 is added to that list as many times as needed to reach the target length.

  • Programming

Why Text Batches Must Line Up

Imagine training a text classifier that decides whether a message is spam. The messages in your training data will not all be the same length. One message might be a single short line, and another might be a long paragraph. A spam detector can easily receive both in the same batch.

That mismatch causes a real problem. Models process batches as grids of numbers, so every message in a batch has to occupy the same number of positions. A short message and a long message cannot sit side by side in that grid until their lengths agree. Each message has already been turned into a sequence of token IDs, and those sequences are what must be made equal.

What do you think happens?

A batch contains a one-line text and a long paragraph. Which approach keeps every word of both messages: cutting both down to the one-line length, or extending the short text with extra positions?

  • Cutting both down to the one-line length

  • Extending the short text with extra positions

Reveal answer
Answer:

Extending the short text with extra positions keeps every word of both messages.

Cutting both to the shortest length throws away everything past that cut in the longer message. Padding adds positions filled with a padding token, so no message content is removed.

Two Routes to Equal Length

There are two basic ways to make variable-length messages agree in length: truncation and padding. Both produce a uniform grid, but they make different trades. Truncation shortens the longer messages. Padding lengthens the shorter ones. The rest of this article follows both routes so you can see what each one keeps and what each one gives up.

Definition

Truncation cuts every message down to the length of the shortest message in the dataset. Padding extends every message up to the length of the longest message by adding padding tokens to the end of the shorter ones.

KeepsOnly the first positions upto the shortest lengthKeepsEvery token of everymessageDiscardsEverything past the cutDiscardsNothingCostCheaper, because fewerpositionsCostExtra positions filled withpadding tokens
How do truncation and padding differ in what they keep, what they discard, and what they cost?

Read the comparison column by column. Truncation has one real advantage: it is computationally cheaper, because the model works with fewer positions overall. Padding costs more computation, since the model handles the extra padding positions, but in exchange it removes nothing from any message.

Truncation and Its Information Cost

Truncation is a natural first instinct. Making every message as short as the shortest one sounds clean, and it is cheap to do. The belief to watch for is that this shortening is harmless because it only trims a little. That belief holds only when message lengths are similar. For a dataset where lengths vary a lot, truncation can remove a great deal.

When a message is longer than the target length, everything past the cut is lost, and the model never sees it. If most messages are close to the shortest length, the loss is small. If the shortest message is much smaller than the average or the longest message, the loss can be large, and model performance may suffer as a result.

Worked example

Counting what truncation throws away

A batch holds three messages with 3, 5, and 8 tokens. Each message is reduced to the length of the shortest one. How many tokens survive, and how many are lost? Use illustrative token labels t1 through t8 for the messages.

  1. 1
    Identify the target length

    The shortest message has 3 tokens, so truncation cuts every message to 3 positions.

  2. 2
    Truncate message A

    Message A already has 3 tokens, so it loses nothing. All 3 survive.

  3. 3
    Truncate message B

    Message B has 5 tokens. Tokens t4 and t5 fall past the cut, so 3 survive and 2 are lost.

  4. 4
    Truncate message C

    Message C has 8 tokens. Tokens t4 through t8 fall past the cut, so 3 survive and 5 are lost.

  5. 5
    Total the effect

    The batch originally held 3 + 5 + 8 = 16 tokens. After truncation, 9 remain and 7 are discarded, which is almost half of the content.

Result

Truncation leaves 9 of 16 tokens. Message C, the longest, loses the most, and the model never sees its later content.

Padding Keeps Every Message Whole

Padding takes the opposite approach. Every message is extended to the length of the longest message in the dataset, using a padding token to fill the added positions. Nothing is cut away. The padding positions carry no message content; they simply fill space so that the batch forms a uniform grid.

The padding token used here is the string '<|endoftext|>'. The important detail is that you do not append that string to each text message. Instead, you add the token ID that corresponds to it to each encoded message. For the GPT-2 tokenizer from tiktoken, that ID is 50256. You can confirm it by encoding the string with the GPT-2 tokenizer, which keeps padding in the same numeric form as the rest of the encoded data.

Key point

Padding works on token IDs, not on text. The message is first encoded into a list of integers, and then the integer 50256 is added to that list as many times as needed to reach the target length.

Adding Padding IDs to Encoded Messages

Take the same three messages from the truncation example, with 3, 5, and 8 tokens. Padding changes the lengths so that all three become 8 positions. The longest message, with 8 tokens, is already at the target length, so it passes through unchanged. The other two receive padding token IDs appended after their real tokens.

Message A3 tokensMessage A3 tokens plus 5 padding IDsMessage B5 tokensMessage B5 tokens plus 3 padding IDsMessage C8 tokens, longestMessage C8 tokens, no paddingpad to 8pad to 8already 8
How do short and long token sequences end up the same length, and where do the added padding token IDs sit relative to the original tokens?

In the diagram, the padding IDs always sit after the real tokens. The real tokens keep their original order at the start of each sequence, so the message content is intact and only the tail is extended. The longest message is the reference point, and every other message is measured against it.

Aligning Positions Across a Batch

Once every message has the same length, the batch can be read as a grid. Each row is one message, and each column is a position. Position 1 of every message lines up with position 1 of the others, and the same holds for every later position. That alignment is what lets the model process the whole batch at once.

Message At1 t2 t3 PAD PAD PAD PADPADMessage Bt1 t2 t3 t4 t5 PAD PAD PADMessage Ct1 t2 t3 t4 t5 t6 t7 t8
Why must every message occupy the same number of positions, and how do the positions line up across messages?

In this illustration the labels t1 through t8 stand in for real token IDs, and PAD marks a padding position. Read straight down any column and you find the same position across all three messages. Column 8 holds a real token in Message C and a padding token in Message A, yet all three rows still have exactly eight positions, which is what the batch needs.

Where Padding Happens in the Dataset

Padding is not applied by hand to each message. It is built into a PyTorch Dataset, which is a class that specifies how data is loaded and processed before any data loaders are created. The dataset class handles the padding step once, so it can be reused every time batches are created.

  1. 1
    Identify the longest sequence in the training dataset.
  2. 2
    Encode the text messages into token IDs.
  3. 3
    Pad every other sequence with the padding token ID until it matches the longest length.

Seeing padding as one step inside a dataset class explains why it is written once and reused, rather than repeated for each batch by hand. Each time the data is accessed, the same rule produces a uniform grid, and the model receives batches of consistent shape.

Mistakes Beginners Make

  • Common mistake

    Assuming truncation to the shortest length is harmless

    What it looks like

    Cutting a batch of 3, 5, and 8 token messages down to 3 tokens discards 7 of 16 tokens.

    Why it fails

    The loss is small only when lengths are similar. When the lengths vary widely, the discarded content can be large enough to hurt model performance.

    Do this instead

    Check the spread of message lengths before choosing truncation, and weigh the lost content against the computation it saves.

  • Common mistake

    Appending the padding string to each text before encoding

    What it looks like

    Adding the text '<|endoftext|>' to the end of each message and then encoding the result.

    Why it fails

    The padding is meant to be a token ID added to already-encoded messages, so the batch stays in numeric form.

    Do this instead

    Encode each message first, then add the token ID 50256 for the GPT-2 tokenizer until each sequence reaches the longest length.

  • Common mistake

    Thinking the longest message is padded

    What it looks like

    Adding padding tokens to the 8-token message when the batch target is 8.

    Why it fails

    The longest message already sets the target length, so it needs zero padding tokens.

    Do this instead

    Pad only the sequences that are shorter than the longest one.

  • Common mistake

    Believing padding positions contain message content, when they only fill space so the batch forms a uniform grid.

Practice Padding a Batch

EASY

A batch contains three encoded messages with 4, 9, and 6 tokens. Using padding, what is the target length, and how many padding token IDs does each message receive?

Hints
  • The target length under padding is the length of the longest message.
  • Subtract each message's length from the target to find its padding count.
  • The longest message receives zero padding IDs.

Key Takeaways

  • Models process batches as grids, so every message in a batch must occupy the same number of positions, which means variable-length messages must be made equal in length.
  • Truncation cuts every message to the shortest length. It is computationally cheaper, but it discards content past the cut and can cause significant information loss when lengths vary widely.
  • Padding extends every message to the longest length using a padding token. It costs extra positions but preserves the entire content of every message.
  • The padding token is added as its token ID, such as 50256 for the GPT-2 '<|endoftext|>' token, to already-encoded messages, and a PyTorch Dataset class can apply this padding automatically.

Related concepts

More concepts starting with T