Nlp_review / tokenization.html
Soha85's picture
Update tokenization.html
5c588ac verified
Raw History Blame Contribute Delete
47.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tokenization: A Complete NLP Reference</title>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=Fraunces:ital,wght@0,300;0,700;1,300&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
:root {
--ink: #0f0e0c;
--paper: #f5f0e8;
--cream: #ede8dc;
--accent: #c85a1e;
--accent2: #2a6e5a;
--accent3: #1a4a7a;
--muted: #6b6560;
--border: #c8c0b0;
--code-bg: #1e1c18;
--code-fg: #e8dfc8;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'DM Sans', sans-serif; background: var(--paper); color: var(--ink); font-size: 15px; line-height: 1.7; }
/* ── HERO ── */
.hero { background: var(--ink); color: var(--paper); padding: 64px 48px 56px; position: relative; overflow: hidden; }
.hero::before { content: 'TOKEN'; font-family: 'Fraunces', serif; font-size: 200px; font-weight: 700; color: rgba(255,255,255,0.04); position: absolute; right: -10px; top: -10px; letter-spacing: -8px; user-select: none; }
.hero-label { font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: 3px; color: var(--accent); text-transform: uppercase; margin-bottom: 16px; }
.hero h1 { font-family: 'Fraunces', serif; font-size: clamp(36px, 5vw, 60px); font-weight: 300; line-height: 1.1; max-width: 640px; }
.hero h1 em { font-style: italic; color: #c8b89a; }
.hero-sub { margin-top: 20px; color: #9a9488; max-width: 540px; font-size: 16px; }
.hero-tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 28px; }
.hero-tag { font-family: 'IBM Plex Mono', monospace; font-size: 10px; letter-spacing: 1.5px; text-transform: uppercase; padding: 4px 10px; border: 1px solid rgba(255,255,255,0.15); color: #9a9488; }
/* ── NAV ── */
.nav { background: var(--cream); border-bottom: 1px solid var(--border); padding: 0 48px; display: flex; overflow-x: auto; position: sticky; top: 0; z-index: 100; }
.nav-item { font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: 1px; text-transform: uppercase; padding: 14px 20px; cursor: pointer; color: var(--muted); border-bottom: 2px solid transparent; white-space: nowrap; transition: all .2s; }
.nav-item:hover { color: var(--ink); }
.nav-item.active { color: var(--accent); border-bottom-color: var(--accent); }
/* ── LAYOUT ── */
.section { padding: 64px 48px; max-width: 1100px; margin: 0 auto; display: none; }
.section.active { display: block; }
.sec-header { display: flex; align-items: baseline; gap: 16px; margin-bottom: 40px; padding-bottom: 20px; border-bottom: 1px solid var(--border); }
.sec-num { font-family: 'Fraunces', serif; font-size: 56px; font-weight: 700; color: var(--border); line-height: 1; }
.sec-title { font-family: 'Fraunces', serif; font-size: 32px; font-weight: 300; }
h3 { font-family: 'Fraunces', serif; font-size: 20px; font-weight: 700; margin: 36px 0 12px; }
p { margin-bottom: 14px; color: #2a2620; }
/* ── CODE ── */
.code-block { background: var(--code-bg); border-radius: 4px; padding: 20px 24px; font-family: 'IBM Plex Mono', monospace; font-size: 13px; color: var(--code-fg); line-height: 1.9; margin: 16px 0; overflow-x: auto; white-space: pre; }
.cm { color: #6b6050; }
.kw { color: #e8a060; }
.st { color: #80c080; }
.ar { color: var(--accent); font-weight: 600; }
/* ── TOKEN VIS ── */
.token-vis { background: var(--cream); border: 1px solid var(--border); border-radius: 4px; padding: 18px 20px; margin: 14px 0; }
.token-label { font-family: 'IBM Plex Mono', monospace; font-size: 12px; color: var(--muted); margin-bottom: 10px; }
.token-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.tok { font-family: 'IBM Plex Mono', monospace; font-size: 13px; font-weight: 600; padding: 4px 10px; border-radius: 3px; }
.t1 { background: rgba(200,90,30,.15); color: var(--accent); border: 1px solid rgba(200,90,30,.3); }
.t2 { background: rgba(42,110,90,.15); color: var(--accent2); border: 1px solid rgba(42,110,90,.3); }
.t3 { background: rgba(26,74,122,.15); color: var(--accent3); border: 1px solid rgba(26,74,122,.3); }
.t4 { background: rgba(122,58,110,.15); color: #7a3a6e; border: 1px solid rgba(122,58,110,.3); }
.unk { background: #2a1a1a; color: #ff6060; border: 1px solid #ff3030; font-size: 12px; }
.tchar { background: var(--ink); color: var(--paper); font-size: 11px; padding: 3px 7px; }
/* ── CALLOUT BOXES ── */
.problem-box { border-left: 3px solid var(--accent); background: rgba(200,90,30,.06); padding: 14px 18px; margin: 14px 0; }
.problem-box strong { color: var(--accent); }
.insight-box { border-left: 3px solid var(--accent2); background: rgba(42,110,90,.06); padding: 14px 18px; margin: 14px 0; }
.insight-box strong { color: var(--accent2); }
/* ── FLOW DIAGRAM ── */
.flow { display: flex; flex-direction: column; max-width: 560px; margin: 24px 0; }
.fn { padding: 13px 18px; font-family: 'IBM Plex Mono', monospace; font-size: 13px; }
.fn-word { background: #2a2620; color: #e8dfc8; }
.fn-oov { background: #3a1a1a; color: #ff9090; }
.fn-char { background: #1a2a2a; color: #90d0d0; }
.fn-warn { background: #2a2418; color: #d0b060; }
.fn-sub { background: #1a2a1a; color: #90d890; border: 2px solid #40b840; }
.fn-llm { background: #1a1a2a; color: #9090e8; }
.fn-fut { background: #2a1a2a; color: #d090d0; }
.fn .badge { float: right; font-size: 10px; letter-spacing: 1px; opacity: .6; }
.fa { text-align: center; color: var(--muted); font-size: 16px; background: var(--paper); padding: 3px; line-height: 1.4; }
/* ── TIMELINE ── */
.timeline { position: relative; padding-left: 32px; margin: 24px 0; }
.timeline::before { content: ''; position: absolute; left: 8px; top: 0; bottom: 0; width: 2px; background: var(--border); }
.tl-item { position: relative; margin-bottom: 36px; }
.tl-dot { position: absolute; left: -28px; top: 6px; width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--paper); }
.d-w { background: var(--muted); }
.d-c { background: var(--accent3); }
.d-s { background: var(--accent2); }
.d-f { background: var(--accent); }
.tl-year { font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: var(--muted); letter-spacing: 1px; }
.tl-title { font-family: 'Fraunces', serif; font-size: 20px; font-weight: 700; margin: 3px 0 8px; }
/* ── TABLES ── */
.table-wrap { overflow-x: auto; margin: 16px 0; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th { font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: 1px; text-transform: uppercase; background: var(--ink); color: var(--paper); padding: 12px 16px; text-align: left; }
td { padding: 11px 16px; border-bottom: 1px solid var(--border); vertical-align: top; }
tr:nth-child(even) td { background: var(--cream); }
td:first-child { font-family: 'IBM Plex Mono', monospace; font-size: 12px; font-weight: 600; }
.bp { display: inline-block; font-family: 'IBM Plex Mono', monospace; font-size: 10px; padding: 2px 7px; border-radius: 20px; margin: 1px; }
.bp-o { background: rgba(200,90,30,.15); color: var(--accent); }
.bp-b { background: rgba(42,110,90,.15); color: var(--accent2); }
.bp-t { background: rgba(26,74,122,.15); color: var(--accent3); }
/* ── BPE STEPS ── */
.bpe-steps { display: flex; flex-direction: column; gap: 10px; margin: 16px 0; }
.bpe-step { display: flex; align-items: flex-start; gap: 16px; background: var(--cream); border: 1px solid var(--border); padding: 14px 18px; }
.step-n { font-family: 'Fraunces', serif; font-size: 28px; font-weight: 700; color: var(--border); min-width: 28px; line-height: 1.2; }
.step-b { padding-top: 4px; }
.step-b strong { color: var(--accent); font-family: 'IBM Plex Mono', monospace; font-size: 12px; }
/* ── CARDS ── */
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; margin: 16px 0; }
.card { border: 1px solid var(--border); padding: 18px; }
.card-icon { font-size: 24px; margin-bottom: 8px; }
.card-title { font-family: 'Fraunces', serif; font-size: 17px; font-weight: 700; margin-bottom: 6px; }
.card p { font-size: 13px; color: var(--muted); margin: 0; }
/* ── PIPELINE ── */
.pipe-label { font-family: 'IBM Plex Mono', monospace; font-size: 10px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); margin-bottom: 6px; }
.pipeline { display: flex; flex-wrap: wrap; align-items: center; background: var(--code-bg); padding: 16px; border-radius: 4px; margin: 6px 0 18px; }
.ps { font-family: 'IBM Plex Mono', monospace; font-size: 11px; padding: 6px 11px; margin: 3px; }
.ps-old { background: rgba(200,90,30,.3); color: #ff9060; text-decoration: line-through; opacity: .7; }
.ps-keep { background: rgba(42,110,90,.3); color: #80d880; }
.pa { color: #4a4840; font-size: 13px; padding: 0 2px; }
/* ── CROSS-FIELD GRID ── */
.cross-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin: 16px 0; }
.cross-card { background: var(--cream); border: 1px solid var(--border); padding: 16px; text-align: center; }
.cross-field { font-family: 'IBM Plex Mono', monospace; font-size: 10px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); margin-bottom: 10px; }
.c-from { font-size: 12px; color: #d06060; text-decoration: line-through; }
.c-mid { font-size: 11px; color: var(--muted); margin: 2px 0; }
.c-to { font-size: 12px; color: #60c860; font-weight: 600; }
/* ── REFS ── */
.ref-list { list-style: none; }
.ref-list li { padding: 14px 0; border-bottom: 1px solid var(--border); display: flex; gap: 16px; align-items: baseline; }
.ref-num { font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: var(--accent); min-width: 28px; }
.ref-content { flex: 1; font-size: 14px; }
.ref-content em { color: var(--muted); font-style: italic; }
/* ── DEMO ── */
.demo-area { background: var(--cream); border: 1px solid var(--border); padding: 24px; margin: 20px 0; }
.demo-area label { font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: 2px; text-transform: uppercase; color: var(--muted); display: block; margin-bottom: 8px; }
.demo-input { width: 100%; font-family: 'IBM Plex Mono', monospace; font-size: 15px; padding: 12px; border: 1px solid var(--border); background: var(--paper); color: var(--ink); outline: none; }
.demo-input:focus { border-color: var(--accent); }
.demo-modes { display: flex; gap: 8px; margin: 12px 0; flex-wrap: wrap; }
.mode-btn { font-family: 'IBM Plex Mono', monospace; font-size: 11px; letter-spacing: 1px; padding: 6px 14px; border: 1px solid var(--border); background: transparent; cursor: pointer; transition: all .15s; color: var(--ink); }
.mode-btn:hover { background: var(--ink); color: var(--paper); }
.mode-btn.active { background: var(--accent); color: white; border-color: var(--accent); }
.demo-result { margin-top: 14px; min-height: 48px; }
.demo-stats { font-family: 'IBM Plex Mono', monospace; font-size: 12px; color: var(--muted); margin-top: 10px; }
@media (max-width: 640px) {
.hero { padding: 36px 20px; }
.nav { padding: 0 10px; }
.section { padding: 36px 18px; }
.cross-grid { grid-template-columns: 1fr; }
.sec-num { font-size: 36px; }
.sec-title { font-size: 22px; }
}
</style>
</head>
<body>
<!-- ══ HERO ══ -->
<div class="hero">
<div class="hero-label">NLP Educational Reference</div>
<h1>Tokenization:<br><em>From words<br>to subwords</em></h1>
<p class="hero-sub">How machines learned to read β€” from rigid word dictionaries to subwords</p>
<!-- <div class="hero-tags">
<span class="hero-tag">NLP</span>
<span class="hero-tag">Deep Learning</span>
<span class="hero-tag">BPE</span>
<span class="hero-tag">WordPiece</span>
<span class="hero-tag">Transformers</span>
<span class="hero-tag">LLMs</span>
<span class="hero-tag">CANINE</span>
</div>-->
</div>
<!-- ══ NAV ══ -->
<nav class="nav" id="mainNav">
<div class="nav-item active" onclick="show('what', this)">What &amp; Why</div>
<div class="nav-item" onclick="show('evo', this)">Evolution</div>
<div class="nav-item" onclick="show('bpe', this)">BPE Deep Dive</div>
<div class="nav-item" onclick="show('sota', this)">Methods &amp; Models</div>
<div class="nav-item" onclick="show('future',this)">Future &amp; Raw Text</div>
<div class="nav-item" onclick="show('demo', this)">Live Demo</div>
<div class="nav-item" onclick="show('refs', this)">References</div>
</nav>
<!-- ════════════════════════════════════════
01 β€” WHAT & WHY
════════════════════════════════════════ -->
<section class="section active" id="sec-what">
<div class="sec-header">
<span class="sec-num">01</span>
<span class="sec-title">What Is Tokenization &amp; Why Does It Matter?</span>
</div>
<p>Tokenization is the <strong>bridge between raw text and numerical representation</strong>. Since machines process numbers, not strings, text must be converted into a sequence of integer IDs drawn from a vocabulary before any model can process it. Each unit in that sequence is a <em>token</em>.</p>
<div class="token-vis">
<div class="token-label">"The model is tokenizing." β†’</div>
<div class="token-row">
<span class="tok t2">The</span>
<span class="tok t1">model</span>
<span class="tok t3">is</span>
<span class="tok t1">token</span>
<span class="tok t4">izing</span>
<span class="tok t2">.</span>
</div>
<div style="margin-top:10px;font-family:'IBM Plex Mono',monospace;font-size:12px;color:var(--muted)">
β†’ [464, 2746, 318, 11241, 1710, 13] &nbsp;Β·&nbsp; integer IDs into an embedding matrix
</div>
</div>
<h3>What, How, and Why</h3>
<div class="cards">
<div class="card">
<div class="card-icon">❓</div>
<div class="card-title">What</div>
<p>Translation from text strings to integer IDs. The model never sees letters β€” only numbers that index into a learned embedding matrix.</p>
</div>
<div class="card">
<div class="card-icon">βš™οΈ</div>
<div class="card-title">How</div>
<p>Modern systems use <strong>Subword Tokenization</strong>. Algorithms like BPE start with individual characters and iteratively merge the most frequent adjacent pairs into common subwords.</p>
</div>
<div class="card">
<div class="card-icon">πŸ’‘</div>
<div class="card-title">Why</div>
<p>Reduces input complexity and vocabulary size. Without it, a model would need to learn every possible character sequence from scratch β€” computationally intractable.</p>
</div>
</div>
<h3>Role in LLMs</h3>
<p>LLMs have a fixed <strong>context window</strong> (e.g., 128k tokens). Efficient tokenization directly determines how much text fits within that window β€” more efficient tokenization means more context, better reasoning.</p>
<p>By sharing subword representations, models also generalize across related words: <em>run, running, runner</em> all share the subword <code>run</code>. This improves accuracy and reduces the parameters needed to learn language.</p>
</section>
<!-- ════════════════════════════════════════
02 β€” EVOLUTION
The OOV problem is introduced here, not in Β§01.
Flow diagram gives the overview; timeline gives the detail.
CANINE gets only a brief mention here β€” full treatment is in Β§05.
════════════════════════════════════════ -->
<section class="section" id="sec-evo">
<div class="sec-header">
<span class="sec-num">02</span>
<span class="sec-title">The Evolution of Tokenization</span>
</div>
<p>Research moved from rigid dictionary lookup to flexible learned subwords, driven entirely by one recurring failure: the <strong>Out-of-Vocabulary (OOV) problem</strong> β€” any word absent from the lexicon silently collapsed into a meaningless <code>&lt;UNK&gt;</code> token.</p>
<div class="flow">
<div class="fn fn-word">πŸ“š Word Tokenization + Lexicons <span class="badge">Pre-2016</span></div>
<div class="fa">↓ problem emerges</div>
<div class="fn fn-oov">⚠️ OOV Crisis β†’ &lt;UNK&gt; tokens destroy meaning</div>
<div class="fa">↓ first attempted fix</div>
<div class="fn fn-char">πŸ”€ Character-Level Tokenization <span class="badge">~2015</span></div>
<div class="fa">↓ creates a new problem</div>
<div class="fn fn-warn">⚑ Sequences too long · Characters carry no semantics</div>
<div class="fa">↓ the breakthrough</div>
<div class="fn fn-sub">βœ… Subword Tokenization β€” BPE, WordPiece, SentencePiece <span class="badge">2016–Now</span></div>
<div class="fa">↓ enables</div>
<div class="fn fn-llm">🧠 Modern LLM Era β€” GPT, BERT, LLaMA, Claude <span class="badge">2018–Now</span></div>
<div class="fa">↓ emerging frontier</div>
<div class="fn fn-fut">πŸš€ Tokenization-Free β€” CANINE, ByT5 <span class="badge">2021 β†’ Future</span></div>
</div>
<div class="timeline">
<div class="tl-item">
<div class="tl-dot d-w"></div>
<div class="tl-year">PRE-2016 Β· ERA 1</div>
<div class="tl-title">Word-Based + Lexicons</div>
<p>Text was split at word boundaries (spaces and punctuation). A <strong>lexicon</strong> mapped each known word to an integer ID. English has 170K+ words; Turkish and Finnish have millions of inflected forms β€” complete coverage was impossible.</p>
<div class="token-vis">
<div class="token-label">A new word enters the language:</div>
<div class="token-row">
<span class="tok t2">Covid</span>
<span style="margin:0 8px;color:var(--muted)">β†’</span>
<span class="tok unk">&lt;UNK&gt;</span>
<span style="font-size:12px;color:var(--muted);margin-left:10px;font-family:'IBM Plex Mono',monospace">all meaning lost</span>
</div>
</div>
<div class="problem-box">
<strong>The OOV Crisis:</strong> "Bitcoiners" in 2010? <code>&lt;UNK&gt;</code>. "Covid" in 2019? <code>&lt;UNK&gt;</code>. Any neologism, brand name, or rare proper noun silently collapsed to a single meaningless token. The model was blind to vocabulary evolution.
</div>
</div>
<div class="tl-item">
<div class="tl-dot d-c"></div>
<div class="tl-year">~2015 Β· ERA 2</div>
<div class="tl-title">Character-Level Tokenization</div>
<p>Splitting text into individual characters eliminated OOV entirely β€” only 26–256 token types are ever needed. But it introduced a worse trade-off.</p>
<div class="token-vis">
<div class="token-label">"unhappiness" β€” 11 tokens, no semantic meaning per token:</div>
<div class="token-row">
<span class="tok tchar">u</span><span class="tok tchar">n</span><span class="tok tchar">h</span><span class="tok tchar">a</span><span class="tok tchar">p</span><span class="tok tchar">p</span><span class="tok tchar">i</span><span class="tok tchar">n</span><span class="tok tchar">e</span><span class="tok tchar">s</span><span class="tok tchar">s</span>
</div>
</div>
<div class="problem-box"><strong>New problem:</strong> Sequences become 4Γ— longer than word-based tokenization. The attention mechanism must span hundreds of individual characters to capture any word-level meaning. Context windows fill up instantly on normal documents.</div>
</div>
<div class="tl-item">
<div class="tl-dot d-s"></div>
<div class="tl-year">2016–PRESENT Β· ERA 3</div>
<div class="tl-title">The Subword Revolution</div>
<p>BPE (Sennrich et al., 2016) introduced the decisive insight: <em>learn token boundaries from data itself.</em> Frequent words become single tokens; rare words decompose into meaningful morphological parts. No fixed dictionary is required β€” the vocabulary is learned.</p>
<div class="token-vis">
<div class="token-label">"unhappiness" β€” 3 tokens, meaningful morphological units:</div>
<div class="token-row">
<span class="tok t1">un</span><span class="tok t2">happi</span><span class="tok t3">ness</span>
</div>
</div>
<div class="insight-box"><strong>What this solved:</strong> No OOV. No lexicons. "unfriendable" tokenizes automatically β€” because <em>un-</em>, <em>friend</em>, and <em>-able</em> are already known subwords. The model generalizes to any unseen word through decomposition.</div>
</div>
<div class="tl-item">
<div class="tl-dot d-f"></div>
<div class="tl-year">2021 – FUTURE Β· ERA 4</div>
<div class="tl-title">Tokenization-Free Models</div>
<p>Google's CANINE (2021) was the first pre-trained model with <em>zero tokenization</em>. It processes raw Unicode characters directly β€” no vocabulary, no fixed token set, 104 languages without any language-specific rules. The tokenizer component is eliminated entirely. See Β§05 for the full picture.</p>
</div>
</div>
</section>
<!-- ════════════════════════════════════════
03 β€” BPE DEEP DIVE
Algorithm, worked example, then the three format variants together.
════════════════════════════════════════ -->
<section class="section" id="sec-bpe">
<div class="sec-header">
<span class="sec-num">03</span>
<span class="sec-title">BPE β€” The Algorithm That Changed NLP</span>
</div>
<p>Byte Pair Encoding was originally a <strong>data compression algorithm</strong> from the 1990s. Sennrich et al. (2016) adapted it for neural machine translation with a simple insight: <em>frequently co-occurring character pairs should become their own tokens.</em></p>
<h3>The Algorithm</h3>
<div class="bpe-steps">
<div class="bpe-step">
<div class="step-n">1</div>
<div class="step-b"><strong>INIT</strong> β€” Split every word in the training corpus into individual characters. These characters are the starting vocabulary.</div>
</div>
<div class="bpe-step">
<div class="step-n">2</div>
<div class="step-b"><strong>COUNT</strong> β€” Find the single most frequently occurring adjacent pair of tokens across the entire corpus.</div>
</div>
<div class="bpe-step">
<div class="step-n">3</div>
<div class="step-b"><strong>MERGE</strong> β€” Combine that pair into one new token everywhere it appears. Add it to the vocabulary.</div>
</div>
<div class="bpe-step">
<div class="step-n">4</div>
<div class="step-b"><strong>REPEAT</strong> β€” Return to step 2 until the vocabulary reaches the target size (typically 32K–100K tokens).</div>
</div>
</div>
<h3>Worked Example</h3>
<div class="code-block"><span class="cm">// Corpus: "lower" "lowest" "newest"
// Step 0: Every word split to characters</span>
<span class="kw">Initial:</span> <span class="st">l o w e r</span> Β· <span class="st">l o w e s t</span> Β· <span class="st">n e w e s t</span>
<span class="kw">Step 1:</span> Most frequent pair: (e, s) β†’ merge β†’ <span class="ar">"es"</span>
<span class="st">l o w e r</span> Β· <span class="st">l o w es t</span> Β· <span class="st">n e w es t</span>
<span class="kw">Step 2:</span> Most frequent pair: (es, t) β†’ merge β†’ <span class="ar">"est"</span>
<span class="st">l o w e r</span> Β· <span class="st">l o w est</span> Β· <span class="st">n e w est</span>
<span class="kw">Step 3:</span> Most frequent pair: (l, o) β†’ merge β†’ <span class="ar">"lo"</span>
<span class="st">lo w e r</span> Β· <span class="st">lo w est</span> Β· <span class="st">n e w est</span>
<span class="kw">Step 4:</span> Most frequent: (lo, w) β†’ merge β†’ <span class="ar">"low"</span>
<span class="st">low e r</span> Β· <span class="st">low est</span> Β· <span class="st">n e w est</span>
<span class="cm">// Vocabulary now includes: low, er, est, new, n, e, w...
// Any unknown word decomposes from these known subwords automatically.</span></div>
<h3>How the Three Major Variants Differ</h3>
<p>All three algorithms share BPE's philosophy but differ in merge strategy and output format:</p>
<div class="token-vis">
<div class="token-label">BPE (GPT-family) β€” merges by raw frequency Β· plain concatenation</div>
<div class="token-row"><span class="tok t1">un</span><span class="tok t2">happi</span><span class="tok t3">ness</span></div>
</div>
<div class="token-vis">
<div class="token-label">WordPiece (BERT) β€” merges by corpus likelihood Β· <code>##</code> marks continuation subwords</div>
<div class="token-row"><span class="tok t1">un</span><span class="tok t2">##believ</span><span class="tok t3">##able</span></div>
</div>
<div class="token-vis">
<div class="token-label">SentencePiece (T5, ALBERT) β€” whitespace treated as a character <code>▁</code> Β· no pre-tokenization step needed</div>
<div class="token-row"><span class="tok t2">▁Hello</span><span class="tok t3">▁world</span></div>
</div>
<div class="insight-box">
<strong>Why decomposition works:</strong> Even without seeing "unfriendable" in training, a BPE model already knows <em>un-</em> (negation), <em>friend</em> (root concept), and <em>-able</em> (capability suffix). Morphological meaning is recovered through decomposition, not dictionary lookup.
</div>
</section>
<!-- ════════════════════════════════════════
04 β€” METHODS & MODELS
Comparison table of all algorithms.
The Before/After comparison is the natural conclusion of this section.
════════════════════════════════════════ -->
<section class="section" id="sec-sota">
<div class="sec-header">
<span class="sec-num">04</span>
<span class="sec-title">Methods &amp; Which Models Use Them</span>
</div>
<p>Today's tokenizers all share the subword philosophy but differ in merge strategy, output format, and architectural assumptions. Each co-evolved with a specific family of models.</p>
<div class="table-wrap">
<table>
<thead>
<tr><th>Method</th><th>Merge Strategy</th><th>Distinctive Feature</th><th>Used In</th></tr>
</thead>
<tbody>
<tr>
<td>BPE</td>
<td>Raw frequency</td>
<td>Simple; plain concatenation; language-agnostic</td>
<td><span class="bp bp-o">GPT-2</span><span class="bp bp-o">GPT-4</span><span class="bp bp-o">LLaMA</span></td>
</tr>
<tr>
<td>WordPiece</td>
<td>Maximizes corpus likelihood</td>
<td><code>##</code> prefix marks continuation tokens</td>
<td><span class="bp bp-b">BERT</span><span class="bp bp-b">DistilBERT</span></td>
</tr>
<tr>
<td>SentencePiece</td>
<td>Treats whitespace as a character</td>
<td>No pre-tokenization; multilingual by default</td>
<td><span class="bp bp-t">T5</span><span class="bp bp-t">ALBERT</span><span class="bp bp-t">XLNet</span></td>
</tr>
<tr>
<td>Unigram</td>
<td>Starts large, prunes by loss</td>
<td>Probabilistic; retains tokens minimizing perplexity</td>
<td>Often paired with SentencePiece</td>
</tr>
<tr>
<td>Tiktoken</td>
<td>Byte-level BPE on raw bytes</td>
<td>Zero encoding failures β€” every byte value is valid</td>
<td><span class="bp bp-o">GPT-4</span><span class="bp bp-o">Claude</span></td>
</tr>
</tbody>
</table>
</div>
<h3>What Subword Tokenization Fixed</h3>
<div class="table-wrap">
<table>
<thead><tr><th>Problem</th><th>Word-Based Era</th><th>Subword Era</th></tr></thead>
<tbody>
<tr><td>Unknown words</td><td>&lt;UNK&gt; β€” meaning destroyed</td><td>Decomposed into subwords; no UNK ever</td></tr>
<tr><td>Lexicons</td><td>Required; always incomplete</td><td>Not needed; vocabulary learned from data</td></tr>
<tr><td>New languages</td><td>Custom rules per language</td><td>One tokenizer handles 100+ languages</td></tr>
<tr><td>Vocabulary size</td><td>100K–1M+ word forms needed</td><td>32K–100K subwords covers all of it</td></tr>
<tr><td>Morphology</td><td>run / running treated as unrelated</td><td>Shared subwords encode morphological links</td></tr>
</tbody>
</table>
</div>
</section>
<!-- ════════════════════════════════════════
05 β€” FUTURE & RAW TEXT ERA
Merged: subword shortcomings β†’ tokenization-free models β†’
preprocessing inversion β†’ cross-field pattern.
All one continuous argument.
════════════════════════════════════════ -->
<section class="section" id="sec-future">
<div class="sec-header">
<span class="sec-num">05</span>
<span class="sec-title">The Future β€” From Tokenization-Free to Raw Text</span>
</div>
<p>Tokenization isn't being improved β€” it's being <strong>eliminated</strong>. In parallel, the preprocessing pipelines that preceded tokenization have also been abandoned. Both shifts are part of the same underlying pattern: deep learning learns better representations than human-engineered ones.</p>
<h3>Why Subwords Are Still Falling Short</h3>
<div class="problem-box">
<strong>Language inequity:</strong> Non-Latin scripts and morphologically rich languages suffer 3–5Γ— higher tokenization costs than English β€” a real computational and economic barrier to multilingual AI.<br><br>
<strong>Fragmentation:</strong> BPE over-segments in multilingual settings, hurting cross-lingual transfer learning.<br><br>
<strong>Static vocabularies:</strong> A fixed token set cannot adapt to new domains, code-switching, or emerging language.
</div>
<h3>Tokenization-Free Models</h3>
<p>Google's <strong>CANINE</strong> (2021) was the first pre-trained encoder with zero tokenization. It processes raw Unicode characters using hash-based embeddings and strided convolutions for downsampling β€” no vocabulary required at any stage.</p>
<div class="cards">
<div class="card">
<div class="card-icon">πŸ”’</div>
<div class="card-title">No Vocabulary</div>
<p>Character embeddings via hashing. Emojis, typos, code-switching, any Unicode β€” all handled identically without special cases.</p>
</div>
<div class="card">
<div class="card-icon">πŸ“‰</div>
<div class="card-title">Fewer Params, Better Results</div>
<p>Outperforms mBERT by +5.7 F1 on TyDi QA with 28% fewer parameters and no fixed vocabulary.</p>
</div>
<div class="card">
<div class="card-icon">🌍</div>
<div class="card-title">104 Languages</div>
<p>No language-specific rules, dictionaries, or model variants β€” one architecture handles them all natively.</p>
</div>
</div>
<h3>Active Research Directions (2024–2026)</h3>
<div class="table-wrap">
<table>
<thead><tr><th>Direction</th><th>Description</th><th>Status</th></tr></thead>
<tbody>
<tr><td>Byte-Level Models</td><td>Operate on raw bytes (256 values). Eliminates all encoding edge-cases entirely.</td><td>Active research</td></tr>
<tr><td>Neural Tokenization</td><td>Token boundaries learned via RL or gradient descent β€” replaces frequency heuristics.</td><td>2026 papers, promising</td></tr>
<tr><td>Hybrid Architectures</td><td>Byte-level encoder + token-level transformer connected via cross-attention.</td><td>Being explored</td></tr>
<tr><td>Adaptive Downsampling</td><td>Dynamic sequence compression that varies with local text complexity.</td><td>Research ongoing</td></tr>
<tr><td>Edge Optimization</td><td>Compressed learned codebooks for mobile and low-resource deployment.</td><td>Critical open gap</td></tr>
</tbody>
</table>
</div>
<h3>Open Challenges</h3>
<div class="problem-box">
<strong>Sequence length:</strong> Characters are 4Γ— longer than subwords; attention complexity is quadratic. Downsampling only partially compensates.<br><br>
<strong>Text generation:</strong> Tokenization-free models excel at encoding (BERT-style) but character-level autoregressive generation (GPT-style) remains significantly harder.<br><br>
<strong>Rare entity memorization:</strong> Character models sometimes struggle to retain rare proper nouns and specific facts.
</div>
<h3>The Bigger Shift: The Entire Preprocessing Pipeline Eliminated</h3>
<p>Tokenization was only the last step in a longer pipeline that deep learning has now made obsolete. Every cleaning step once considered mandatory has been shown to hurt model performance β€” because each one encoded a human assumption the model is better off learning itself.</p>
<div class="pipe-label">Classical NLP β€” every step was mandatory</div>
<div class="pipeline">
<span class="ps ps-old">Lowercase</span><span class="pa">β†’</span>
<span class="ps ps-old">Remove punctuation</span><span class="pa">β†’</span>
<span class="ps ps-old">Remove stopwords</span><span class="pa">β†’</span>
<span class="ps ps-old">Stem / Lemmatize</span><span class="pa">β†’</span>
<span class="ps ps-old">Tokenize</span><span class="pa">β†’</span>
<span class="ps ps-old">Lexicon lookup</span><span class="pa">β†’</span>
<span class="ps ps-keep">Model</span>
</div>
<div class="pipe-label">Modern deep learning β€” almost nothing required</div>
<div class="pipeline">
<span class="ps ps-keep">Raw Text</span><span class="pa">β†’</span>
<span class="ps ps-keep">[Optional: Unicode normalization]</span><span class="pa">β†’</span>
<span class="ps ps-keep">Model</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Old Step</th><th>Why It Hurt</th><th>What Replaced It</th></tr></thead>
<tbody>
<tr><td>Lowercasing</td><td>Erased "Apple" (company) vs "apple" (fruit)</td><td>Model learns case sensitivity as a feature</td></tr>
<tr><td>Stopword removal</td><td>Deleted "not" in "not good" β€” flipped sentiment</td><td>Attention learns importance weighting dynamically</td></tr>
<tr><td>Stemming</td><td>run / running / ran collapsed β†’ tense information lost</td><td>Subwords preserve morphology and conjugation</td></tr>
<tr><td>Punctuation stripping</td><td>"!" "?" "." carry sentiment, emphasis, and syntax</td><td>Model treats punctuation as semantic signals</td></tr>
<tr><td>Lexicon lookup</td><td>OOV = silent failure</td><td>Subwords / bytes = unbounded effective vocabulary</td></tr>
</tbody>
</table>
</div>
<div class="insight-box">
<strong>The core insight:</strong> Every preprocessing step encoded a <em>human bias</em>. Neural networks trained on raw, unmodified text consistently outperform those trained on carefully cleaned text β€” because they learn better, unbiased representations directly from signal.
</div>
<h3>The Same Inversion Across All of AI</h3>
<p>This is not unique to NLP. Every field in deep learning has undergone the same transition β€” away from hand-engineered intermediate representations and toward learning from raw signals.</p>
<div class="cross-grid">
<div class="cross-card">
<div class="cross-field">Computer Vision</div>
<div class="c-from">SIFT / HOG features</div>
<div class="c-mid">↓</div>
<div class="c-mid">raw pixels</div>
<div class="c-mid">↓</div>
<div class="c-to">CNNs learn features</div>
</div>
<div class="cross-card">
<div class="cross-field">Speech</div>
<div class="c-from">Phoneme extraction</div>
<div class="c-mid">↓</div>
<div class="c-mid">raw waveforms</div>
<div class="c-mid">↓</div>
<div class="c-to">wav2vec learns repr.</div>
</div>
<div class="cross-card">
<div class="cross-field">NLP</div>
<div class="c-from">POS tags / parse trees</div>
<div class="c-mid">↓</div>
<div class="c-mid">raw text</div>
<div class="c-mid">↓</div>
<div class="c-to">Transformers learn all</div>
</div>
</div>
</section>
<!-- ════════════════════════════════════════
06 β€” LIVE DEMO
════════════════════════════════════════ -->
<section class="section" id="sec-demo">
<div class="sec-header">
<span class="sec-num">06</span>
<span class="sec-title">Live Tokenization Demo</span>
</div>
<p>Type any word or phrase and switch between strategies to see how the same input is tokenized differently across eras.</p>
<div class="demo-area">
<label>Input Text</label>
<input class="demo-input" id="demoInput" type="text" value="unhappiness" oninput="runDemo()">
<div class="demo-modes">
<button class="mode-btn active" onclick="setMode('word',this)">Word-Based</button>
<button class="mode-btn" onclick="setMode('char',this)">Character-Level</button>
<button class="mode-btn" onclick="setMode('bpe',this)">Subword (BPE)</button>
<button class="mode-btn" onclick="setMode('wp',this)">WordPiece</button>
</div>
<div class="demo-result" id="demoResult"></div>
<div class="demo-stats" id="demoStats"></div>
</div>
<div id="demoExplain"></div>
</section>
<!-- ════════════════════════════════════════
07 β€” REFERENCES
════════════════════════════════════════ -->
<section class="section" id="sec-refs">
<div class="sec-header">
<span class="sec-num">07</span>
<span class="sec-title">References</span>
</div>
<ul class="ref-list">
<li>
<span class="ref-num">01</span>
<div class="ref-content">Sennrich, R., Haddow, B., &amp; Birch, A. (2016). <strong>Neural Machine Translation of Rare Words with Subword Units.</strong> ACL. <em>β€” Introduced BPE to NLP; the foundational subword tokenization paper.</em></div>
</li>
<li>
<span class="ref-num">02</span>
<div class="ref-content">Schuster, M., &amp; Nakajima, K. (2012). <strong>Japanese and Korean Voice Search.</strong> ICASSP. <em>β€” Original WordPiece research, later adopted for BERT.</em></div>
</li>
<li>
<span class="ref-num">03</span>
<div class="ref-content">Vaswani, A., et al. (2017). <strong>Attention Is All You Need.</strong> NeurIPS. <em>β€” The Transformer architecture that made large-scale subword models possible.</em></div>
</li>
<li>
<span class="ref-num">04</span>
<div class="ref-content">Devlin, J., et al. (2019). <strong>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.</strong> NAACL. <em>β€” Popularized WordPiece tokenization; defined modern NLP benchmarks.</em></div>
</li>
<li>
<span class="ref-num">05</span>
<div class="ref-content">Kudo, T. &amp; Richardson, J. (2018). <strong>SentencePiece: A simple and language-independent subword tokenizer and detokenizer.</strong> EMNLP. <em>β€” Language-agnostic tokenizer used by T5, ALBERT, XLNet.</em></div>
</li>
<li>
<span class="ref-num">06</span>
<div class="ref-content">Kudo, T. (2018). <strong>Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.</strong> ACL. <em>β€” Introduces Unigram language model tokenization and BPE-dropout.</em></div>
</li>
<li>
<span class="ref-num">07</span>
<div class="ref-content">Clark, J.H., et al. (2022). <strong>CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation.</strong> TACL. <em>β€” First tokenization-free pre-trained model; operates on raw Unicode characters.</em></div>
</li>
<li>
<span class="ref-num">08</span>
<div class="ref-content">Xue, L., et al. (2022). <strong>ByT5: Towards a token-free future with pre-trained byte-to-byte models.</strong> TACL. <em>β€” Extends T5 to the byte level; competitive quality with no tokenizer.</em></div>
</li>
</ul>
</section>
<script>
function show(id, el) {
document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
document.getElementById('sec-' + id).classList.add('active');
el.classList.add('active');
window.scrollTo({ top: document.querySelector('.nav').offsetTop - 8, behavior: 'smooth' });
}
let currentMode = 'word';
function setMode(m, btn) {
currentMode = m;
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
runDemo();
}
const subs = {
'unhappiness': [['un','t1'],['happi','t2'],['ness','t3']],
'tokenization': [['token','t1'],['ization','t2']],
'tokenizing': [['token','t1'],['iz','t2'],['ing','t3']],
'running': [['run','t1'],['ning','t2']],
'unbelievable': [['un','t1'],['believ','t2'],['able','t3']],
'preprocessing': [['pre','t1'],['process','t2'],['ing','t3']],
'transformer': [['transform','t1'],['er','t2']],
'bitcoin': [['bit','t1'],['coin','t2']],
'unfriendable': [['un','t1'],['friend','t2'],['able','t3']],
'embeddings': [['embed','t1'],['ding','t2'],['s','t3']],
'multilingual': [['multi','t1'],['lingual','t2']],
'subword': [['sub','t1'],['word','t2']],
'morphological': [['morph','t1'],['olog','t2'],['ical','t3']],
};
const wps = {
'unhappiness': [['un','t1'],['##happi','t2'],['##ness','t3']],
'unbelievable': [['un','t1'],['##believ','t2'],['##able','t3']],
'tokenization': [['token','t1'],['##ization','t2']],
'running': [['run','t1'],['##ning','t2']],
'transformer': [['transform','t1'],['##er','t2']],
};
const known = new Set('the a an is are was were be been have has had do does did will would could should may might can need hello world cat dog run go see say know think come take make good new first last long great little own right big high few same able model text word language machine data learn deep neural network training input output'.split(' '));
const colors = ['t1','t2','t3','t4'];
const tok = (t,c) => `<span class="tok ${c}">${t}</span>`;
function splitGeneric(w) {
const pfx = ['un','re','pre','dis','over','under','sub','mis','non','in','im','ir'];
const sfx = ['ing','tion','ness','ment','able','ible','ful','less','ly','er','est','ed','s'];
let r = w, parts = [];
for (const p of pfx) { if (r.startsWith(p) && r.length > p.length+2) { parts.push(p); r=r.slice(p.length); break; } }
for (const s of sfx) { if (r.endsWith(s) && r.length > s.length+2) { parts.push(r.slice(0,-s.length)); parts.push(s); r=''; break; } }
return (parts.length && !r) ? parts : [w];
}
function runDemo() {
const raw = document.getElementById('demoInput').value || 'hello';
const words = raw.trim().split(/\s+/).filter(Boolean);
let html = '<div class="token-row">', count = 0;
if (currentMode === 'word') {
words.forEach(w => {
const lw = w.toLowerCase().replace(/[^a-z]/g,'');
if (known.has(lw) || lw.length < 4) { html += tok(w,'t2'); }
else { html += tok('<UNK>','unk') + `<span style="font-size:11px;color:var(--muted);margin-left:6px;font-family:'IBM Plex Mono',monospace">("${w}")</span>`; }
count++;
});
document.getElementById('demoExplain').innerHTML = `<div class="problem-box"><strong>Word-Based:</strong> Every word needs a dictionary entry. Unknown or new words become &lt;UNK&gt; β€” all meaning permanently lost. Lexicons must cover every word form in every language, which is impossible.</div>`;
} else if (currentMode === 'char') {
raw.split('').forEach(c => {
if (c === ' ') html += '<span style="margin:0 5px;color:var(--muted);font-family:monospace;font-size:11px">Β·</span>';
else { html += tok(c,'tchar'); count++; }
});
document.getElementById('demoExplain').innerHTML = `<div class="problem-box"><strong>Character-Level:</strong> Solves OOV completely (only 26–256 token types needed) but produces sequences 4Γ— longer and carries no semantic meaning per token. The attention mechanism cannot efficiently recover word-level context.</div>`;
} else if (currentMode === 'bpe') {
words.forEach((w, wi) => {
if (wi > 0) html += '<span style="color:var(--muted);padding:0 5px;font-family:monospace">β”‚</span>';
const key = w.toLowerCase().replace(/[^a-z]/g,'');
const parts = subs[key] || splitGeneric(key).map((p,i) => [p, colors[i%4]]);
parts.forEach(([t,c]) => { html += tok(t,c); count++; });
});
document.getElementById('demoExplain').innerHTML = `<div class="insight-box"><strong>Subword (BPE):</strong> Words decompose at morpheme boundaries. Frequent words become single tokens; rare words split into known subword parts. No input is ever truly unknown β€” any text tokenizes gracefully from learned merges.</div>`;
} else {
words.forEach((w, wi) => {
if (wi > 0) html += '<span style="color:var(--muted);padding:0 5px;font-family:monospace">β”‚</span>';
const key = w.toLowerCase().replace(/[^a-z]/g,'');
const parts = wps[key] || (subs[key] ? subs[key].map(([t,c],i)=>[i>0?'##'+t:t,c]) : splitGeneric(key).map((p,i)=>[i>0?'##'+p:p,colors[i%4]]));
parts.forEach(([t,c]) => { html += tok(t,c); count++; });
});
document.getElementById('demoExplain').innerHTML = `<div class="insight-box"><strong>WordPiece (BERT):</strong> The <code>##</code> prefix explicitly marks continuation subwords, signalling that this piece belongs to the same word as the previous token. Merges are chosen to maximize training corpus likelihood rather than raw frequency.</div>`;
}
html += '</div>';
document.getElementById('demoResult').innerHTML = html;
document.getElementById('demoStats').textContent = `β†’ ${count} token${count!==1?'s':''} Β· input: ${raw.length} characters`;
}
runDemo();
</script>
</body>
</html>