Transformers - Part 1: Tokenization, Embeddings and Positional Embeddings
Why we need tokenization
Neural networks only understand numbers. Human language is text. We need a step that converts text into numbers the model can learn from and adjust in training. -> Tokenization.
Character-level and word-level tokenization
- Character level Every character gets its own number. Hello -> H=1, E=2, L=3, L=3, O=4.
- 'understanding' has 13 characters, so 13 steps. Very inefficient.
- Every character looks the same to the model. No meaning inside a token. (High Cognitive Load)
- Rishabh = 7 tokens, 7 times the processing, still no context.
- Word level Every word is one token. 'the cat sat' -> 1, 2, 3.
- Each token carries meaning the model can learn.
- 'understanding' is processed in one step. Solved meaning and efficiency. But it introduces three problems.
- Variants: cat, cats, cat's are treated as three different words. A human sees one concept. (Vocabulary bloat)
- Typos: 'teh' is not in the vocabulary. The model has nothing to look up, treats it as unknown, may hallucinate.
- Unknown words: anything not in the vocabulary is invisible. Even 100,000 words misses many. New languages blow the vocabulary up.
Subword tokenization
Like pronouncing a long new word by breaking it into parts. understanding -> under + stand + ing
- under: under the hood
- stand: standing, stand up
- ing: dying, telling, making, crying, playing, walking
- New words are built from known pieces. Vocabulary has swim and ing, so swimming works. cry + ing = crying, die + ing = dying.
- Typos: a mangled word splits into known subwords, so the model can recover.
- Vocabulary no longer explodes as words or languages are added. (Solves bloat, unknown, typo)
- Three tokens for one word looks costlier, but the pieces are reused everywhere.
Byte Pair Encoding (BPE)
Subword tokenization -> the idea. Byte Pair Encoding -> an algorithm that does it, like multiplication is the algorithm for a goal of multiplying numbers.
- Start with tiny pieces.
- Count which pieces come together most often in lots of text.
- If 'ing' shows up in walking, dying, crying, make 'ing' a single token.
- Repeat until the vocabulary is good enough.
OpenAI, Anthropic and Google DeepMind each use their own tokenizer. Their current ones are not public. Older ones (GPT-3 era) are public. BPE is the old starting point.
What modern tokenizers do
- Spaces: 'Hello world' -> 'Hello' + ' world'. The space is attached to the next word. Without this the model would generate one long word.
- Contractions: don't -> don + 't. The 't piece reuses across wasn't, weren't.
- Complex words: artificial intelligence -> art + ificial + intelligence. 'art' reuses in many words, so it is split off even though 'ificial' reuses less.
Why tokenization matters
- Limits: every model has a max tokens per request. GPT-4 128k, Gemini 1M, Claude 200k, GPT-5.2 Codex 400k. This controls cost and GPU load.
- Cost: APIs are priced per token, so efficient tokenization saves money.
- Languages: the same meaning needs different token counts in different languages.
- Perception: tokens are the eyes of the model. It sees only the tokens, not letters. If it can't see a pattern in tokens, it can't learn it.
Example
Strawberry is tokenized as str + aw + berry. The model never sees the whole word, so counting r's often gave 1, 2 or 4. Reasoning models take time, spell s-t-r-a-w-b-e-r-r-y and count, so they get 3. They can still slip occasionally.
Characters are too granular, words are too many. Subwords sit in between. Research on removing tokenizers is ongoing (Meta works on a BPE variant using entropy) but no good answer yet.
Tokenizers in practice (tiktokenizer and tiktoken)
- A web tokenizer viewer lets you choose a model and see tokens and IDs.
- 'Rishabh' splits into 3 tokens. 'my name is Rishabh' gives 6 tokens: my, ' name', ' is', ' R', ish, abh. 'R' and ' R' have different IDs; ish and abh keep the same IDs.
- Numbers: 100 is one token, 1000 is 100 + 0, 100x is 100 + x.
- 'swimming' splits as sw + imming for GPT-4o, not swim + ing. Splits come from training data.
import tiktoken
enc = tiktoken.get_encoding('cl100k_base')
print(enc.n_vocab)
ids = enc.encode('Hello world')
print(ids) # [9906, 1917] -> 'Hello', ' world'
print(enc.encode('strawberry')) # 3 tokens: str, aw, berry| Text type | Tokens (cl100k_base) |
|---|---|
| Simple English | ~4-10 |
| Python code | 11 |
| JSON | 19 (most) |
| Numbers / URL | in between |
Other tokens from the library: emoji split into several byte-like tokens. Many spaces collapse to one space token. Token IDs differ between models even when splits match. English is cheaper than JSON for APIs.
From IDs to meaning: embeddings in code
The Problem Token IDs are arbitrary. 15496 doesn't tell the model it is a greeting. The Solution Each ID points to a row in an embedding matrix, a vector capturing meaning.
- Vocabulary 50,000 x embedding dimension 768 = about 38 million parameters, just for embeddings.
- Initialised randomly. Backprop reduces loss and the vectors drift into meaningful places.
- Lookup: 'Hello world' -> IDs 9906, 1917 -> each a 768-number vector.
import gensim.downloader as api
m = api.load('glove-wiki-gigaword-100')
m.most_similar('king') # prince, queen, son, brother, monarch...
m.most_similar(positive=['king','woman'], negative=['man']) # queen first- Names give names, 'computer' gives software, technology, pc, hardware.
- Other analogies: paris - france + germany = berlin; bigger - big + cold = colder.
- Plotted, animals, tech, family and royalty each form their own cluster.
Why matrices/vectors: GPUs are fast at vector and matrix multiplication, and vectors let one point carry many dimensions.
The problem of sequence
The Problem 'The dog bit the man' and 'The man bit the dog' contain the same tokens. Meaning differs only by order.
- RNN/LSTM: words arrive one by one, so order is implicit.
- Transformer: all tokens go in at once (the reason it is fast). It doesn't know what came first. The Solution Add position information to each embedding. -> Positional embedding.
Sinusoidal positional embeddings
Idea Take several sine and cosine waves, each with a different frequency.
- Position 0 reads the start of each wave: 0, 1, 0, 1 (sine starts at 0, cosine at 1).
- Position 1 moves the same step along every wave, giving a new set of values.
- Each position's column of values is a unique fingerprint and never repeats. A single straight line would give repeating or non-distinguishing values. (Reasons to fail)
- No learnable parameters. Sine and cosine values are already known from a formula.
- Many dimensions with many frequencies keep every position unique.
Combining final embedding = token embedding + positional embedding (same shape) Example: 'the cat sat' -> 3 tokens x 768 = (3, 768) for both, then added. Same word 'the' at position 0 vs position 5 gets different vectors (distance about 14). Meaning plus position in one vector.
Glossary
- Tokenization
- Converting text into token IDs a model can process.
- Subword
- A piece of a word used as a token, reusable across many words.
- Byte Pair Encoding
- Algorithm that merges frequently co-occurring pieces into tokens.
- Vocabulary
- The set of all tokens a model knows.
- Token embedding
- A vector (e.g. 768 numbers) representing a token's meaning.
- Positional embedding
- Vector added to a token embedding to carry its position in the sequence.