Course
AI · Module 01: How LLMs Work Under the HoodTutorial 1 of 21
AI Course·~1.5 hrs

1.1 Tokenization, BPE & Token Economics

Discover why LLMs never read words or characters: play with a live BPE subword tokenizer, understand why models struggle with spelling and math, and master token cost economics.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. The Mental Model: LLMs Never See Words or Characters

When you send "Write a SQL query for unbelievable growth!" to GPT, Claude, or Gemini, the neural network never sees a single English letter. Neural networks only multiply matrices of floating-point numbers.

Before Layer 1 of a Transformer ever runs, a deterministic C++/Rust pre-processor called a Tokenizer chops your UTF-8 string into subword chunks called tokens, maps each chunk to an integer ID in a fixed vocabulary (typically 100,000 to 256,000 entries), and looks up a dense embedding vector for each ID.

1. RAW UTF-8 TEXT"unbelievable!"LLMs never readraw strings directly2. BPE SUBWORD MERGESunbelievable!Frequent byte pairs mergeinto reusable stems3. VOCAB IDs[359, 48219, 481, 0]200k-entry lookuptable (o200k_base)4. EMBEDDINGS[0.14, -0.82, ...][-0.41, 0.59, ...]4,096-D float vectorsenter Transformer
Figure: Every API prompt is sliced into BPE subword tokens, mapped to integer IDs, and converted to dense vectors before layer 1 runs.

Why Subwords? (Why Not Characters or Whole Words?)

Early NLP researchers tried two extremes — and both failed at scale:

  • Word-level vocabularies (["cat", "cats", "catfish", ...]): Explode past 2,000,000+ entries, waste memory on typos/slang/variable names (parseUserJwtPayload), and collapse to <UNK> (unknown) whenever a user invents a new word.
  • Character-level vocabularies (['c', 'a', 't']): Tiny 256-entry vocabulary, zero unknown tokens — but a 2,000-word document becomes 12,000 tokens long! Because Transformer attention scales quadratically (O(N²)) with sequence length, character-level sequences are far too slow and semantically thin per step.

Byte Pair Encoding (BPE) hits the exact sweet spot:

  1. Start with raw UTF-8 bytes (0–255), guaranteeing zero <UNK> errors for any language, emoji, or binary snippet on Earth.
  2. Scan terabytes of text and code, find the most frequent adjacent pair (e.g., 'i' + 'n' → 'in', then 'in' + 'g' → 'ing'), and merge it into a single new vocabulary ID.
  3. Repeat ~200,000 times. Common English words (" the", " function", " return") become 1 single token (including their leading space!), while rare words ("unbelievable") split cleanly into reusable morphemes ("un" + "believ" + "able").

2. Hands-On Lab: Slice Text & Measure Cost Live

Don't take anyone's word for it — test how subwords, leading spaces, indented JSON, Python code, and multilingual scripts tokenize right here in your browser:

Interactive BPE Tokenizer & Token Cost Lab
100% Client-Side Subword Simulator · Type or switch presets below
Try Preset:
Subword Token Stream (17 tokens)· = leading space attached to stem
Tokenization·splits·raw·text·into·subword·chunks·before·the·Transformer·ever·sees·a·single·word!
Tokens
17
96 chars
Packing Efficiency
5.6 chars/tok
English avg ≈ 4.0
Frontier (1k calls)
$0.0425
@ $2.50 / 1M input
Flash / Mini (1k calls)
$0.0026
@ $0.15 / 1M (~16× cheaper!)

Try clicking Pretty vs Minified JSON and deleting all spaces and newlines in the box above. Notice how stripping indentation alone cuts token count (and your monthly API bill!) by 20%–35% with zero loss of meaning!


3. Three Weird LLM Quirks Explained Instantly by Tokenization

Once you think in tokens instead of characters, three "mysterious" LLM failures suddenly become obvious engineering facts:

Quirk 1: The Classic "How many r's in strawberry?" Bug

To you, "strawberry" is 10 individual letters (s-t-r-a-w-b-e-r-r-y). To a BPE tokenizer, " strawberry" is often just two integer IDs — say [10428, 19772] (" straw" + "berry"). Asking an LLM to count 'r's without code execution or letter-by-letter spelling is like asking you to count brushstrokes inside a sealed envelope!

Quirk 2: Inconsistent Multi-Digit Arithmetic

Modern tokenizers (cl100k_base, o200k_base) split numbers into 1-to-3-digit chunks from left to right:

  • 98450 → 984 + 50
  • 984501 → 984 + 501

Adding one digit completely changes every token ID in the number, making mental carry-over alignment brittle. Production Rule: Never ask an LLM to sum invoices in prose — give it a Python calculator tool or aggregate in SQL!

