Skip to content
AI360XpertBeta
Playgrounds

Generative AI

Tokenization (BPE)

Repeated adjacent symbols form larger tokens through counted, ordered merges, without understanding meaning.

Guided steps 1 / 2

Stage 1 of 2: Characters

One whole-string toy BPE trainer. Starting symbols are Unicode code points, not bytes or grapheme clusters. No normalisation, lowercasing, pre-tokenisation, special tokens or unknown-token fallback. Source offsets are UTF-16 code units, half-open [start,end).

Original text · code-point positions

Current text has 8 tokens. Next pair "a" + "a". Completed merges 0. Selected char-0.

Tiles wrap in measured space; long JSON labels shorten and excess tiles are omitted. The selected token stays in the tile window. Native selection and inspection retain every complete value. Tile width is display only.

Active computation: 0 completed training merges, 8 current tokens. Count overlapping adjacent pairs; require count at least two. Highest count wins, ties use earliest current token index. Replace nonoverlapping occurrences left-to-right, then recount. This stopping rule belongs to this lab. No model is trained and no pretrained vocabulary encodes a separate text.

Selected occurrence char-0; vocabulary ID 0; token "a"; original UTF-16 [0,1); code points [0,1). Original slice = "a".

Decoded text (concatenated current strings): "aabbaabb". Original preserved: true.

  • Token

Token Count8Token Count: 8

Is one visible character always one starting symbol?

This lab starts from Unicode code points. Emoji sequences and combining marks may contain several; UTF-16 offsets count different units.

Starting symbol

One string-iterator element: a code point, or a retained lone surrogate. Not a byte or grapheme cluster.

Check this stage

Check your understanding

Train a toy BPE tokenizer on your text and inspect pair counts, source spans and vocabulary indices.

What this lab computes

This is a toy BPE trainer on one whole string. It begins with Unicode code points, counts adjacent pairs and learns ordered replacements. It does not apply a production tokenizer's pretrained vocabulary, encode a separate input with learned ranks, or train a language model.

In Characters, edit Text to tokenize and select a source position. In Byte Pair Encoding, predict the next pair, then press Step for one full replacement pass. Play repeats real passes; Pause stops them; Replay rewinds the same corpus. Recorded step selects a deterministic training prefix. Reset in transport rewinds the current corpus; Reset controls restores the default corpus and selection, returns guided and clears recovery and prediction. Returning to Characters retains the effective prefix and settings.

Count, choose, replace, recount

For a current sequence of n tokens, the count of pair (a,b) is

C(a,b)=∑i=0n−21[(ti,ti+1)=(a,b)].C(a,b)=\sum_{i=0}^{n-2}\mathbf{1}[(t_i,t_{i+1})=(a,b)].

Only pairs with count at least two qualify here. Choose the highest count; at a tie, choose the pair whose first occurrence starts at the earliest current token index. Replace every nonoverlapping match left-to-right, then recount the new sequence. A requested prefix can stop early; otherwise this toy stops when no pair repeats. Other BPE trainers have different frequency thresholds, merge budgets and vocabulary targets.

Try aabbaabb. Initially (a,a), (a,b) and (b,b) each occur twice; (b,a) occurs once. The first pair wins the tie:

  1. Merge a+a: [aa,b,b,aa,b,b].
  2. Merge aa+b: [aab,b,aab,b].
  3. Merge aab+b: [aabb,aabb].

The remaining pair occurs once, so no further pass qualifies. The first-occurrence alphabet is a=0, b=1; new strings aa, aab and aabb receive vocabulary indices 2, 3 and 4. Both final tokens have vocabulary ID 4 but distinct occurrence identities char-0 and char-4. These indices are lookup identities, not semantic scores.

Now try aaaa: the overlapping pair (a,a) counts three positions, but the pass makes only two replacements, yielding [aa,aa]. Frequency and replacement count answer different questions. The live pair table exposes counts and first indices; select a row to inspect its first source occurrence. The drawer retains each completed intermediate sequence, its counts and next choice, plus the vocabulary including entries absent from the current sequence. A merged text already in the vocabulary reuses its index.

Code points, offsets and original text

The starting operation is JavaScript string iteration. A valid surrogate pair such as the rocket emoji is one code point and two UTF-16 code units. An e followed by a combining accent is two code points even when it looks like one character. A joined emoji sequence can contain several code points. Grapheme clusters, code points, code units and bytes are different units. Lone surrogates remain individual iterator elements in the pure computation and JSON link.

Offsets use UTF-16 code units, zero-based half-open [start,end): start is included and end is excluded. The separate code-point interval counts iterator elements. Merging retains the leftmost source occurrence identity and extends its span; selecting an original position follows the containing current token through later merges and history changes. Inspect the exact original slice alongside token text and vocabulary ID.

