Module lessons (1/4)
How LLMs Process Text: The Tokenizer Deep Dive
How LLMs Read Text: The Subword Tokenizer
Large Language Models do not process characters or words directly. Instead, they ingest sequences of discrete integer Token IDs generated by a subword tokenizer (most commonly Byte-Pair Encoding, or BPE).
A common rule of thumb for English text is:
- 1 token ≈ 4 characters (or ~0.75 words).
- 1,000 tokens ≈ 750 words.
However, this ratio diverges significantly when processing source code, JSON keys, numbers, or non-Latin alphabets (such as Arabic, Hindi, or Japanese), where single characters often split into multiple UTF-8 byte tokens.
| Modality / Content | Typical Ratio (Chars / Token) | Why It Matters |
|---|---|---|
| Standard English prose | ~4.0 chars / token | Baseline cost for prompts |
| Python / JS Source Code | ~2.5 - 3.0 chars / token | Indentation and punctuation expand |
| JSON API Payloads | ~2.2 - 2.8 chars / token | Repeated keys & quotes consume TPM |
| Non-Latin Scripts | ~1.2 - 1.8 chars / token | UTF-8 multibyte fragmentation |
Interactive Tokenizer & Compression Lab
Experiment with real-time Byte-Pair Encoding subword segmentation across prose, source code, JSON payloads, and multibyte Unicode:
Token Counting & Budget Estimation in Python
In production systems, estimating token counts before dispatching requests to LLM APIs is essential to prevent context_length_exceeded runtime errors and manage Rate Limits (Tokens Per Minute — TPM).
def estimate_tokens(text: str, chars_per_token: float = 4.0) -> int:
"""Fast pre-flight token estimate before calling model APIs."""
if not text:
return 0
return max(1, int(len(text) / chars_per_token))
prompt = "Explain the difference between dense and sparse vector embeddings in detail."
print(estimate_tokens(prompt)) # ~19 tokensCheck Your Understanding
Why do non-Latin alphabets (like Japanese or Arabic) consume more tokens per sentence than English?
Practice: Subword Token Counting & Sliding Windows
Warmup — Estimate token budgets
Write estimate_prompt_cost(num_chars, rate_per_million, chars_per_token=4.0) that calculates the dollar cost of processing a prompt. Round the cost to 6 decimal places.
Show hint
Compute tokens as num_chars / chars_per_token, then multiply (tokens / 1_000_000) by the rate per million.
Solution available after 3 attempts
Practice — Safe token truncation
Write truncate_to_budget(text, max_tokens, chars_per_token=4.0) that truncates text so estimated tokens never exceed max_tokens. Return the truncated string.
Show hint
Compute max_chars = int(max_tokens * chars_per_token) and slice text[:max_chars].
Solution available after 3 attempts
Mastery — Multi-document token allocator
Write allocate_token_budget(scores, total_budget) that accepts a list of positive float relevance scores and returns a list of integer token budgets proportional to each score, summing to total_budget.
Show hint
Normalize scores to sum to 1.0, multiply by total_budget, and assign any rounding remainder to the highest-scoring document.
Solution available after 3 attempts