› 01 · Tokens › What is a Token?
⚡ Visual Simulator Codebase
AI Journey · Understand Language

What is a Token?

The absolute fundamental processing unit of modern Generative AI. Explore how human text is chopped, mapped, and mathematically converted into numerical representations that deep learning engines can understand.

🔴 MUST 15 Study Phases First Topic
🔬
MiniLLM Lab · Stage 1 — Teach it to Read
Tokens are the first building block. This topic feeds directly into your tokenizer milestone.
View project →
🧙‍♂️ The Core Mental Model The Scholar's Memory vs. Words
⏮️ 00 · Math & Foundations Hub →

The Wise Scholar Speaks in Numbered Chunks (Tokens)

Think of the LLM as a wise elder scholar who has read 100,000 books. When they speak, they don't utter individual letters or continuous ink. They pull concept tokens out of their memorized dictionary (their vocabulary) one-by-one. Tokens are the discrete syllables of thought through which the scholar expresses all parametric memory.

🌐 Live Interactive Visualizers Spotlight

Test any text live with OpenAI's official visualizer or explore side-by-side models on Tiktokenizer. You can also experiment directly with our interactive simulator in Phase 05 below!

01

UnderstandWhat is a Token?

🤔 Layman Curiosity Hook

"If a super-intelligent AI chatbot can solve complex programming bugs and explain quantum physics, why does it consistently fail to count how many 'r's are in the word 'strawberry'?"

This famous, hilarious failure is not because the AI is dumb, but because of its 'eyes'. It has a visual condition called Token Blindness.

💡 This is how it happens: The AI has never seen the letters s-t-r-a-w-b-e-r-r-y independently! A tokenizer preprocessing step chopped the word into two chunks: ['straw', 'berry'], which are mapped to numbers like [1024, 4821]. To the model, the word is just a pair of integers. When you ask it to count 'r's, it has to guess based on memory because it literally cannot see the spelling!

A token is the fundamental, indivisible unit of text that a language model (LLM) reads and writes. To humans, the atomic unit of text is a word, a syllable, or a single letter. But to a machine, words are too open-ended and numerous, while single characters are too sparse and carry no immediate semantic meaning. A token represents the optimal structural bridge—a text segment that can represent a whole word, part of a word, a punctuation mark, or even raw spacing.

❓ Why we need tokens: The Numeric Impasse

Language models are, at their core, sophisticated mathematical calculators. They consist of billions of parameters (weights) that perform vector multiplications. Neural networks cannot process the raw string "Hello" directly; they require numbers. Therefore, we must have a reliable, deterministic way to translate text into numbers (indices), which can then be mapped to multi-dimensional vectors (embeddings) for mathematical processing.

Not Words

"unbelievable" may become un + believ + able — three tokens, one word. Common words like "the" or "is" typically stay as one token each because of their high training frequency.

Not Characters

"the" is not three character tokens — it's one. The tokenizer groups characters into reusable pieces that compress sequence lengths and reflect frequency in the training corpus.

📚 Terminology & Key Concepts

  • Character: The smallest text block (e.g., "a", "b", "c"). Standard ASCII or Unicode.
  • Token: A segmented text chunk chosen by a tokenizer (e.g., "un", "believ", "able").
  • Vocabulary (Vocab): A static, pre-defined dictionary of unique tokens that the model is allowed to know. Any token outside this vocab cannot be understood unless decomposed into smaller known pieces.
  • Token ID: The integer index representing a token's position in the vocabulary table. This is what is fed into the neural network.

💡 Key Concept: Tokenization does NOT understand meaning

The tokenizer is a purely statistical, deterministic pre-processor. It splits text using static tables of merges acquired during training. It has no neural weights, no comprehension of English, and simply acts as a deterministic dictionary. The model itself infers semantic meaning later in the Embedding and Attention layers.

One-sentence definition: A token is a piece of text that the tokenizer chose to treat as a single unit — it could be a whole word, a word fragment, a punctuation mark, a space, or even a single character.
02

VisualizeThe Translation Pipeline & Live Demo

Visualizing the token pipeline makes it clear where the tokenizer begins and ends, and where the actual neural model takes over.

graph TD
    A["Raw Human Text: 'I love AI'"] --> B["Tokenizer Split: ['I', ' love', ' AI']"]
    B --> C["Vocabulary Lookup: [40, 1826, 9821]"]
    C --> D["Model Input: Integer Vector [40, 1826, 9821]"]
    D --> E["Embedding Layer: Dense Vectors [3 x 4096 dimensions]"]
    
    style A fill:#3b82f6,stroke:#1d4ed8,color:#fff
    style C fill:#10b981,stroke:#047857,color:#fff
    style E fill:#8b5cf6,stroke:#6d28d9,color:#fff
          
