AI Hints
Fine-Tuning LLMs · Lesson 11 of 120

Token IDs and Special Tokens

The numbers the model sees.

⏱ 2 min read▶ Video at 16:47🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

The model never sees words. It only sees a list of numbers. Let's look at those numbers, and meet a few special tokens that have a job to do.

  • The model sees numbers
  • A list of token IDs
  • And some special tokens

Text to IDs, and back

Calling the tokenizer on text gives us input IDs. Decode turns the IDs back into text. Then we tokenize four small words. Run it. Each token became a number, and decode gives us the original sentence back. Now look at the words. Book, with a space before it, has a different ID. A capital B is different again. And unhappiness needs three tokens.

app.pypython
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
ids = tok("Where is my copy of The Hobbit?")["input_ids"]
print("IDs:    ", ids)
print("Decoded:", tok.decode(ids))
for word in ["book", " book", "Book", "unhappiness"]:
    print(f"{word!r:15} -> {tok(word)['input_ids']}")
Output
IDs:     [9576, 314, 957, 3784, 282, 378, 20625, 3333, 47]
Decoded: Where is my copy of The Hobbit?
'book'          -> [3767]
' book'         -> [1863]
'Book'          -> [15654]
'unhappiness'   -> [419, 88, 38462]

Special tokens

Some tokens aren't text at all. They're signals. The end of sequence token tells the model to stop writing. The padding token fills empty space. We'll see why soon. And chat models use start and end tokens, to mark who is speaking. Run it. In this chat model, the end token is called i m end. It also serves as padding.

app.pypython
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
print("End of text token:", tok.eos_token, tok.eos_token_id)
print("Padding token:    ", tok.pad_token, tok.pad_token_id)
print("Special tokens:   ", tok.all_special_tokens[:6])
Output
End of text token: <|im_end|> 2
Padding token:     <|im_end|> 2
Special tokens:    ['<|im_start|>', '<|im_end|>', '<|endoftext|>']

Why the end token matters

Remember our base model, repeating itself? It never produced the end token, so it never stopped. A model learns when to stop from its training examples. That's one of the first things fine-tuning will teach our model. Answer, then stop.

keyvalue
End tokenmeans stop writing
Base modelrarely stops
Fine-tuningteaches when to stop
Our goalanswer, then stop

Summary

Let's recap. Each token has an ID, and decode turns IDs back into text. Spaces and capitals change the ID. And special tokens, like the end token, are signals, not text. Next, handling many messages at once, with padding.

Key takeaways
  • text ↔ IDs
  • Spaces and capitals matter
  • eos_token means stop
Next up: Padding, Truncation, Attention Masks — many texts at once