SeeingML
Modern AI & LLMs Guide 1 of 7 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Tokenization & Word Embeddings

How LLMs turn raw text into subword token IDs and map meaning into geometry where King - Man + Woman lands right on Queen.

When you type "Unbelievable coffee prices!" into ChatGPT, Claude, or Gemini, the neural network inside cannot read letters, words, or emojis directly. Neural networks only do math with numbers!

How do you turn a sentence into numbers cleanly? Memorizing every word and typo in human history would require an impossibly huge dictionary, while feeding one letter at a time stretches short sentences into painfully long chains. Instead, modern models slice text into reusable word pieces, like Lego bricks: common words like " coffee" stay whole as 1 piece, while longer words like "Unbelievable" snap into smaller familiar pieces ("Un" + "believ" + "able"), and every piece gets an integer ID.

This step is called Subword Tokenization, usually built with Byte-Pair Encoding (BPE). It is called Byte-Pair because during setup, the computer scans billions of sentences and repeatedly merges the most frequent side-by-side pairs of characters or pieces until it builds a reusable ~100,000-piece vocabulary.

Click through the 4 text samples below to inspect the exact pieces and IDs the model receives, including the real secret behind the famous “strawberry” riddle!

Interactive Lab 1: Inside a BPE Subword Tokenizer (Text to IDs)
27 chars -> 6 tokens
Step 1: Pick a sample sentence below. Step 2: Click or hover any token chip to highlight where it came from!
Raw Input String (Color-Sliced Into Reusable Pieces)
"Unbelievable coffee prices!"
Subword Token Chips & Vocabulary IDs Seen by the Model= leading space attached to word
Takeaway: Common words like " coffee" stay whole as 1 piece (including their leading space), while rarer words like "Unbelievable" snap cleanly into reusable Lego-like pieces ("Un" + "believ" + "able") so the model never gets stuck on an unfamiliar word.

From BPE Tokenization to Word Embeddings

Wait: token ID 6891 (" coffee") and token ID 6892 could be completely unrelated words! Remember the Categorical Encoding trap? Plain integer IDs carry zero sense of similarity.

To represent meaning, imagine placing every word onto a giant map using coordinates. On a tiny 2-number map, "king" might sit at (6.2, 7.4) right next door to "queen" at (7.8, 6.6), while "cat" sits across town at (-7.4, 6.8) and "Paris" sits far below at (-7.6, -6.8). Real language models use the exact same idea with a much richer map (often 1,536 to 12,288 coordinates per word!) so every shade of meaning has room.

Each token’s list of coordinates is called a Word Embedding, and the giant learned lookup table storing one coordinate row for every token ID is called an Embedding Matrix. During training on trillions of words, tokens appearing in similar contexts naturally drift into tight neighborhoods. To measure how close two words sit on this map, models use Cosine Similarity: how closely two arrows pointing from the center line up in the same direction, from 0% (unrelated) to 100% (same direction).

Click any word dot on the 2D meaning map below (or use the quick-pick buttons) to inspect its 3 closest neighbors!

Interactive Lab 2: Explore the 2D Map of Meaning
Selected: king (6.2, 7.4)
Click any word dot on the map, like "king" or "cat", or use the quick-pick buttons below.
RoyaltyAnimalsCitiesTech
ANIMALSROYALTYCITIESTECHcenter (0, 0)kingqueenprincecrowncatkittendogpuppyLondonParisTokyoPythonneuralGPUCoordinate 1 (Meaning Axis A)Coordinate 2
Quick pick:
Top 3 Closest Neighbors to "king" (Click any card to jump there)
Why these neighbors? All 3 top neighbors ("prince", "crown", "queen") sit tightly inside the Royalty neighborhood at 99% to 100% closeness because royal titles and monarchy words appear in similar stories and sentences. Their arrows from the center point in almost the exact same direction!

Doing arithmetic with ideas: King - Man + Woman = Queen

Even more astonishing: a meaning map does not just group similar words together; relationships between concepts turn into consistent directional steps! If stepping right turns "Man" into "Woman", taking that exact same step from "King" lands you right on "Queen".

Pick one of the three classic discoveries below (Royalty, Capital Cities, or Verb Tenses) and walk through Steps 1 -> 2 -> 3 to watch the exact same arrow solve each analogy!

Interactive Lab 3: Doing Math With Meaning (Parallel Arrows)
King + (Male to Female) = ?
Male to Female stepManWomanKing (start)Gender direction (Male to Female)Royalty level
What is happening: Step 1: Look at the green reference arrow from "Man" to "Woman". That arrow captures the exact "Male to Female" direction on the meaning map. Now pick "King" as our starting point.

Static vs. Contextual Embeddings: the "bank" test

Now try a tricky puzzle. Where on the meaning map should the word "bank" live? In "I sat peacefully by the river bank," it belongs next to "river", "water", and "shore". In "I deposited cash at the bank," it belongs next to "money", "vault", and "loan".

Early embedding dictionaries like Word2Vec (Mikolov et al., 2013) were Static Embeddings: every spelling got one frozen map pin forever, mashing "river bank" and "money bank" into one awkward midpoint! Modern language models fix this with Contextual Embeddings: the lookup table gives "bank" a starting spot, and then the model reads nearby words (using a spotlight mechanism called Self-Attention, which we will explore visually in the very next guide) to slide "bank" smoothly into the right neighborhood.

The lab below starts on the old frozen map so you can see "bank" stuck in the middle. Switch sentences first, then toggle on Contextual (Reads Neighbors) to watch "bank" glide cleanly to the matching neighborhood!