Fig 1. The structural transformation of human text into numeric embeddings in a Transformer pipeline.

Here is how text passes through each step of the pipeline. Notice that spaces are preserved as part of the token elements:

Raw text→ Tokenizer→ Tokens→ Token IDs→ Model

Notice that spacing (like the space before love or AI) is integrated directly into the token itself. This is critical for models to reconstruct text spacing perfectly during output generation.

🔬 Live Interactive Tokenizer Sandbox

Type any sentence below, select a preset, or write your own text to see how a model slices characters into token chips and assigns vocabulary IDs in real-time!

0 Characters
0 Tokens
0.00 Chars/Token
🤖 What the LLM Sees (Token IDs)
[ ]
This live demo runs an active regular expression tokenizer mimicking subword splitting boundaries. Real-world tokenizers (like Byte-Pair Encoding or WordPiece) map each resulting slice to unique pre-trained vocabulary database indices!
03

CalculateToken Arithmetic and Cost Estimations

When engineering with LLMs (such as OpenAI's GPT models or Anthropic's Claude), token calculations dictate pricing, context limits, and latency. Let's study the rules of thumb and the arithmetic of tokens.

The Rule of Thumb

In standard English prose, the relationship between characters, words, and tokens is highly predictable:

1 Token ≈ 4 characters of English text
1 Token ≈ 0.75 words of English text
100 Tokens ≈ 75 words

Worked Example: Calculating Cost & Capacity

Let's calculate the input and output cost of processing a custom book chapter through GPT-4o, where the book chapter contains 3,000 words.

1 Calculate expected token count from word count:
$$\text{Tokens} = \frac{3,000 \text{ words}}{0.75} = 4,000 \text{ tokens}$$
2 Assume the API pricing is:
Input tokens: \$5.00 per million tokens.
Output tokens: \$15.00 per million tokens.
Our prompt has 4,000 input tokens, and the model generates a 500-token summary (approx. 375 words).
3 Calculate input cost:
$$\text{Input Cost} = 4,000 \times \left(\frac{\$5.00}{1,000,000}\right) = \$0.02$$
4 Calculate output cost:
$$\text{Output Cost} = 500 \times \left(\frac{\$15.00}{1,000,000}\right) = \$0.0075$$
$$\text{Total Cost} = \$0.02 + \$0.0075 = \$0.0275$$
04

CodeBuilding and Comparing Tokenizers

Let's make these concepts concrete. Below, we first write a basic dictionary-based tokenizer from scratch in Python, followed by a second block showing how to use a production HuggingFace tokenizer.

1. Toy Dictionary Tokenizer (From Scratch)

This script shows how string elements are converted into vocabulary indexes, with space handling and an unknown fallback character.

🧩
ToyDictionaryTokenizer — full class
encode() · decode() · [UNK] fallback · ~50 lines
python ▼
python
class ToyDictionaryTokenizer:
    def __init__(self):
        # Static predefined vocabulary with explicit spacing representation
        self.vocab = {
            "[UNK]": 0, "I": 1, " love": 2, " AI": 3, " code": 4,
            "ing": 5, "is": 6, " fun": 7, "!": 8, "python": 9
        }
        # Reverse vocabulary lookup for decoding IDs back to text
        self.reverse_vocab = {v: k for k, v in self.vocab.items()}

    def encode(self, text):
        """Translate raw string into tokens and numeric token IDs."""
        tokens = []
        token_ids = []
        # A simple whitespace split simulation for our dictionary
        raw_words = text.split(" ")
        for i, word in enumerate(raw_words):
            # Prep prefix spaces to match vocabulary formatting
            processed_word = word if i == 0 else " " + word
            
            # Simple direct matching or split fallback
            if processed_word in self.vocab:
                tokens.append(processed_word)
                token_ids.append(self.vocab[processed_word])
            else:
                # Basic character fallback or [UNK] indicator
                tokens.append("[UNK]")
                token_ids.append(self.vocab["[UNK]"])
        return tokens, token_ids

    def decode(self, ids):
        """Translate numeric IDs back into human-readable text."""
        return "".join([self.reverse_vocab.get(i, "[UNK]") for i in ids])

