AI Hints
Fine-Tuning LLMs · Lesson 10 of 120

Tokenizers

Text becomes tokens.

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

A model can't read text. It can only do maths with numbers. So before anything else, text must be cut into tokens, and each token turned into a number. That's the tokenizer's job.

  • Models only do maths
  • Text must become numbers
  • That's the tokenizer's job

What a tokenizer does

A tokenizer has two jobs. First, it splits text into tokens. Second, it looks up each token in its vocabulary, which is a big list of every token it knows. Each token has a number in that list, called its ID. Every model comes with its own tokenizer, and you must always use the matching one.

keyvalue
Job 1split text into tokens
Job 2look up each token's ID
Vocabularythe list of known tokens
Rulealways use the model's own tokenizer

Split a sentence

Let's see it. Auto tokenizer loads the tokenizer that matches our model. Tokenize splits a customer message into tokens. Run it. Nine tokens. Common words are one token each. But Hobbit is split into two pieces, Hob, and bit. And that strange G symbol means there's a space before the word.

app.pypython
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
text = "Where is my copy of The Hobbit?"
tokens = tok.tokenize(text)
print(tokens)
print("Number of tokens:", len(tokens))
Output
['Where', 'Ġis', 'Ġmy', 'Ġcopy', 'Ġof', 'ĠThe', 'ĠHob', 'bit', '?']
Number of tokens: 9

Why split words into pieces?

Why not just use whole words? Because there are too many words, names, and typos. With pieces, the tokenizer can build any word, even one it has never seen. Common words stay whole. Rare words become a few pieces. A rough rule. One token is about three quarters of an English word.

keyvalue
Whole wordstoo many to list
Piecescan build any word
Common wordsone token
Rule of thumb1 token ≈ ¾ of a word

Summary

Let's recap. A tokenizer splits text into tokens, and turns each token into an ID. Rare words become several pieces. And you must always use the model's own tokenizer. Next, token IDs, and special tokens.

Key takeaways
  • Split into tokens
  • Tokens → IDs
  • Use the matching tokenizer
Next up: Token IDs and Special Tokens — the numbers the model sees