Interactive Lab 4: Frozen Map vs. Context-Aware Meaning ("bank")
Step 1: Switch sentences below while on the frozen map. Step 2: Turn on Contextual (Reads Neighbors) above and watch "bank" glide!
RIVER / NATUREMONEY / FINANCEstuck in the middlerivershorewatermoneyloanvault"bank"Frozen map: "bank" stays trapped at one blurry midpoint no matter which sentence you pick.
Takeaway: Notice the trap: even though the sentence clearly mentions "river", this old frozen map pins "bank" at one permanent blurry midpoint halfway between water and money. Try clicking the cash sentence (it still will not budge!), then switch to Contextual (Reads Neighbors) above.
See Byte-Pair Encoding (BPE), Embedding Matrices & Distributional SemanticsThesis / Reference

1. Byte-Pair Encoding (Sennrich et al., 2016; Radford et al., 2019): Starting from the 256 raw UTF-8 bytes, BPE iteratively counts all adjacent token pairs across a training corpus and merges the single most frequent pair into a brand-new vocabulary symbol until reaching target vocabulary size ∣V∣|V| (typically 50,00050{,}000 to 256,000256{,}000). Because every string decomposes down to UTF-8 bytes in the worst case, Byte-Level BPE achieves zero Out-of-Vocabulary (<UNK>) errors on any language or code snippet.

2. Learned Embedding Lookup Table: An embedding layer stores a trainable parameter matrix E∈R∣V∣×dmodel\mathbf{E} \in \mathbb{R}^{|V| \times d_{\text{model}}}. For token index t∈{0,…,∣V∣−1}t \in \{0, \dots, |V|-1\}, its initial vector is the row lookup:

et=Et,:=eone-hot(t)⊤E∈Rdmodel\mathbf{e}_t = \mathbf{E}_{t, :} = \mathbf{e}_{\text{one-hot}}(t)^\top \mathbf{E} \in \mathbb{R}^{d_{\text{model}}}

Similarity between two embeddings (or full document embeddings inside Vector Databases & HNSW for RAG) is ranked via Cosine Similarity, invariant to vector length:

cos⁡(u,v)=u⊤v∥u∥2 ∥v∥2∈[−1,+1]\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u}^\top \mathbf{v}}{\|\mathbf{u}\|_2\,\|\mathbf{v}\|_2} \in [-1, +1]

3. Distributional Hypothesis (Firth, 1957; Mikolov et al., 2013): “You shall know a word by the company it keeps.” Optimizing next-token cross-entropy (or Skip-Gram negative sampling) forces embeddings to factorize Pointwise Mutual Information (Levy & Goldberg, 2014), naturally encoding semantic axes like gender, geography, and tense as linear directions.

See Tokenization & nn.Embedding Lookup in PythonOptional Code
python
import torch
import torch.nn as nn

# Vocabulary of 50,257 BPE tokens mapped into 768-dim vectors (GPT-2 scale)
vocab_size, d_model = 50_257, 768
embed_table = nn.Embedding(num_embeddings=vocab_size, embedding_dim=d_model)

# Batch of 1 sentence encoded as 6 subword token IDs
token_ids = torch.tensor([[1844, 42910, 489, 6891, 7609, 0]])
vectors = embed_table(token_ids)
print("Embedding tensor shape:", vectors.shape)  # torch.Size([1, 6, 768])

How did "bank" know to jump straight toward "river" or "money"?

The embedding table gave "bank" a neutral starting coordinate. What exact mathematical spotlight scanned the rest of the sentence, spotted "river" or "cash", and pulled "bank" to the right meaning?

Welcome to the single most famous mechanism in modern AI: Self-Attention Explained.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Why do modern AI language models slice text using Byte-Pair Encoding (BPE) subword pieces instead of storing every whole English word?

Pick an option first, or peek anytime
2

Why did AI language models historically struggle to count how many times the letter 'r' appears in 'strawberry'?

Pick an option first, or peek anytime
3

What key advantage do Contextual Embeddings have over classic Static Embeddings like Word2Vec?

Pick an option first, or peek anytime
4

Plain token IDs like 6891 and 6892 already tell an AI model that two words have similar meanings, so no coordinate map of meaning is needed.

Pick an option first, or peek anytime
Quick Reference

Common Questions

Why do LLMs use subword tokens (BPE) instead of whole words or single characters?
Whole-word dictionaries explode into millions of entries and break on typos or new compound words, while single characters produce super-long sequences that waste context window and compute. Subword BPE finds the sweet spot (~50k to 200k reusable chunks), keeping common words as 1 token while cleanly splitting rare words.
Why did LLMs famously fail to count the letter 'r' in 'strawberry'?
Because the neural network never receives raw characters s-t-r-a-w-b-e-r-r-y! The tokenizer immediately converts 'strawberry' into two opaque integer IDs ('straw' + 'berry'), forcing the model to recall spelling from memory rather than counting visible letters.
What is an Embedding in AI and LLMs?
An embedding is a dense list of numbers (for example 1,536 or 4,096 floats) representing the meaning of a token, sentence, or image as a point in geometric space so semantically related concepts sit close together.
How is an embedding lookup table actually stored inside a Transformer?
It is simply a learnable weight matrix E of shape (Vocabulary_Size x d_model). Passing token ID 6891 selects row 6891 of that matrix (mathematically equivalent to multiplying by a one-hot vector, just vastly faster).
What is the difference between Word2Vec and modern LLM embeddings?
Word2Vec (2013) gives every word ONE frozen static vector regardless of context, blending 'river bank' and 'money bank' together. Modern Transformers start from a token lookup vector and let Self-Attention reshape it dynamically based on every surrounding word in the prompt.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/tokenization-embeddings/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026tokenizationembeddings,
  author       = {Irshad, Muhammad Aashir},
  title        = {Tokenization & Word Embeddings: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/tokenization-embeddings/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Tokenization & Word Embeddings: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/tokenization-embeddings/