# Validation
tokenizer = ToyDictionaryTokenizer()
text_input = "I love python"
tokens, ids = tokenizer.encode(text_input)

print(f"Input text: '{text_input}'")
print(f"Tokens:     {tokens}")
print(f"IDs:        {ids}")
print(f"Decoded:    '{tokenizer.decode(ids)}'")

2. Production Tokenizer Comparison (HuggingFace)

Compare the simplicity of our toy tokenizer with how a transformer library (like HuggingFace) manages state, special boundary tags, and lowercase normalization.

🤗
HuggingFace AutoTokenizer — BERT WordPiece
pip install transformers · bert-base-uncased · [CLS]/[SEP] tokens
python ▼
python
# ── HuggingFace Tokenizer Example ──
# To run this, install dependencies: pip install transformers
from transformers import AutoTokenizer

# Load BERT's classic WordPiece tokenizer
tok = AutoTokenizer.from_pretrained("bert-base-uncased")

text = "I love AI systems"
enc  = tok(text)

print("Tokens:", tok.convert_ids_to_tokens(enc["input_ids"]))
# Expected output: ['[CLS]', 'i', 'love', 'ai', 'systems', '[SEP]']

print("IDs:   ", enc["input_ids"])
# Expected output: [101, 1045, 2293, 9932, 3001, 102]

# Decode back to plain text
print("Decoded back:", tok.decode(enc["input_ids"]))
# Expected output: [CLS] i love ai systems [SEP]

What to notice

  • Special boundaries [CLS] and [SEP] are auto-added for modeling constraints.
  • Input characters are automatically normalized (lower-cased by BERT).

The Universal API

Regardless of model size, the core operational sequence remains identical: encode(text) → IDs followed by decode(IDs) → text.

05

ExperimentTracing Tokenizer Spacing and Characters

Let's run a hands-on experiment to prove that tokenizers treat spaces, capitalization, punctuation, and emojis as explicit sub-units. Capitalization changes the vocabulary lookup index completely!

🍓 Live Lab: The "Strawberry" Token Blindness Simulator
Why LLMs Can't Count Characters Inside Words
3 'r's found
👀 1. What Humans See (Character Stream)
Your brain examines letters sequentially ($s \cdot t \cdot r \cdot a \cdot w \cdot b \cdot e \cdot r \cdot r \cdot y$), making letter frequency trivial.
🤖 2. What the LLM Sees (Opaque Token IDs)
The tokenizer bundles letters into opaque integer IDs. The transformer receives only numbers—it literally cannot see individual letters!
🔍 Behind-the-Scenes: The Mathematical Blind Spot Explained

When you ask GPT-4 "How many 'r's in strawberry?", this is the exact flow:

  1. Pre-processing: Tokenizer turns "strawberry" into two tokens: ["straw", "berry"].
  2. Integer Mapping: Those tokens become IDs [496, 675] in vocabulary tables.
  3. Vector Lookup: IDs retrieve row vectors $\vec{v}_{496}$ and $\vec{v}_{675}$.
  4. Neural Attention: The attention layers calculate associations for "straw" and "berry" (fruit, red, plant, pie, sweet). The vector contains zero explicit data about character-level string length or letter positions!
  5. Conclusion: To answer, the model must guess statistical associations rather than actually inspecting the characters.

Experiment 2: Tokenizer Sensitivity Sandbox

>>> # Spacing and capitalization shifts IDs completely
>>> # Prompt A: "apple" vs Prompt B: " apple"
>>> tokenizer.encode("apple")
['apple'] -> [ID: 14592]
>>> tokenizer.encode(" apple")
[' apple'] -> [ID: 3512] (Notice: totally different ID!)
>>> # Emojis require multiple token IDs due to multi-byte nature
>>> tokenizer.encode("😊")
['😊'] -> [ID: 94121, 10221] (Split into multiple pieces!)

Observations: Spacing is not discarded—it is preserved inside tokens (often represented by the Ġ glyph in BPE-style encoders). Emojis and foreign scripts are decomposed into several smaller tokens because they require more bytes in Unicode representation, explaining why emojis cost more to process in LLM queries!

06

CompareWord vs. Character vs. Subword Levels

Tokenization resides along a spectrum. Different levels trade vocabulary size against sequence length and robustness to unknown words:

Metric Word-level Character-level Subword-level (BPE / WordPiece)
Vocab Size Extremely Large (1M+) Very Small (~100-250) Optimal Medium (~32K-100K)
Sequence Length Shortest Extremely Long Balanced
Unknown Words Fails completely ([UNK]) 0% Unknowns 0% Unknowns (falls back to characters/bytes)
Meaning preservation Excellent Discards morphological roots Excellent (preserves roots/affixes)
Commonly Used By Older legacy NLP engines Byte-level networks GPT-4, Claude, LLaMA, BERT, etc.
Modern Paradigm Choice: production architectures exclusively select Subword-level strategies because they preserve prefix roots ("un-", "pre-") and suffix extensions ("-ing", "-tion") dynamically without bloating embedding matrices.
07

TheoryVocabulary, IDs, and Embeddings

Tokenization is a discrete, categorical process. There is no numeric relationship between token IDs. ID 500 is not in any sense "between" ID 499 and ID 501 semantically — they could represent completely unrelated pieces of text. The IDs are just index labels, like keys in a dictionary.

📖
Vocabulary ID mapping — "the cat sat on the mat"
IDs are positions · not arithmetic · GPT-2 vocab example
text ▼
text
Vocabulary (partial mapping list):
  "the"    → ID  279
  " cat"   → ID 4582
  " sat"   → ID 6838
  " on"    → ID  319
  " mat"   → ID  2603

Sentence: "the cat sat on the mat"
Token IDs: [ 279, 4582, 6838, 319, 279, 2603 ]

Notice:
  • ID 279 appears twice  → same token "the" reused.
  • ID 6838 - ID 4582 ≠ meaningful arithmetic!
  • The numbers are POSITIONS in the embedding matrix, nothing more.

Vocabulary is Fixed

Once the tokenizer is built, its vocabulary and merge tables never change. GPT-4's tokenizer (tiktoken cl100k) has exactly 100,277 unique tokens. Retraining is required to add any new terms.

Dense Embedding Mapping

The first actual layer of the model maps these integer indices to dense multi-dimensional floats (e.g. 4096 dimensions). Meaning and associations are computed entirely inside this continuous vector space!

Critical point: The first layer of every language model is the embedding lookup. It converts integer IDs into dense floating-point vectors. Everything the model "knows" about tokens lives in those vectors — not in the IDs themselves.
08

How It WorksThe 5-Stage Tokenization Pipeline

Modern subword tokenization isn't just a simple table lookup. It runs as a series of structured transformations converting raw string patterns into integer vectors:

INPUTRaw Text TRANSFORMATIONTokenization OUTPUTInteger IDs
1. Normalization→2. Pre-tokenization→3. Subword splitting→4. Vocabulary lookup→5. Integer IDs

Live sentence walkthrough

Inside the tokenizer — choose an example or type your own, then watch the same sentence pass through all five stages.

● LIVE INPUT
Stage 1 of 5
01Normalization

Standardize text representation; casing rules depend on the tokenizer.

INPUT → CLEANED TEXT
02Pre-tokenization

Find rough boundaries around word-like pieces and punctuation.

WORD-LIKE CHUNKS
03Subword splitting

Split rough pieces into reusable units where the vocabulary requires it.

ILLUSTRATIVE TOKEN PIECES
04Vocabulary lookup

Map each final token piece to its vocabulary index.

TOKEN → ID
05Integer IDs

Return the ordered integer sequence for the model.

MODEL-READY IDS

Normalization

Standardize text representation; casing rules depend on the tokenizer.

Learning note: This is an interactive teaching simulation. Subword splits and IDs are illustrative, not output from a production tokenizer such as tiktoken or a Hugging Face model. Real token boundaries and IDs depend on the specific tokenizer.

09

Hands-onExplore the Token Boundaries Yourself

To truly grasp token limits, you must inspect edge cases. Complete this active checklist to see how small changes shift tokenizer behaviors:

Goal: Completing these steps ensures you recognize that token boundaries are determined entirely by stats, not grammatical rules.
10

ApplyWhere Tokens Show Up in the Real World

Tokens govern almost every performance and resource ceiling in AI engineering:

  • Context Windows: When a model states it supports a "128k context window", it means 128,000 tokens (input prompts + generated outputs combined), not words or letters.
  • API Pricing: LLM platforms bill specifically by the million tokens processed. Input queries are priced differently than output text generations.
  • RAG Chunk Sizes: When building Retrieval-Augmented Generation indexes, documents are split into chunks measured in token length (e.g., 500-token blocks) to match target embedding context windows.
  • Prompt Engineering: Longer prompts or extensive few-shot instructions eat into your available token headroom and increase processing latency.

Quick English Rules