There is no normalisation or case folding. Normalised text is the identity copy of original text. Accents, case, punctuation, leading/trailing/repeated spaces, tabs and newlines are ordinary symbols; pairs can merge across word boundaries. No word splitting, special tokens, end-of-word markers or byte conversion occurs. A browser textarea follows native line-ending handling; the pure API and JSON link retain supplied code units, including carriage returns. JSON labels expose invisible characters rather than changing the computation.

Vocabulary, coverage and decoding

The lab constructs its base alphabet from the exact training string, in first-occurrence order. It has no fixed unknown entry or fallback path: every supplied symbol enters that alphabet. This says nothing about encoding unseen text with a fixed vocabulary. There is no independent encoding mode here. In a ranked encoder, learned merge order determines which available rule applies; it does not retrain by recounting the new input's pair frequencies.

Decoded text here concatenates current token strings in order and reconstructs the supplied original exactly. A production pipeline that normalises text, inserts/skips special tokens or uses bytes needs its own decoding rules; reversibility cannot be inferred merely from the name BPE. A complete byte alphabet can cover byte values, provided the actual encoding and fallback preserve them. This lab is code-point based and has no such byte mode.

A token is not universally a word or a fixed number of characters. Different vocabularies, normalisation, pre-tokenisation, budgets and algorithms can yield different segments. Fewer tokens is not proof of better representations, prediction, accuracy or generalisation. These merges count symbols, without evidence of understanding their meaning. Digit fragmentation alone does not evaluate arithmetic; language imbalance alone does not establish a speed or quality result. No model is evaluated here.

Limits, failure and recovery

Try xyz, empty input or a singleton: no repeated pair means no merge. Repeated spaces can merge, so whitespace-only is not automatically empty. Load no-repeat text saves the preceding complete experiment before loading xyz. Restore experiment restores text, prefix, selection, vocabulary, guided stage, sandbox, playback speed and prediction after further edits, paused. The tie challenge retains aabbccaabbcc, whose five highest pairs each count two and whose first winner is (a,a).

The editor accepts at most 256 code points. Oversized edits are rejected with a message and retain the previous experiment; no text silently truncates. Invalid or oversized shared corpus JSON falls back to default text with feedback. The pure API supports longer strings; nonfinite merge requests resolve to zero, finite requests floor and clamp at zero, and exhausted sequences stop before the request. Numeric URL controls clamp to their declared integer range, then resolve against the actual corpus and history.

Text edits restart training and selection. Text, selection, cursor, stage and sandbox changes invalidate prediction; opening Help/inspection or changing presentation/motion does not. Stage/mode/text/history/restoration/reset changes pause playback and invalidate pending callbacks. Share includes the entire corpus as JSON, resolved source position, completed prefix and displayed stage, opening guided and paused. Guesses and recovery remain in memory. Reset controls and URL navigation clear them; local progress records exploration rather than assessment. No random draws or seed control exist in this experiment.

Tiles wrap within measured space. Long JSON labels shorten and excess tiles are omitted; the selected token stays in the displayed window. No label shrinks to fit and no text is truncated in computation. Native selectors and the drawer retain every exact token, span and intermediate count. Tile geometry and glyphs do not alter token IDs, frequencies or decoded text.

Sources and next steps

Sennrich, Haddow and Birch describe learning subword merges with word boundaries. The Hugging Face pipeline separates normalisation, pre-tokenisation and model stages; tiktoken illustrates a production ranked byte vocabulary. Their configurable features are context, not lab capabilities. Unicode segmentation distinguishes grapheme clusters, while the ECMAScript string iterator specifies the starting iteration used here.

For a fair comparison, hold exact corpus/input, normalisation, preprocessing, vocabulary or vocabulary budget, merge budget/ranks, special tokens, fallback and evaluation fixed except for the declared change. This lab compares prefixes of the same corpus and algorithm; wrapping is only a presentation change. Continue with the tokenization concept for context beyond this toy.

Stage recap

  1. Characters

    This lab starts from Unicode code points. Emoji sequences and combining marks may contain several; UTF-16 offsets count different units.

  2. Byte Pair Encoding

    Train on this exact whole string: count pairs, choose the highest repeated count, break ties leftmost, merge nonoverlapping matches and recount.

Reference

Token
An algorithm-dependent text unit. This lab records its text, occurrence identity, source span and separate vocabulary index.
BPE
A pair-merging method. Here it trains on Unicode code points in one whole string, including whitespace and punctuation.
Merge rule
The highest-count pair occurring at least twice. Replace nonoverlapping matches left-to-right and recount.
Tie-break
Equal counts choose the pair whose first occurrence starts at the earliest current token index.
Stopping condition
This toy stops below pair count two or at the requested completed prefix. Other trainers may use different budgets or thresholds.

Break it on purpose

A text with no repeated adjacent pair, such as xyz, cannot merge under this toy trainer’s minimum-count-two policy.