Quirk 3: The Non-English & Emoji "Token Tax"

Because training corpora are heavily English + code, "Hello" is 1 token, whereas words in Hindi (नमस्ते), Tamil, Arabic, or emojis (🚀) often fall back to raw UTF-8 byte pairs — consuming 2× to 4× more tokens (higher latency, smaller effective context window, and higher cost per sentence).


4. Token Economics: How Cloud LLM Bills Actually Scale

Every commercial LLM API bills you separately for Input Tokens and Output Tokens — and Output Tokens always cost 3× to 5× more than Input Tokens:

Tier (2026 Representative Pricing)Input / 1M TokensOutput / 1M TokensBest Production Role
Frontier Reasoning / Flagship (GPT-4o / Claude Sonnet / Gemini Pro)$1.25 – $3.00$5.00 – $15.00Complex coding, multi-step synthesis, ambiguous reasoning
Flash / Mini Workhorses (GPT-4o-mini / Gemini Flash / Claude Haiku)$0.10 – $0.80$0.40 – $4.00High-volume classification, routing, extraction, RAG Q&A

Why is output 4× pricier? As you will see in Lesson 1.2, all input tokens run in one parallel GPU matrix multiplication, whereas output tokens must be generated one token at a time in a sequential loop that reloads hundreds of gigabytes of model weights from GPU VRAM for every single word!


5. Wire-Level Trace: Pre-Flight Token Counting & Cost Guardrails

Click Next below to trace what happens from raw prompt string → BPE token array → API usage receipt:

Tracing Tokenization & API Billing Across a Request
Interactive LLM Pipeline Tracer · Step 1 of 4 (1. Raw UTF-8 Strings)
Wire Telemetry:in=0 tokout=0 tokcost=$0.000000
1→system = "Return ONLY valid JSON: {sentiment, confidence}"
2→user = "Order #98450 arrived 2 days early — amazing!"
3input_ids = tokenizer.encode(system + user)
4resp = client.responses.create(model="...", input=...)
5receipt = resp.usage # {input_tokens, output_tokens}
Application Strings99 chars total
system (49 chars) + user (45 chars) + role framing markers
What's Happening: Your application starts with human-readable UTF-8 strings. Notice role wrappers (<|im_start|>system...) also add ~4 overhead tokens per message!

6. Production SDK Code: Counting Tokens Across OpenAI, Gemini & Claude

Never guess len(text) // 4 when enforcing hard budget caps. Here is how production engineers count exact tokens cleanly across all three major ecosystems:

SDK:
import tiktoken
from openai import OpenAI

# 1. Instant offline BPE token count (~0.2ms, zero network call!)
enc = tiktoken.get_encoding("o200k_base")  # GPT-4o / o-series encoding
prompt = "Explain PostgreSQL B+ Tree indexes in 3 bullet points."
tokens = enc.encode(prompt)
print(f"Tokens: {len(tokens)} | IDs: {tokens[:6]}...")

# 2. Always enforce max_output_tokens on live calls + log exact usage
client = OpenAI()
resp = client.responses.create(
  model="gpt-4o-mini",
  input=prompt,
  max_output_tokens=200,
)
print(resp.usage.input_tokens, resp.usage.output_tokens)

7. What Breaks in Production (War Stories)

  1. The Indented JSON Bloat Bill: Sending 50 pretty-printed database rows (json.dumps(rows, indent=4)) inside a RAG prompt burns thousands of tokens purely on spaces and repeated key names. Serialize tabular context as compact CSV or Markdown tables or json.dumps(rows, separators=(",", ":")) to slash input tokens by 30%–45%.
  2. Base64 Image / PDF Explosions: Never paste a raw Base64 string inside a text prompt (f"Decode this: {b64}") — a 500 KB image turns into ~170,000 text tokens! Always pass images/PDFs via the provider's native multimodal image_url / Vision block, which bills images by fixed tile counts (~250–1,000 tokens).
  3. Unbounded User Inputs (Denial-of-Wallet): Without a strict character/token cap at your API gateway, a single script pasting 100k-token payloads in a loop can drain $500 of API credits in minutes. Enforce both a pre-flight input cap and max_output_tokens on every call.

Module 1.1 Mastery Check — Tokenization & Economics

Q1.Why do modern LLMs use Byte Pair Encoding (BPE) subword tokenizers instead of whole-word or pure character vocabularies?
Q2.Why do commercial LLM APIs charge 3×–5× more per 1M OUTPUT tokens than per 1M INPUT tokens?
Q3.How does a BPE tokenizer typically handle leading spaces in English prose like ' hello world'?
Q4.Which serialization format typically consumes the FEWEST tokens when passing 100 structured product rows into an LLM prompt?

Keep Exploring: Related Lessons & Tools

All Courses →