For standard English, 1 token ≈ 4 characters ≈ 0.75 words. This means 1,000 tokens is approximately 750 words, or roughly a single page of text.

Non-English Cost Multiplier

Languages with complex scripts or low training representation (e.g., Arabic, Korean, Hindi) segment into far smaller, byte-level tokens, costing up to 3-10x more for the same length message.

11

LimitsWhat Trips People Up

Understanding token limits prevents common bugs in LLM integrations. Avoid these standard traps:

Never Mix Tokenizers: Each model is trained exclusively with its own tokenizer vocabulary. You cannot use a LLaMA tokenizer with a GPT model or vice-versa. Mixing them will output garbage strings.

Mistake: Word-for-Token Substitution

Assuming a prompt of 200 words translates to exactly 200 tokens. This is false. Spaces, capitalization, and formatting always increase token counts.

Reality

There is no exact mathematical formula to convert words directly to tokens. You must run the specific tokenizer library (like tiktoken) to get the exact counts.

Mistake: Treating IDs as Continuous

Assuming ID 5000 is mathematically related to ID 5001. Vocabulary assignments are arbitrary positions in a giant lookup table.

Reality

Each model maps IDs to different embedding files. Spelling, letter reversing, and character counting tasks can easily fail because models do not see separate characters.

12

Feynman ChallengeThe Train Car Metaphor

Can you explain what a token is without sounding like an academic paper? Test your comprehension using our Feynman-style metaphor.

The Train Car Metaphor

Imagine a model is a train track that can only carry standardized cargo boxes. It cannot carry loose sand (raw letters are too numerous and unstructured), and it cannot carry an entire giant shipping vessel (words are too large to fit the tracks).

So, we have a loading dock helper (the tokenizer). When you bring a raw shipping delivery, the helper chops it up into perfect modular boxes (tokens). "Unbelievable" gets sliced into three standardized boxes: [ "un" ], [ "believ" ], and [ "able" ].

The train model travels at high speed because every cargo box fits the tracks exactly. If a new, weird cargo arrives, the helper simply chops it into smaller boxes, loading any arbitrary shipment without derailing the train!

⚠️ Common Beginner Misconceptions

  • Misconception 1: "1 Token = 1 Word". This is false. A word like "fantastic" might be 1 token, but "anticonstitutionally" could easily be 5 or 6 tokens.
  • Misconception 2: "Models think in letters". False. GPT has no native concept of the letter "a" unless it reads a token that represents only "a". Spatially, it processes text chunks. This is why older models struggle with spelling or word-reversing games!
13

BuildCapstone Mini-Project & Guided Prompts

Consolidate your understanding by building a functional component.

🛠️ Capstone Project
#charan #capstone
Interactive Token-to-ID Inspector

Build a Python CLI script or local HTML page that:

  1. Loads a predefined lookup table of common words and suffixes
    {"the": 1, "ing": 2, "es": 3}
  2. Accepts a custom input sentence from the user.
  3. Splits words, extracts matched subwords, outputs the corresponding numeric array of token IDs, and color-coordinates each word in the terminal using brackets to show exact tokenization splits.
greedy BPE  ·  color-coded chips  ·  bracket notation  ·  Python terminal  ·  live vocab editor
Ready to build? Open the interactive inspector → Launch →

📊 Guided Build Ideas

Pick one of these projects to implement and share with your team:

🔨 Toy Tokenizer

Write a simple python script with a static vocabulary dictionary, implementing standard encode() and decode() methods with safe unknown fallback markers.

📊 Token Counter Tool

Write a CLI utility that reads a file and reports exact characters, words, subword token counts, and the exact word-to-token ratio.

🎨 Token Visualizer

Build a web form that highlights token slices in alternating colours, displaying the vocabulary ID directly underneath each block.

🔬 Two-Tokenizer Compare

Compare how gpt2 vs bert-base-uncased slice the exact same inputs, displaying token differences side by side.

14

QuizFeynman Mastery Check

Which statement best describes what a token is?

10-second Feynman explanation: A token is whatever piece of text the tokenizer decides to treat as one unit. Not a word, not a character — a learned, reusable piece. The model only ever sees the integer ID of each token, and the embedding matrix turns that ID into a meaningful vector. Everything else — context windows, pricing, attention — is counted in these tokens.
15

SummaryWhat You Should Remember

🧠
Core Takeaway

The tokenizer represents the input, the LLM generates a response using learned patterns and context, and the decoder converts generated token IDs into readable text. Token usage can affect API costs, while ambiguity and unfamiliar concepts can affect response quality.

