Large language models do not read letters or words – they read tokens. Tokenization splits text into these pieces and maps each to a number. It affects cost, context limits, speed and even why LLMs sometimes struggle to count letters.
What You Will Learn
- What a token is
- Word, character and sub-word tokenization
- Byte-Pair Encoding (BPE) from scratch
- Counting tokens with tiktoken
- Practical effects: pricing, context windows, Hindi and code
Prerequisites
Three Ways to Split Text
| Method | “unbelievable” | Problem |
|---|---|---|
| Word | [“unbelievable”] | Huge vocabulary; unknown words break it |
| Character | [“u”,”n”,”b”,…] | Very long sequences |
| Sub-word (BPE, WordPiece, SentencePiece) | [“un”,”believ”,”able”] | Best balance – used by all modern LLMs |
BPE from Scratch
Byte-Pair Encoding starts from characters and repeatedly merges the most frequent adjacent pair into a new token.
from collections import Counter
corpus = ["low", "lower", "lowest", "newer", "wider", "new"]
words = Counter({tuple(w) + ("</w>",): 1 for w in corpus}) # </w> marks word end
def best_pair(words):
pairs = Counter()
for w, f in words.items():
for a, b in zip(w, w[1:]):
pairs[a, b] += f
return pairs.most_common(1)[0]
def merge(words, pair):
out = {}
for w, f in words.items():
new, i = [], 0
while i < len(w):
if i < len(w) - 1 and (w[i], w[i + 1]) == pair:
new.append(w[i] + w[i + 1]); i += 2
else:
new.append(w[i]); i += 1
out[tuple(new)] = f
return out
for step in range(6):
pair, count = best_pair(words)
words = merge(words, pair)
print(step + 1, pair, count)
print(list(words))
1 ('l', 'o') 3
2 ('lo', 'w') 3
3 ('e', 'r') 3
4 ('er', '</w>') 3
5 ('n', 'e') 2
6 ('ne', 'w') 2
[('low', '</w>'), ('low', 'er</w>'), ('low', 'e', 's', 't', '</w>'), ('new', 'er</w>'), ('w', 'i', 'd', 'er</w>'), ('new', '</w>')]
Explanation: After 6 merges the vocabulary contains useful pieces: low, new and the suffix er. “lowest” is still partly split because “est” was rare. Real tokenizers learn 50,000–200,000 merges from huge corpora, and work on bytes so any text, emoji or code can be encoded.
Count Tokens with tiktoken
# pip install tiktoken
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # encoding used by recent OpenAI models
ids = enc.encode("Machine learning is fun!")
print(len(ids), [enc.decode([i]) for i in ids])
Explanation: A short English sentence is usually about one token per word plus punctuation. Each model family (GPT, Claude, Llama, Gemini) has its own tokenizer, so counts differ between providers; Hugging Face tokenizers load with AutoTokenizer.from_pretrained(name).
Why Tokens Matter
| Effect | Detail |
|---|---|
| Cost | APIs charge per input and output token – see OpenAI API |
| Context window | Limits (e.g. 128K or 1M tokens) are counted in tokens, not words |
| Rule of thumb | English ≈ 0.75 words per token (about 4 characters) |
| Other languages | Hindi, Punjabi and other Indic scripts often need more tokens per word, so the same message can cost more |
| Spelling & counting | Models see “strawberry” as a few tokens, not letters, which is why letter-counting can fail |
| Numbers & code | Long numbers split oddly; whitespace and indentation also use tokens |
Series
Generative AI series: Intro to GenAI · LLM Fundamentals · Tokenization · Embeddings · Prompt Engineering · RAG · Vector DBs · Function Calling · AI Agents · Agent Frameworks · MCP · Hallucinations · Run LLMs Locally · Diffusion Models
Interview Questions
Q: What is a token?
A unit of text (often a sub-word) mapped to an integer ID that an LLM processes.
Q: Why sub-word tokenization?
It keeps the vocabulary manageable while handling rare and new words by splitting them into known pieces.
Q: How does BPE work?
Start from characters/bytes and repeatedly merge the most frequent adjacent pair into a new token.
Practice Exercises
- Run 10 more merges in the BPE example – when does “lowest” become fewer tokens?
- Count tokens for the same sentence in English and Hindi with tiktoken.
Summary
LLMs read tokens produced by sub-word tokenizers such as BPE. Token counts drive price and context limits and explain several quirks of LLM behaviour.
Next: Text Embeddings
Machine Learning Tutorials, Courses and Certifications