GOAT EngineerPreparing your learning space…

AI Engineering · Concept Library · Free article

LLM Tokenization

A model never sees your words. It sees tokens: short, common chunks of characters from a fixed vocabulary, about three quarters of a word each in English. That is what you are billed for, what the context limit counts, and why a model can write working code and still miscount the letters in a word.

Before a model reads a single character of your prompt, your text is sliced into tokens, short common chunks of characters from a fixed vocabulary, and that is what the model reads, what you are billed for, and what its memory limit is measured in. In English a token is roughly ¾ of a word, and for code, other languages and long numbers it is a good deal worse. Learn to count in the model’s units and a surprising amount of “why is this slow, expensive, getting cut off, or bad at spelling?” answers itself.

You wire up your first model call, send it a short paragraph, and the usage line reads 1,300 tokens. You sent maybe 200 words, and the rule of thumb you half-remember says that should be nearer 260. Where did the rest come from, and why is that the number on the bill instead of words, or characters, or requests?

Two answers, and you need both. The model never saw your paragraph, it saw a list of tokens. And it was never sent only your paragraph: your system prompt, the conversation so far and a few tokens of per-message overhead were all billed with it. That one substitution, words in, tokens out, is the difference between guessing at cost, latency, and context limits and actually being able to predict them.

What is a token in an LLM?

A token is a chunk of characters from a fixed vocabulary, not a word: roughly four characters or three quarters of a word in English, and often a whole word, a word fragment, a punctuation mark or the space in front of a word. Before a model reads anything, a step called tokenization slices your text into pieces from a fixed vocabulary the model was trained with. Each piece is a token, and each token is really just an integer ID, an index into that vocabulary. The vocabulary holds the most common chunks of text, whole short words, word-fragments, single characters, punctuation, even the space in front of a word.

So the split does not follow spaces the way you would expect. Common words are usually one token; rarer or longer ones break into several; symbols and emoji fragment hard. Type into the playground and watch it happen: try the presets, then break it with your own text.

The interactive version of this example is available when JavaScript loads.

Why chop text into subwords at all?

Why not just use whole words as tokens, or fall back to single characters? Each extreme breaks:

The vocabulary trade-off tokenizers are threading
ApproachThe problem
One token per wordThe vocabulary would be enormous and still miss every typo, new product name, and rare word: each arriving as a useless “unknown.”
One token per characterTiny vocabulary, but sequences become punishingly long and each token carries almost no meaning: expensive and weak.
Subword chunks (the winner)Common words stay whole; rare words decompose into known fragments. Small-ish vocabulary, short-ish sequences, nothing truly unknown.

How does byte-pair encoding build its vocabulary?

The most common recipe is byte-pair encoding (BPE), and the way it learns its vocabulary is worth seeing once, because it explains why the split lands where it does. Training starts from the smallest pieces, individual characters (really individual bytes), and then does one thing over and over: scan the whole training corpus, find the most frequent adjacent pair of tokens, and fuse that pair into a single new token. Do that tens of thousands of times and frequent sequences (“ing”, “ the”, “refund”) each earn their own token, while rare ones stay split into pieces. You stop when you hit a target vocabulary size.

Watch it happen on a tiny corpus: each click is one merge:

The interactive version of this example is available when JavaScript loads.

Two details matter in practice. First, using a trained tokenizer is not the same as training it: to encode your text, the tokenizer applies the merges it already learned in the order it learned them (earliest, most-frequent merges first), not by re-counting anything, which is what makes tokenization fast and perfectly deterministic. Second, most tokenizers you will meet work at the byte level, or fall back to bytes, so the base vocabulary includes all 256 possible byte values. For those there is no such thing as an unknown character: any emoji, accent, or garbled input still decomposes into bytes the model knows, so you never get an “unknown token”, just more tokens. Older SentencePiece models without that byte fallback do still have one. T5 is the example you are most likely to hit: feed it Japanese text or an emoji and it emits a literal <unk>, losing the characters rather than spending more tokens on them.

Which tokenizers do real models use?

BPE is the most common recipe, but it is not the only one, and the differences show up when you move between model families. There are really three vocabulary-building algorithms in the wild:

The three tokenizer algorithms (names reshuffle: reason about the family)
AlgorithmHow it builds the vocabularyWhere you meet it
BPE (byte-pair encoding)Merge the most frequent adjacent pair, over and over, by raw frequency. Deterministic.GPT models (via tiktoken), Llama 3, Mistral: most recent frontier models.
WordPieceMerge the pair that most improves the training likelihood: favouring pairs that co-occur more than chance, not just the most frequent.BERT and its descendants (the encoder models behind a lot of search and classification).
UnigramStart from a large vocabulary and prune the least useful tokens away; probabilistic, so it can segment one word more than one way.T5, ALBERT, XLNet, mT5.

One name that causes endless confusion: SentencePiece is not a fourth algorithm. It is a popular library that runs BPE or Unigram over the raw character stream, encoding the space itself as a visible marker (▁) instead of relying on whitespace. That is exactly what makes it a good fit for languages like Chinese, Japanese, or Thai that do not put spaces between words. So when someone says “Llama uses SentencePiece,” they mean the library; the algorithm underneath is BPE. (Newer Llama generations moved to a tiktoken-style byte-level BPE: another reminder that the specific tooling churns even when the ideas don't.)

Why count tokens instead of words?

Because three of the numbers you will spend your career tuning are denominated in tokens and none of them is denominated in words: what you pay, how much the model can hold in view, and how long the reply takes. Tokens are not a billing quirk:

The three things tokens secretly control

  1. Cost. You pay per token, in both directions: input (your prompt) and output (the reply) are billed separately, and output is usually pricier. A prompt you casually pad with a giant example is a bill you pay on every single call.
  2. Context limit. A model can only hold so many tokens in view at once, its context window. System prompt, conversation so far, retrieved documents, and the reply it is about to write all count against it. Overflow, and the request is refused: both major APIs answer a too-long prompt with a 400 rather than quietly dropping anything. The trimming you have seen in a chat app is that product deciding what to leave behind, and in your own service it is your job. That is the real mechanism behind “it forgot what I told it.”
  3. Latency. The reply is generated one token at a time, in sequence, so more output tokens means a longer wait, close to linearly. “Be concise” is a latency setting, not a style note.

Why do code and other languages cost more tokens?

The ¾-word rule is English prose. Step outside it and the token count, and the bill, and the shrinking effective context, climbs fast. The same message, written in a different script or as structured data, can cost several times more:

The interactive version of this example is available when JavaScript loads.

The same “meaning” can cost very different token counts
ContentRoughly vs English proseWhy
Plain English1×What the tokenizer was optimized for.
Source code~1 to 2×A keyword like return is often one token, so dense code can be efficient, but indentation, punctuation, and long identifiers like handleRefundRequest fragment, and whitespace is real text you pay for.
JSON output~1.5 to 3× the payloadEvery brace, quote, and repeated key is billed output. Structured-output and tool modes buy you schema conformance, not a smaller bill: the schema is billed as input, tool use adds a few hundred input tokens of its own, and the braces are still billed output. Trim repeated keys and boilerplate instead.
Many non-English languages~1.3 to 3×, and far worse in the tailThe vocabulary has fewer dedicated chunks for them, so words shatter into small fragments, and non-Latin scripts fare worst. The multiplier depends heavily on the tokenizer generation. Measured on FLORES-200, where every language expresses the same 997 sentences, one audit puts Hindi at 4.08× English on the 100k-vocabulary cl100k_base and 1.34× on the 200k o200k_base, with GPT-2 at 6.34×. Languages outside the top hundred are still several times more expensive, and a few got worse as vocabularies grew.

The strange failures tokenization explains

A model that can write working code will confidently miscount the letters in a word or fumble a two-number sum. The cause is primarily not “bad at reasoning”. It is that the model never sees letters or digits directly. It sees tokens, and the characters are welded inside them.

The interactive version of this example is available when JavaScript loads.

The family of boundary failures

  • Counting or finding letters: the letters are hidden inside a couple of token blocks, so the model has to reconstruct spelling it was never handed.
  • Reversing a string or spotting palindromes: character order is invisible inside a token.
  • Multi-digit arithmetic: a number can be chopped at boundaries that ignore place value, so carrying across the split is guesswork. Comma-formatting numbers, or asking for digit-by-digit work, measurably helps.
  • Rhyming and syllable games: the phonetic structure lives below the token floor.

Two tokens most engineers never think about

Special tokens are the control characters of a conversation: markers like begin-of-sequence, end-of-sequence, and the role delimiters that separate system, user, and assistant turns. The model stops generating when it predicts the end-of-sequence token. This is a genuine security surface: if untrusted user input can smuggle in a raw control token, an end-of-sequence marker, an “assistant” delimiter, it can prematurely end generation or impersonate a role, a token-level cousin of injection attacks (sometimes called special-token injection). The defence is structural: assemble messages with the provider’s chat template or messages API, which encodes user content as ordinary text, and never hand-concatenate raw role markers or let user strings inject special tokens.

Glitch tokens are the eerie ones: a handful of tokens that ended up in the vocabulary but were almost absent from the model’s training data, so their internal representation is essentially untrained. Prompt a model with one and it can behave erratically: evading, misspelling, or emitting nonsense. The first famous batch was surfaced in early 2023 by two researchers probing an early tokenizer, who found strings like SolidGoldMagikarp (a scraped username) that made the model misbehave. They are rare in any one prompt, and they are not history: automated detection work in 2024 turned them up across most production tokenizers. The seams are still there, because the vocabulary is trained separately from the model.

How do you budget and measure tokens in production?

Knowing what a token is only pays off when you count them where it counts. A production request is a packing problem inside a fixed budget: system prompt + few-shot examples + retrieved context + conversation history + user message + reserved room for the reply, all in tokens. The single most important discipline is the least obvious: reserve the reply’s tokens first, then pack context into what is left, so context is what gives rather than the reply. On a thinking model reserve for the thinking and the answer: those share one budget, so a reservation sized for the answer alone can be spent entirely on reasoning you never see. Dial the parts and feel where it bites:

The interactive version of this example is available when JavaScript loads.

The token-budgeting checklist

  • Count with the target model’s tokenizer, at request-build time, not a generic estimate. Every model family ships its own vocabulary, so the identical prompt can be 1,300 tokens on one model and 1,500 on another; counts do not transfer between vendors.
  • Reserve output tokens up front. Decide the max reply length and subtract it from the window before you pack context, so a long answer never gets truncated mid-sentence.
  • Alert before you overflow. Log a token histogram per request and warn as you approach the window, rather than discovering it as a hard API error in production.
  • If you cut documents into token-sized pieces, re-cut them after a model swap. Those piece sizes were counted with one model’s tokenizer; a different model tokenizes the same text differently, so the pieces come out the wrong size and you may have to slice everything again. (You’ll do exactly this kind of slicing later, when you feed the model your own documents.)

How do you count tokens in code?

Every guardrail above rests on one primitive: an honest token count for the model you are actually calling. Where that count comes from differs by provider, so the practical move is to wrap it once and route every prompt through it.

A countTokens helper, and where each count comes from

  • OpenAI: run the tiktoken library locally and offline: pick the model’s encoding with encoding_for_model("gpt-4o"), then len(enc.encode(text)). Exact, no network call.
  • Anthropic (Claude). There is no local tokenizer for current Claude models, so call the POST /v1/messages/count_tokens endpoint to get the exact count before you send. Do not reuse an OpenAI count. It will be wrong.
  • Open-weight models: Hugging Face AutoTokenizer.from_pretrained(name) loads the model’s own tokenizer, then len(tok.encode(text)): the same vocabulary the model was trained with.
  • Wrap it once. Put a single countTokens(text, model) behind your call so every prompt is measured with the right tokenizer at build time. It is the cheapest guardrail you will ever write against surprise bills and truncation.

Tokenization myths to drop

Common misconceptions

  • “A token is a word.” It is a subword chunk: a lone space, a suffix like tion, or a full emoji can each be one token, and one long word can be several.
  • “Text is split on spaces.” Byte-level BPE has no notion of words; the space is usually part of the following token, so refund ≠ refund.
  • “Token counts are the same across models.” Every family has its own vocabulary: GPT-2 ≠ the GPT-4-era tokenizer ≠ a Llama or Claude tokenizer. Estimate with the model you actually call.
  • “Just divide characters by four.” English-only. Code, JSON, numbers, emoji and non-Latin scripts run roughly 1.3 to 3× that, and rarer scripts much more. Measure, don’t assume.
  • “Structured JSON output is free.” Its braces, quotes, and keys are billed output tokens; at volume that overhead is real money.
  • “I can just swap in a better tokenizer.” You can’t: the vocabulary is baked into the model’s weights. A new tokenizer means a new (re-trained) model.

Three habits the rest of the page has not already given you

What reasoning in tokens tells you to do

  • Offload exact-character work to tools. Counting, reversing and arithmetic belong in a len() call or a calculator tool, not in the prompt. The failure is baked into tokenization, so no amount of prompting fixes it.
  • Budget for your users’ real languages. Measure per-language inflation on your actual traffic and price and size context for it, so non-English users are not quietly paying more for a smaller window.
  • Watch what structure costs you. Function-calling and structured-output modes buy schema conformance, not a smaller bill: the schema is billed as input, tool use adds a few hundred input tokens of its own, and braces and repeated keys are billed output. Trim the boilerplate instead.

Interview cheat-sheet: intern to principal

Roughly how many tokens is a 1,000-word English document?
About 1,300 (~1.3 tokens/word). Enough to matter: stuffing a 1,000-word example into every call adds real cost and eats the context window, and in another language the same document could be 2 to 5× that.
Why does subword tokenization exist instead of word- or character-level?
Word-level needs a huge vocabulary and still can’t handle unseen words; character-level makes sequences too long and each token nearly meaningless. Subword (BPE) keeps common words whole and splits rare ones into known fragments: small vocabulary, short sequences, nothing truly unknown (byte-level means no character is ever ‘unknown’).
How does BPE actually build its vocabulary, and how is encoding different from training?
Training starts from characters/bytes and repeatedly merges the most frequent adjacent pair into a new token until it hits a target vocab size, so frequent fragments earn their own token. Encoding your text with the trained tokenizer is different: it applies the already-learned merges in the order they were learned, no re-counting, which makes it fast and fully deterministic.
BPE vs WordPiece vs Unigram, and where does SentencePiece fit?
Three vocabulary-building algorithms: BPE merges by raw frequency (GPT, Llama, Mistral); WordPiece merges by training likelihood, favouring pairs that co-occur more than chance (BERT); Unigram starts big and prunes, and is probabilistic (T5, ALBERT, mT5). SentencePiece isn’t a fourth algorithm. It’s a library that runs BPE or Unigram over the raw stream (encoding the space as ▁), which is why it suits languages without spaces.
Why is a model bad at counting the letters in a word or doing multi-digit math?
Primarily because it never sees letters or digits directly. They’re welded inside tokens, so letter identity, character order, and place value are hidden. It’s compounded by the model having no built-in counting or arithmetic procedure; it pattern-matches these instead of computing them. Fixes: format with separators, spell out first, or hand it a tool.
What are glitch tokens and special tokens, and why should an engineer care?
Glitch tokens are strings that made it into the vocabulary but were nearly absent from the model’s training data, so their embeddings are untrained and prompting them causes erratic behavior: a reminder the tokenizer is trained separately from the model. Special tokens are control markers (BOS/EOS, role delimiters); the risk is that untrusted user text carrying raw special tokens can end generation early or spoof a role, so always assemble prompts with the provider’s chat template rather than concatenating role markers.
The model ‘forgets’ the start of a long chat. What’s actually happening?
The conversation grew past the context window, a fixed token budget. The API refuses a request that does not fit, so something upstream, the chat product or your own code, is dropping or summarizing the oldest turns to keep it under the limit. It’s not a memory bug, and the fix is to choose what gets trimmed rather than to scold the model.
Why do token counts differ between providers, and why does it matter?
Each model family trains its own tokenizer/vocabulary, so the same text tokenizes differently. It matters because cost estimates, context-fit, and token-based document chunks are all tied to a specific tokenizer: swap models and your budgets and chunks can shift. And you can’t just swap tokenizers: the vocabulary is baked into the weights.
How would you count tokens correctly in production?
With the target model’s own tokenizer, at request-build time, behind a single helper. Use tiktoken locally for OpenAI models, Anthropic’s count-tokens API endpoint for Claude (there’s no local Claude tokenizer), and Hugging Face AutoTokenizer for open-weight models. Never reuse one provider’s count for another, and never ship a characters-÷-4 estimate for anything load-bearing.
How would you keep a global product’s token costs under control?
Measure per-language token inflation on real traffic (non-English can be several times English), reserve output tokens before packing context, trim boilerplate and repeated keys rather than assuming a structured-output mode is cheaper, because the schema is billed input and the braces are billed output, count with the target tokenizer at build time, alert before window overflow, and cache/compress stable context so you don’t re-pay for it every call.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.