Token Fundamentals
  • ▸ Definition: A token is the smallest unit of text a language model processes — a piece decided by the tokenizer, not a word and not a character.
  • ▸ Not a word, not a character: Common words may be one token; rare words may be several; punctuation and spaces can each be a token; emojis may be many tokens.
  • ▸ Vocabulary required: Every token must exist in the tokenizer's vocabulary, which is fixed at tokenizer training time and never changes at inference time.
  • ▸ IDs are indices, not values: A token ID is a row number in the embedding matrix. There is no numeric relationship between IDs — ID 500 is not semantically greater than ID 10.
  • ▸ Meaning comes from embeddings: The embedding lookup is the first layer. It converts each integer ID into a dense floating-point vector. The model reasons with vectors, not IDs.
  • ▸ Context windows, pricing, and chunking are in tokens: Any limit or cost you encounter in practice is expressed in tokens — understanding them lets you work precisely within those constraints.
  1. 1
    Tokenizer: Converts text into tokens and maps them to numerical IDs. It doesn't decide the answer or understand your intent by itself.
  2. 2
    Question clarity: A clear, specific question helps the LLM understand your intent.
    ❌ "Explain transformers."
    ✓ "Explain how self-attention helps a Transformer understand relationships between words."
  3. 3
    Poorly written questions: LLMs can often understand misspellings, incomplete sentences and informal language, but ambiguity can lead to incorrect responses.
    ❌ "wat is transfrmr"
    ✓ "What is a Transformer in AI?"
  4. 4
    Ambiguity: Poor question clarity can create ambiguity when a question has multiple possible meanings.
    ❌ "Explain Python."
    ✓ "Explain Python as a programming language."
    The LLM uses context to infer the intended meaning but can interpret the question incorrectly.
  5. 5
    Not a grammar-correction step: The tokenizer primarily converts text into tokens and IDs. It does not normally correct spelling, grammar or sentence structure.
  6. 6
    LLM response: The model processes token representations using learned patterns and context to predict the next token and generate a response. More words don't automatically mean a better answer; relevant details and clear intent matter most.
  7. 7
    Token usage and pricing: API costs often depend on input and output tokens.
    Input tokens
    Your question, instructions and relevant conversation context
    Output tokens
    The answer generated by the model
    More tokens generally mean higher cost, depending on pricing rates.
  8. 8
    Input tokens: The tokenizer converts supplied text into token IDs, which are mapped to embeddings before the LLM processes them.
  9. 9
    Output tokens: The LLM predicts and selects token IDs one at a time to generate its response.
  10. 10
    Decoder / detokenizer: Converts generated token IDs back into readable text.
  11. 11
    Token IDs in both directions: With the same tokenizer and vocabulary, encoding and decoding use the same ID mapping. However, IDs can mean different things across tokenizers, and decoding isn't always perfectly reversible.
  12. 12
    Capitalization matters: Uppercase and lowercase text can produce different tokens or token IDs, which may influence the model's output.
    apple vs. Apple — may have different tokenizations and meanings
    us vs. US — pronoun vs. United States
    Capitalization can affect interpretation, but it doesn't always change the answer.
  13. 13
    Vocabulary size: A tokenizer's vocabulary contains its available token entries, each associated with a token ID. For example, cl100k_base has 100,277 vocabulary entries. Tokens can represent words, word fragments, punctuation, whitespace patterns and other text pieces.
  14. 14
    When a word exists in the vocabulary: The tokenizer can represent it using its corresponding token ID. If a whole word isn't available as one token, the tokenizer may split it into smaller pieces.
  15. 15
    What if a word cannot be found in the vocabulary, even after splitting?
    • Modern byte-level tokenizers can generally represent unfamiliar text using available byte-level tokens.
    • The LLM receives the resulting token IDs but may not know what an unfamiliar or invented word means.
    • It may admit uncertainty, infer a meaning from context, or invent an incorrect explanation.
    • Successful tokenization does not guarantee correct understanding. The tokenizer represents text; hallucination can occur in the model's generated response.
Complete Mental Model
Input text → Tokenizer → Token IDs → Embeddings → LLM → Generated Token IDs → Decoder → Readable output
Question clarity, spelling and capitalization all feed into context before the LLM processes them. Token usage drives API cost. Ambiguity and unfamiliar vocabulary can degrade response quality.
This page 0:00
This session 0:00
Total (all pages) 0:00
Today 0:00
▶ Running
📊 View all study stats →
0:00 studying