LLM Fundamentals
A computer cannot read words. It can only work with numbers.
Tokenization is the step that turns your text into numbers. It cuts the text into small pieces called tokens. Then it gives each piece an ID number.
That is all. Every time you send a prompt to ChatGPT, Claude, Gemini or Llama, tokenization runs first.
A token is not the same as a word. A token can be:
- a whole word:
hello - a part of a word:
un+believ+able - a single character or symbol:
? - a space attached to a word:
world
Rule of thumb for English: 1 token is about 4 characters, or about 0.75 of a word. So 100 tokens is roughly 75 words.
Why Tokens Matter (4 Real Reasons)
- Cost. APIs charge per token, not per word.
- Context window. The model can only look at a fixed number of tokens at once. Your prompt, the documents you add, and the answer all share that space.
- Speed. More tokens means slower responses.
- Quality. Odd splits explain odd mistakes, like bad spelling, bad arithmetic, or weak results in some languages.
If you build AI products, you will think in tokens every day.
Step-by-Step: What Happens to Your Text
Take the sentence: Tokenization is fun!
- Step 1: Clean the text. The tokenizer may normalize it (for example, Unicode fixes).
- Step 2: Split into pieces. It uses a learned list of pieces (the vocabulary). Example:
Tokenizationisfun! - Step 3: Map to IDs. Each piece has a fixed number, like
Token= 3404,is= 374. (Numbers are illustrative.) - Step 4: Send IDs to the model. The model turns each ID into an embedding (a list of numbers). You can read more in the embeddings guide.
- Step 5: Model predicts the next token ID. It produces one token at a time.
- Step 6: Decode. IDs are turned back into text you can read.
The exact split depends on the model. Different models have different tokenizers, so the same text can give different token counts.
Three Ways to Split Text
| Method | How it splits | Good | Bad |
|---|---|---|---|
| Character-level | One piece per letter | Tiny vocabulary, no unknown words | Very long sequences, slow |
| Word-level | One piece per word | Short sequences | Huge vocabulary, fails on new words ("unknown word" problem) |
| Subword | Common words stay whole, rare words are split | Balanced. Handles new words | Splits can look strange |
Modern LLMs use subword tokenization.
How BPE Works (Byte Pair Encoding)
BPE is the most common method. The idea is simple: merge the pairs that appear most often.
Mini example. Our small training data has four words: hug, pug, pun, bun.
- Start with single characters:
h u g,p u g,p u n,b u n. - Count neighbor pairs.
u gappears 2 times (hug, pug).u nappears 2 times (pun, bun). - Merge the most frequent pair into a new token. Say we merge
u gintoug. - Repeat. Now merge
u nintoun. - Keep going until the vocabulary reaches the size you want (for example, 100,000 tokens).
Result: common chunks like ug and un become single tokens. Rare words are built from smaller parts. No word is ever "unknown", because the worst case is single characters or bytes.
Byte-level BPE
GPT-style models and many others work on bytes instead of characters. That means any text in any language, emoji, or code can be tokenized. Nothing is out of vocabulary.
Other tokenizers you will meet
- WordPiece: used in BERT.
- Unigram / SentencePiece: used in models like T5 and earlier Llama versions. It does not need spaces to find word borders, so it is good for languages without spaces.
- tiktoken: OpenAI's fast tokenizer library (byte-level BPE).
Typical vocabulary sizes: about 50k (GPT-2), about 100k (GPT-4 era), about 128k (Llama 3).
Special Tokens
Tokenizers also have special tokens that are not normal text:
- BOS / EOS: beginning and end of a sequence.
- Chat template tokens: mark who is speaking (system, user, assistant).
- Padding tokens: fill batches to equal length.
When you fine-tune a model, you must use the same chat template as the base model. Wrong special tokens are a common reason for bad results.
Count Tokens in Python
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
text = "Tokenization is fun!"
ids = enc.encode(text)
print(ids) # list of token IDs
print(len(ids)) # token count
print([enc.decode([i]) for i in ids]) # see each piece
For open models (Llama, Qwen, Mistral) use Hugging Face:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B")
ids = tok("Tokenization is fun!")["input_ids"]
print(len(ids), tok.convert_ids_to_tokens(ids))
Real-World Example: Estimating Cost
You run a support bot. Each ticket plus your instructions is about 800 tokens in, and the answer is about 200 tokens out. You get 50,000 tickets a month.
- Input: 50,000 × 800 = 40 million tokens
- Output: 50,000 × 200 = 10 million tokens
If a model charged, say, $2 per 1M input tokens and $8 per 1M output tokens (example prices only), cost is $80 + $80 = $160 per month. Always check current prices. The method stays the same: count tokens, multiply by price.
Use Cases Where Tokenization Knowledge Pays Off
- Cost control: shorten prompts, cache repeated parts, trim retrieved text.
- RAG: chunk sizes are best measured in tokens, not characters. See chunking strategies.
- Multilingual apps: Arabic, Urdu, Hindi and many other languages often need more tokens for the same meaning than English. That means higher cost and less room in the context window. Test your own text with the model's tokenizer before you plan a budget.
- Fine-tuning: you must tokenize with the model's own tokenizer and template.
- Debugging: if a model cannot count letters in "strawberry", the cause is often tokenization. It sees pieces, not letters.
Common Mistakes
- Counting words and assuming it equals tokens.
- Using one model's tokenizer to count tokens for another model.
- Forgetting that the leading space is part of the token (
helloandhelloare different tokens). - Ignoring that the output also uses tokens from the same window.
- Forgetting special and system tokens that add to the count.
FAQ
What is a token in an LLM? A small piece of text (a word, part of a word, or symbol) that the model reads as one unit with an ID number.
How many tokens are in a word? In English, about 1.3 tokens per word on average. Short common words are 1 token. Long or rare words can be 3 or more.
What is a context window? The maximum number of tokens the model can handle at once, including your input and its output.
Is tokenization the same as embedding? No. Tokenization turns text into IDs. Embedding turns each ID into a vector of numbers that carries meaning.
Why do different models give different token counts? Each model has its own tokenizer and vocabulary.
Key Takeaway
Tokenization cuts text into subword pieces and gives each piece an ID. Tokens decide your cost, your context limit and some strange model mistakes. Always count tokens with the right tokenizer, never words.
