Contents
  1. Text as model input
    1. Tokens and vocabulary IDs
      1. One string, seven vocabulary entries
    2. Characters, code points and bytes
      1. Two representations of é
    3. Preprocessing sets boundaries
  2. Vocabulary design
    1. Vocabulary size, coverage and length
      1. Granularity moves costs rather than removing them
    2. Must-know turning points
    3. Learning and applying BPE
      1. Counts follow the current segmentation
      2. Rank priority is not longest match
    4. WordPiece, Unigram and SentencePiece
      1. Different names answer different questions
  3. Reconstruction and source locations
    1. What decoding preserves
      1. Reconstruct bytes before characters
    2. Offsets need a coordinate system
      1. Name the coordinates
  4. Conversation structure
    1. Special tokens and chat templates
      1. Serialization is checkpoint-specific
      2. Three kinds of ending
      3. Do not format twice
  5. Language and boundary effects
    1. Language, code and formatting
      1. Translated content can occupy different budgets
    2. Joining text changes boundaries
      1. Joined encoding is not fragment addition
      2. Test behavior, not a token-count folk rule
  6. Request accounting
    1. Count the complete request
      1. What normally belongs in model input
      2. Exact and estimated hosted counts
    2. Reserve room for generation
      1. Different ways a bounded request can end
    3. From token usage to charges
      1. A dated accounting example
      2. Cached is not absent
  7. Check understanding
  8. Open questions
  9. Selected talks
  10. References
  11. Talk library
← All topics

Tokenization: How Text Becomes the Units Models Learn and Generate

Language models process sequences of vocabulary identifiers rather than written words directly. Tokenization maps text into those units; decoding maps generated units back to text. The mapping affects what fits in a request, how languages and code are represented and how applications locate pieces of the original input. This chapter follows characters and bytes through segmentation, vocabulary lookup and chat formatting to the sequence the model actually receives.

Text as model input

Tokens and vocabulary IDs

A token is one entry in a tokenizer’s finite vocabulary. Encoding converts text into an ordered sequence of token IDs; decoding maps IDs back toward text. Depending on the tokenizer, an entry may represent a word, a word fragment, punctuation, whitespace, a byte sequence, or a structural marker. A token is therefore neither reliably a word nor reliably a character. The tokenizer associated with the selected model defines the mapping.

One string, seven vocabulary entries

Published cl100k_base output for the string 2 + 2 = 4. The spaces do not follow one universal rule: some belong to punctuation pieces and others occupy separate entries.
Text pieceToken ID
217
+489
220
217
=284
220
419

Repeated pieces reuse the same IDs, but the numbers themselves are names, not measurements. ID 220 is not semantically “between” IDs 17 and 489. The model uses each ID to retrieve a learned vector and then computes with those vectors; Embeddings and Representation Learning explains that numerical representation. Changing IDs or using another tokenizer changes which learned rows the model receives, so tokenizer compatibility is part of the model interface rather than an interchangeable preprocessing preference. Ishan Anand’s GPT walkthrough provides an implementation-oriented view of this transition from pieces to IDs and vectors.

Characters, code points and bytes

Before inspecting a token boundary, name the text unit. A Unicode code point is a numbered position in the Unicode codespace. A grapheme cluster is a programmatic approximation to a user-perceived character and may contain several code points. UTF-8 then represents Unicode scalar values using one to four bytes. Some programming environments expose UTF-16 code units as yet another length and offset system.

Two representations of é

These forms can render alike while remaining different input strings.
FormCode pointsUTF-8 bytes
Composed éU+00E9C3 A9
Decomposed U+0065 U+030165 CC 81

One visible span, three coordinate systems

A👩‍💻B

The underlined emoji spans three code points
CharacterCode pointUTF-16 spanUTF-8 spanUTF-8 bytes
AU+0041
[0, 1)
[0, 1)[0, 1)41
👩U+1F469
[1, 2)
[1, 3)[1, 5)F0 9F 91 A9
ZWJU+200D
[2, 3)
[3, 4)[5, 8)E2 80 8D
💻U+1F4BB
[3, 4)
[4, 6)[8, 12)F0 9F 92 BB
BU+0042
[4, 5)
[6, 7)[12, 13)42
Code points: [1, 4)UTF-16: [1, 6)UTF-8: [1, 12)

Each interval is zero-based and end-exclusive. ZWJ is U+200D, the zero-width joiner. Highlighting the same emoji requires three different index pairs; tokenizer offsets require a separately specified tokenizer.

A👩‍💻B is a constructed encoding example. The emoji uses 3 code points, 5 UTF-16 units, and 11 UTF-8 bytes; these are not tokenizer positions.

A tokenizer may preserve this distinction, normalize it away, or split the byte sequences in different places. Consequently, a UI showing one apparent character does not establish a string length, byte length, token count, or safe slicing boundary.

Preprocessing sets boundaries

Tokenizer implementations commonly separate several responsibilities. Normalization transforms text under chosen equivalence rules. Pre-tokenization establishes regions within which the segmentation model may operate. The model then selects vocabulary pieces, and post-processing may insert special tokens. These stages are configurable; they are not universal properties of tokenization.

From source text to vocabulary IDs

  1. 1. Source textThe application supplies a string.
  2. 2. NormalizeConfigured rules may change that text.
  3. 3. Pre-tokenizeEstablish regions; these are not final tokens.
  4. 4. Select piecesUse fixed trained rules within each region.
  5. 5. Look up IDsMap pieces to vocabulary entries.
  6. 6. Post-processOptionally add configured structural tokens.
  7. 7. Ordered IDsEmbedding lookup happens afterward.
Stages are configurable; this shows their responsibilities, not a universal tokenizer configuration.

Normalization can discard distinctions an application needs, while lowercasing, accent removal, and whitespace cleanup are separate transformations. Treat every configured transformation as part of the input contract.

Pre-tokenization constrains later choices. In the inspected tiktoken 0.11.0 definition, one numeric expression creates regions of one to three numeric characters; for constructed ASCII input, 1234 first becomes 123|4. Those are preliminary regions, not a claim about the final token IDs: vocabulary merges still decide the pieces inside each region.

Vocabulary design

Vocabulary size, coverage and length

A whole-word vocabulary is compact for frequent known words but needs an entry for every retained form. Unseen names, misspellings, compounds, and inflections then require an unknown marker or another fallback. An unknown token preserves only the fact that some unsupported input occurred; it cannot reconstruct which input was lost. Character and byte representations avoid a huge word inventory, but usually produce longer sequences. Subword tokenization uses reusable fragments between those extremes, without promising that the fragments are linguistic morphemes.

Granularity moves costs rather than removing them

The actual outcome depends on the tokenizer’s base inventory, normalization, vocabulary, and fallback policy.
UnitVocabulary pressureCoverageTypical sequence effect
Whole wordHigh across domains and languagesUnsupported forms may become unknownShort for known words
CharacterSmall alphabet-dependent inventoryDepends on character coverageLonger sequences
UTF-8 byte256 ordinary byte values plus controlsCan represent arbitrary valid UTF-8 bytesOften longer sequences
SubwordLearned middle-sized inventoryDepends on base symbols and fallbackFrequent patterns become shorter

Vocabulary size also affects model parameters because token IDs index an embedding table with roughly vocabulary size times vector width entries. That matters especially for tiny models: a vocabulary suitable for a large multilingual system can dominate a small educational model’s parameter budget. But a smaller inventory may increase sequence work, so neither vocabulary size nor token count alone identifies the cheapest design. Byte-based models remain a live alternative: the 2022 ByT5 study removed the learned subword vocabulary, accepted longer sequences, and reported task-dependent advantages on tested noisy and spelling-sensitive workloads. It was a separately trained architecture, not a replacement tokenizer for an existing checkpoint.

Must-know turning points

Several lines of work contributed different parts of today’s tokenizer interface: compression, open-vocabulary segmentation, neural subword translation, and reproducible raw-text processing.

Four contributions to tokenization

  1. Byte-pair encoding

    Block-oriented data compression repeatedly replaced frequent byte pairs and stored their substitutions; it was not yet a language-model tokenizer.

    Philip Gage

    A New Algorithm for Data Compression
  2. Statistical word pieces

    Statistical word pieces addressed open-ended vocabulary and text without explicit word spaces in Japanese and Korean speech recognition.

    Mike Schuster and Kaisuke Nakajima; Google speech-recognition team

    Excellent Papers for 2012 — Japanese and Korean Voice Search
  3. Subword translation

    BPE was adapted to represent rare names, compounds, and changing word forms with reusable subword units inside a translation model.

    Rico Sennrich, Barry Haddow, and Alexandra Birch

    Neural Machine Translation of Rare Words with Subword Units
  4. SentencePiece

    SentencePiece packaged BPE or Unigram segmentation, normalization rules, and raw-text processing into a reproducible model artifact.

    Taku Kudo and John Richardson

    SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
Connected contributions, not a succession in which each method replaced its predecessor. Layout spacing does not measure elapsed time.

These are connected developments, not a ladder on which each new method eliminated the previous one. Word, character, byte, BPE, WordPiece, and Unigram approaches continue to coexist because their coverage, sequence length, preprocessing, and implementation tradeoffs differ.

Learning and applying BPE

Byte-pair encoding (BPE) separates vocabulary training from request encoding. Training repeatedly merges selected adjacent units and records their priorities. Encoding later applies those fixed priorities to new text; it does not recount the request or retrain the vocabulary.

Counts follow the current segmentation

In the published word-bounded BPE procedure, adjacent-pair counts are weighted by word frequency. Each merge changes the current segmentation, so the next pair is counted from that updated representation. Boundary and tie policies must be specified for a reproducible vocabulary.

Rank priority is not longest match

Applying ranks is not the same as greedily taking the longest vocabulary entry. A tokenizer must be identified by more than its vocabulary list. In the comparison, BPE changes merge priority; WordPiece changes the available prefix pieces; Unigram changes piece probabilities and compares their products across complete segmentations. These controls belong to different algorithms. Anand’s implementation walkthrough demonstrates the repeated-merge intuition in an accessible model reconstruction.

Same text, different segmentation rules

Base pieces: a, b, c, ab, bc. Each algorithm has its own configuration; changing one control affects only that algorithm. No abc piece or later merge is available.

Ranked BPE

a | bc

Start: a | b | c

  1. Merge bc (rank 1) → a | bc

Stop: no eligible adjacent pair remains. Lower rank wins; ties use the leftmost pair.

WordPiece: longest match

ab | c

ab · ##c

Choose the longest match at each position. Noninitial vocabulary entries use ##; it is a continuation marker, not input text. The fixture includes initial and continuation versions of every listed piece.

Unigram: score full paths

a | bc

P(a)=0.15, P(b)=0.10, P(c)=0.10. Moving the slider redistributes the remaining 0.65 between ab and bc. All five probabilities sum to 1.

Multiply piece probabilities across each complete path; the largest product wins. The table evaluates every path for this short input.

For abc: BPE a | bc; WordPiece ab | c; Unigram a | bc.

All complete Unigram segmentations, best first
PathPiece probability productScore
Best: a | bc0.15 × 0.400.06
ab | c0.25 × 0.100.025
a | b | c0.15 × 0.10 × 0.100.0015
These small vocabularies, ranks and normalized probabilities are teaching fixtures, not a released tokenizer. WordPiece continuation markers are displayed separately from input pieces; no token IDs or quality claims are implied.

WordPiece, Unigram and SentencePiece

Reusable pieces do not imply one selection algorithm. The original BERT WordPiece encoder works left to right, choosing the longest vocabulary match at each position. Continuation pieces use the ## prefix; its documented example represents unaffable as un, ##aff, ##able. If a remaining span cannot be matched, that implementation emits the unknown token for the whole word.

A Unigram tokenizer instead assigns scores to vocabulary pieces and evaluates complete candidate segmentations. The best segmentation is the highest-scoring path, commonly found with the Viterbi algorithm; the same inventory can admit several alternatives. Kudo’s 2018 subword-regularization work sampled such alternatives during training to create segmentation variation. That does not imply that randomly changing segmentation at inference will improve an already-trained model.

Different names answer different questions

Identify the algorithm, inventory, and preprocessing configuration separately.
NameWhat it identifies
Ranked BPERepeated use of learned merge priorities
Original BERT WordPiece encoderLongest matching piece from each position
UnigramA scored choice among complete segmentations
SentencePieceA toolkit and artifact format supporting BPE, Unigram, and configurable text processing

Google’s 2016 GNMT system adopted speech-derived WordPiece to help with rare-word translation and copying, but the deployed system combined many changes; its overall results cannot be assigned to tokenization alone. SentencePiece later made raw-text preprocessing and reconstruction rules part of a portable tokenizer artifact, improving reproducibility without guaranteeing preservation of distinctions removed by normalization.

Reconstruction and source locations

What decoding preserves

A text round trip, decode(encode(text)), preserves the original string only when the full pipeline is reversible for that input. Normalization may replace the original representation; unsupported input may become an unknown token; decoding may omit special tokens or clean spaces. Even when text round-trips, the reverse encode(decode(ids)) need not reproduce the same IDs because several token sequences can decode to the same text.

Reconstruct bytes before characters

A byte-based token boundary can fall inside a multibyte UTF-8 character. Decode the reconstructed byte stream, not each arbitrary fragment independently. An incremental decoder retains incomplete input between calls and handles any remainder when the stream ends.

A byte fragment can end inside a character

é → UTF-8 C3 A9 → fragments [C3], then [A9]

Independent decoders

[C3] → end of fragment →

[A9] → decode alone →

Combined emitted text: ��
Both are U+FFFD under replacement handling.

One stateful decoder

[C3] → buffer C3 → emit nothing

[A9] → complete C3 A9 → emit é

End of stream → flush → empty buffer

Flush the decoder at end of stream: a remaining incomplete sequence must be handled according to the error policy. Strict decoding throws instead of replacing malformed input.

For token bytes or other raw byte fragments. Follow the API contract for hosted streams that already provide decoded text strings.

Do not apply that repair where it is unnecessary. Some hosted streaming APIs already deliver decoded text fragments rather than token bytes; those strings should be accumulated according to the API contract. A delivery event is not necessarily one model token. Inference Engineering covers streaming and serving behavior in depth.

Finally, reversible tokenization does not force the model to copy text exactly. Generation selects a new sequence from model predictions. Systems that require exact identifiers, quotations, or source strings must compare the produced value with the required original or bypass generation for that field.

Offsets need a coordinate system

An offset is incomplete without two declarations: the representation it indexes and the unit it counts. Byte offsets, Unicode code-point offsets, UTF-16 code-unit offsets, and token positions are different coordinate systems. Ranges should also state their convention; the examples here use zero-based, end-exclusive intervals.

Name the coordinates

A displayed span can have different interval values in different representations.
Coordinate unitWhat it counts
Unicode code pointsPositions in the Unicode codespace sequence
UTF-16 code unitsSixteen-bit encoding units
UTF-8 bytesEight-bit encoding units
Token positionsEntries in one tokenizer output

Normalization creates a second mapping problem: an offset into normalized text may need alignment back to the original. Hugging Face’s internal NormalizedString uses byte-level alignment data, while the Transformers fast-tokenizer interface documents returned offsets as character start/end pairs. Those contracts should not be conflated merely because both expose two integers. Applications that attach extracted values to source material need the same discipline across every transformation; Document Understanding and OCR’s alignment section develops that broader source-location problem.

Conversation structure

Special tokens and chat templates

A special token is a designated vocabulary entry used for structure or control. A chat template converts ordered role/content messages into the token sequence expected by a particular chat checkpoint. It can insert a beginning marker, role headers, turn endings, and—where required—a generation prompt marking the start of an assistant response. Message objects are therefore an application interface, not the representation consumed directly by the model.

Serialization is checkpoint-specific

A pinned Mistral-7B-Instruct-v0.1 configuration formats the conversation user Hi, assistant Hello, user Bye with instruction boundaries and sequence markers. This template does not add a separate assistant prefix. Other checkpoints use different role markers and continuation rules, even when they share a base architecture.

Format the conversation once

1. user: Hi2. assistant: Hello3. user: Bye

↓ apply the checkpoint template once

<s> [INST] Hi [/INST] Hello</s> [INST] Bye [/INST]

Tokenize this serialization with additional special-token insertion disabled.

If automatic BOS insertion runs again: <s><s> [INST] Hi [/INST] Hello</s> [INST] Bye [/INST]

Pinned configuration: <s> is BOS ID 1; </s> is EOS ID 2. No full conversation ID sequence is asserted.

Mistral-7B-Instruct-v0.1, revision b54db9339734a22dd2b55531bd8146540729fbb8. This template adds no separate assistant prefix.

Visible delimiters show serialization, not proof that every delimiter is one reserved token. Structural markers do not authenticate roles or authorize actions.

Three kinds of ending

Similar-looking ending mechanisms operate at different layers.
MechanismRole
End-of-sequence tokenA model-vocabulary marker associated with sequence termination
End-of-turn or handoff tokenA model-family convention marking a conversational boundary
Application stop stringA serving configuration that terminates after matching text

Do not format twice

Apply structural formatting exactly once. If a chat template already inserts the required beginning token and a subsequent tokenization step inserts it again, the model receives a different prefix. Daniel Han’s fine-tuning bug review describes degraded inference when training and serving used different beginning-token counts. The same general rule applies to export: preserve the training serialization at inference. Padding is separate batch filler; if a training loss masks every occurrence of the padding ID, reusing an end-of-sequence ID for padding can also remove end targets from supervision. That conditional training issue belongs to Post-training and Alignment.

Structural markers guide the model’s learned interpretation; they do not authenticate a role or authorize an action. An application must enforce those responsibilities outside the tokenizer.

Language and boundary effects

Language, code and formatting

A tokenizer allocates its finite vocabulary according to training data and design choices. Patterns well represented in that data may receive long reusable pieces; less represented scripts, domain terms, identifiers, and numeric forms may fragment. Consequently, comparable information can occupy different numbers of tokens. The result describes representation length under one tokenizer, not a language’s complexity or a model’s intelligence.

Translated content can occupy different budgets

In a FLORES-200 study of 2,000 translated sentences across 200 languages, Table 1 reported these historical cl100k_base token-count ratios relative to English.
LanguageTokens relative to English
English1.00
French1.60
Japanese2.30

These corpus-specific ratios are not universal conversions. A related metric, token fertility, is the average number of subwords per tokenized word. It requires a stated word-segmentation convention and is not the same denominator as a parallel-sentence token ratio. Neither metric directly measures downstream task quality.

Formatting can be equally surprising. Published cl100k_base regression fixtures show today followed by newline-space taking three tokens, while adding one more newline makes the string two tokens. More input characters produced fewer tokens because the complete pattern admitted a different segmentation. Indentation, punctuation, escaping, and numeric grouping can similarly alter counts—but only text presented to the model matters. Extra syntax in an HTTP envelope does not count unless the service serializes it into model-visible content.

Joining text changes boundaries

Tokenization is generally not additive under string concatenation. Encoding a + b can differ from concatenating encode(a) and encode(b) because the joined text changes pre-tokenization regions or creates adjacent units eligible for a merge. This matters for prompt prefixes, leading spaces, suffixes, partial words, and labels that look indivisible to a human.

Joined encoding is not fragment addition

An inspected GPT-2 regression fixture gives an exact boundary counterexample.
OperationResult
encode("0")[15]
encode("0") + encode("0")[15, 15]
encode("00")[405]

Both ID sequences can decode to the text 00, so decoding and re-encoding [15,15] need not preserve those original IDs. For counting and caching, always serialize the complete request before encoding rather than summing arbitrary fragments.

Test behavior, not a token-count folk rule

Boundaries can also complicate character-sensitive work, but they are not a complete causal explanation. The 2024 CUTE study found that tested models could often spell tokens yet struggled more with character insertion, deletion, substitution, and swapping. The 2025 CharBench preprint found different relationships for counting and character-position tasks, with word length and requested counts often mattering more than token count alone. These results rule out both extremes: tokenized models are not categorically blind to spelling, and fewer tokens do not universally solve character tasks.

A boundary change is a reason to run a controlled behavior test, not proof that a rewritten prompt is better. Prompting and In-Context Learning covers instructions, demonstrations, ordering, and held-out prompt experiments.

Request accounting

Count the complete request

The relevant input count belongs to the complete representation presented to the model: system instructions, serialized message history, role and boundary markers, retrieved content, and model-visible tool or schema definitions. The HTTP JSON envelope is a transport representation and should not be tokenized as a substitute unless its literal syntax is itself included in model content.

Count the complete model-visible request

Model-visible boundary
System instructionsRetained messagesRetrieved contentExposed tools and schemas

↓ serialized together; applicable role / turn markers inserted by template

Complete ordered input, including cached prefixes

↓ count this complete representation using the endpoint’s contract

Prompt count P

The HTTP envelope transports the request. Its ordinary field names, headers, and wire syntax remain outside this boundary unless literally exposed as model input. Separately tokenized fragment counts need not add up to the joined count.

Inclusion depends on the endpoint and template. OpenAI documents an exact Responses input-count contract; Claude documents an estimate. Those guarantees are not interchangeable.

What normally belongs in model input

Establish the counting boundary before choosing a counting method.
MaterialCount it when
User and assistant contentThe serialized request retains it
System instructionsThey are supplied to the invocation
Role and turn markersThe selected template inserts them
Tools and schemasThe service exposes their definitions to the model
HTTP keys and wire syntaxOnly when they become model-visible text

Exact local counting requires the intended tokenizer artifacts, chat-template revision, special-token settings, and complete joined input. Pinning a repository revision does not freeze caller overrides. Adding vocabulary entries also requires resizing compatible model embedding parameters; a tokenizer with attractive counts cannot simply replace the checkpoint’s tokenizer.

Exact and estimated hosted counts

Hosted counters have provider-specific contracts. OpenAI documents its Responses input-count endpoint as returning the exact input count the model will receive, including role and boundary formatting. Claude documents its token-counting result as an estimate that can differ slightly from message-creation usage and may include automatically added material. Use the provider’s stated guarantee rather than generalizing one service’s semantics to another. Noah Hein’s AI Engineering 101 workshop illustrates the practical value of counting documents with the selected model tokenizer before processing them.

Reserve room for generation

A context window is a bound on the token sequence available to one model invocation. For an endpoint with a shared context limit, let PP be the complete counted prompt, RR the generated-token allowance reserved by the application, and CC the supported context capacity. If the endpoint also has a separate maximum output OO, both bounds must hold:

P + R ≤ C, and R ≤ O

Reserve output within both limits

Striped: cached inputBlue: other inputGold: reserved outputWhite marker: C = 8,192

Shared context: 7350 + 700 = 8050. 142 tokens remain.

Separate output cap: R = 700; O = 1,000. Fits output cap.

Caching changes no segment’s occupancy. A reservation is an allowance, not a promise that the model emits that many tokens.

Example capacities: shared context C = 8,192 and output cap O = 1,000 tokens. Apply the actual endpoint contract; fitting these bounds does not guarantee answer quality or effective use of retained context.

A max_new_tokens-style setting caps generated tokens; it does not prove that prompt plus generation fits the shared context. Provider-defined hidden reasoning or formatting tokens may also consume the generated allowance, so reserve according to the actual endpoint contract without counting the same category twice.

Different ways a bounded request can end

Capacity, transport success, and semantic completion are separate facts.
OutcomeMeaning
Input rejectionThe submitted representation exceeded an accepted limit
Input truncationAn application or runtime removed input tokens before execution
Natural completionThe runtime reported its normal completion condition
Output-cap terminationThe returned prefix reached a generated-token bound
Context-limit terminationGeneration filled the available shared context

Cached prefixes still occupy context even when caching reduces processing charges. Likewise, fitting the nominal window does not guarantee that every retained fact influences the answer. Controlled long-context experiments have found position-dependent use in several tested models and tasks. Choosing what deserves the finite allowance is context allocation, covered in Context Engineering; architectural reach and effective use are discussed in When longer context helps.

From token usage to charges

Providers bill according to named usage categories rather than one universal token rate. Read the pricing table and usage schema together because input, cached input, and generated output can have different prices and reporting rules.

A dated accounting example

Using rates inspected on August 30, 2026 for Claude Sonnet 4.6, this constructed request costs $0.006 before cache, tool, regional, or other charges. It was not executed or billed.
CategoryUsageRate per millionCharge
Ordinary input1,000 tokens$3$0.003
Output200 tokens$15$0.003
Total$0.006

Cached is not absent

Claude reports cache reads, cache creation, and ordinary input separately. Add the documented categories when reconciling total input; cached prefixes still occupy context.

Tokenization therefore affects both capacity and charges: language, formatting, templates, and tool definitions can change counted input. But price per token alone cannot compare models whose tokenizers, output lengths, and task results differ. Token counts also affect computational work without determining elapsed latency; concurrency, batching, hardware, request rate, and output behavior matter. AI Cost and Performance Engineering owns those workload comparisons, while Inference Engineering covers serving behavior and bottlenecks.

Open questions

  1. Can future byte- or patch-based model architectures retain open input coverage while matching subword systems’ practical training and serving efficiency? BLT concentrates expensive processing at uncertain byte regions, but operation counts do not yet establish equivalent wall-clock behavior or broad deployment. Progress would require controlled quality, latency, memory, and robustness comparisons at matched training resources.

  2. How should multilingual tokenizer quality be evaluated when word boundaries, scripts, morphology, and downstream tasks differ? Existing fertility and parallel-corpus ratios reveal representation disparities but do not measure competence. Progress would combine explicit denominators, versioned tokenizers, representative workloads, and task outcomes across languages.

  3. How much of character-level failure is caused by token boundaries rather than data, architecture, prompting, or task formulation? Recent studies find task-dependent relationships and show that models can possess spelling knowledge while failing at manipulation. Stronger causal evidence would hold the model and training data fixed while varying representation and evaluating multiple character operations.

  4. Can provider token accounting become portable without hiding model-specific serialization? Current APIs expose different guarantees and category semantics. Progress would look like versioned, machine-readable contracts that identify tokenizer artifacts, template revisions, model-visible additions, count guarantees, and billing-category relationships.

Follow the curated reading path through the speakers and demonstrations behind this entry.

Explore more talks

The rest of the library, beyond the curated path. Cited talks support this entry; reviewed transcripts were processed in full. Metadata candidates have not been reviewed as sources or verified as topic members.

9 matching talks

TalkSpeakerEventYear
Diego CarpenteroAI Engineer Europe 20262026
AI Engineering 101

Cited in this entry

Noah HeinAI Engineer Summit 20232023
Low Level Technicals of LLMs

Transcript reviewed

Daniel HanAI Engineer World's Fair 20242024
Ishan AnandAI Engineer World's Fair 20242024
Nupur SharmaAI Engineer Europe 20262026
Jamie Neuwirth, Zack WittenAI Engineer World's Fair 20242024
Philipp KrennAI Engineer World's Fair 20252025
Mark MoyouAI Engineer World's Fair 20242024
Yesu FengAI Engineer World's Fair 20252025

References

Coverage and source review
Processed transcripts
9 processed in full · 4 in the curated path
Automated source review
Passed
Metadata candidates
4 unreviewed; not verified topic membership
Corpus version
1bd8e407b26a07b33815594e1b2db5f41827119a2b3cb6fbf240f9fc571fc767

Automated review checks source support; it is not publication approval.

A synthesis of selected conference talks and technical references. Citations link to the source material; they do not imply that every talk on this subject is included.

  1. Hugging Face: Tokenizers

    A tokenizer converts text into a sequence of vocabulary identifiers that a model can process numerically. Tokens can represent words, characters or subword fragments; one word need not equal one token. Subword tokenization balances vocabulary size against the ability to represent unfamiliar words. Encoding performs tokenization and conversion to IDs; decoding maps IDs back into text.

  2. Tokenization algorithms — Transformers

    A tokenizer represents text using a finite vocabulary rather than treating each word as an indivisible unit. Subword methods can keep frequent words intact and split less common words into smaller pieces. BPE learns merge rules by repeatedly combining frequent adjacent units; byte-level BPE begins from byte values so it can encode arbitrary input bytes without an unknown-word token. The same text can split differently under different vocabularies. Tokenization therefore changes sequence length and the units available to the model; a token count is not a word count.

  3. OpenAI Cookbook: How to count tokens with Tiktoken

    The published cl100k_base example encodes "2 + 2 = 4" as [17,489,220,17,284,220,19], corresponding to byte pieces ["2"," +"," ","2"," ="," ","4"]. Repeated occurrences reuse IDs, and spaces can belong to punctuation pieces or stand alone. The same string uses five tokens under r50k_base. For "お誕生日おめでとう", the published counts are 14 under r50k_base, nine under cl100k_base and eight under o200k_base. In cl100k_base, the bytes of 誕 are split between tokens 45918 and 243.

  4. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    A token ID identifies a vocabulary entry; its embedding supplies the numeric representation used to express relationships and perform model computation.

  5. Attention Is All You Need

    Learned embeddings map discrete vocabulary tokens to numerical vectors. Positional information supplies ordering, and decoder attention masks future positions so predictions depend only on available preceding output. A learned linear projection and softmax convert decoder representations into next-token probabilities; for vocabulary scores z, softmax(z)j=exp(zj)/Σv exp(zv). These are computations using weights. Training instead updates weights with an optimizer; the paper uses Adam. Recomputing representations for a new context is consequently different from learning new parameters.

  6. Unicode Glossary

    A Unicode code point is an integer position in the Unicode codespace; not every position has an assigned character. An encoded character associates an abstract character with a code point. A code unit is a unit of encoded text: UTF-8 uses eight-bit units, UTF-16 sixteen-bit units, and UTF-32 thirty-two-bit units. These are character-encoding units, distinct from a model tokenizer's vocabulary identifiers.

  7. Unicode Standard Annex #29: Unicode Text Segmentation

    Grapheme clusters are a programmatically determined approximation to user-perceived characters. A perceived character can contain multiple code points: the annex illustrates a base letter followed by a combining accent. Extended grapheme clusters provide default boundaries, with permitted tailoring. Unicode word boundaries also require language-sensitive treatment; reliable word segmentation for languages including Thai, Chinese and Japanese can require dictionary lookup or other mechanisms.

  8. Unicode FAQ: UTF-8, UTF-16, UTF-32 and BOM

    UTF-8 represents Unicode scalar values using sequences of one to four bytes. Valid multibyte sequences have constraints on their leading and continuation bytes; arbitrary byte sequences need not be valid UTF-8. A conforming decoder must handle malformed sequences as errors rather than interpret them as characters, potentially reporting an error or inserting U+FFFD, the replacement character.

  9. Unicode normalization charts: Latin

    The normalization chart gives U+00E9, é, as its own NFC and NFKC result, while NFD and NFKD produce U+0065 U+0301. This supplies an exact composed-versus-decomposed accent example without assuming that a tokenizer performs either transformation.

  10. Unicode 16.0 Core Specification, Chapter 3: encoding forms

    Unicode specifies UTF-16 surrogate pairs for scalar values above U+FFFF and the bit distributions for UTF-8. Applying these rules gives U+00E9 the UTF-8 bytes C3 A9, while U+0065 U+0301 becomes 65 CC 81. For the constructed sequence U+1F469 U+200D U+1F4BB, UTF-8 is F0 9F 91 A9 E2 80 8D F0 9F 92 BB. It occupies three code points, five UTF-16 code units and eleven UTF-8 bytes. In A👩‍💻B, the emoji therefore spans [1,4) in code-point coordinates, [1,6) in UTF-16 units and [1,12) in UTF-8 bytes.

  11. Unicode Standard Annex #15: Unicode Normalization Forms

    NFD performs canonical decomposition; NFC additionally performs canonical composition. NFKD and NFKC also apply compatibility decompositions. Canonically equivalent representations include a precomposed accented letter and its base-plus-combining-mark sequence. Compatibility normalization can remove distinctions: the fi ligature becomes two letters, and superscript formatting can disappear. Normalization therefore supplies a consistent representation under a chosen equivalence relation, rather than preserving every original code-point sequence.

  12. Hugging Face Tokenizers: The tokenization pipeline

    The library separates normalization, pre-tokenization, the segmentation model and post-processing. Normalization can change text; its NFD-plus-accent-removal example converts accented letters to unaccented ones. Pre-tokenization establishes regions within which the segmentation model operates, constraining possible final tokens. The model applies learned segmentation rules and maps pieces to vocabulary IDs; post-processing can insert special tokens. The documented Whitespace pre-tokenizer separates punctuation, including the apostrophe in I'm. Combining it with individual-digit splitting turns 911 into three separate digit regions. Returned spans refer to positions in the original sentence.

  13. tiktoken 0.11.0: encoding definitions

    The cl100k_base and o200k_base definitions separate the pretokenization regular expression, mergeable ranks and special-token mapping. Their numeric expression matches runs of one to three numeric characters. Applying that expression to constructed ASCII examples gives regions 123|4 and 123|456|7; these are pretokenization regions, not asserted final token sequences. GPT-2's expression instead permits unrestricted numeric runs. The definitions also specify expected hashes for downloaded vocabulary artifacts, making the artifact identity more precise than the encoding name alone.

  14. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Whole-word tokenization trades a growing vocabulary for difficulty representing unknown or misspelled words.

  15. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    Subword tokenization can resemble meaningful word decomposition, but its frequency-driven splits need not match human linguistic intuition.

  16. ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models

    ByT5 processes UTF-8 bytes using 256 byte values plus special IDs, removing the learned subword vocabulary and its preprocessing pipeline. This reduces vocabulary-related parameters but produces longer sequences, creating a different resource tradeoff. Against mT5, the study reports stronger results on tested spelling- and pronunciation-sensitive tasks and greater resilience to synthetic character noise. Inference-speed differences vary substantially by task; short word-level tasks behave differently from sentence classification and document summarization. Byte-based representation therefore remains a practical alternative rather than an obsolete precursor to subwords.

  17. SentencePiece configuration options

    SentencePiece supports Unigram, BPE, word and character models, so its name does not identify one segmentation algorithm. Its byte_fallback option represents otherwise out-of-vocabulary characters with UTF-8 byte tokens; this differs from starting every input region with bytes. Without fallback, excluded characters can become an unknown token whose decoded surface is a configured placeholder. Normalization and whitespace handling are separately configurable, including compatibility normalization, dummy prefixes and removal of extra whitespace. Control symbols are not recognized from raw text and decode to empty strings, whereas user-defined symbols are matched from raw text.

  18. Training an LLM from Scratch, Locally

    Character-level tokenization keeps the workshop vocabulary small but requires more tokens and more composition to represent meaningful text.

  19. Training an LLM from Scratch, Locally

    A large vocabulary can make the embedding table disproportionately large for a tiny model.

  20. Philip Gage: A New Algorithm for Data Compression

    Gage's February 1994 article presents BPE as general-purpose data compression with a small, fast decompression routine suited to limited-memory applications. It repeatedly replaces frequent adjacent byte pairs with unused byte values and stores the substitution table alongside the compressed block. Its example transforms ABABCABCD into XXCXCD by replacing AB, then into XYYD by replacing XC. Compression works on buffered blocks with separate substitution tables; slow compression is an acknowledged tradeoff.

  21. Excellent Papers for 2012 — Japanese and Korean Voice Search

    Google's account of Schuster and Nakajima's 2012 speech-recognition work identifies two related problems: representing an open-ended vocabulary without unrecognized words, and handling text without explicit spaces between words. It describes statistical segmentation as part of the solution used in Google's Japanese and Korean Android voice-search systems, alongside language modeling and dictionary construction.

  22. Neural Machine Translation of Rare Words with Subword Units

    The 2016 ACL paper adapts BPE to handle rare-word translation within the neural model instead of relying on dictionary fallback. Names, compounds and changing word forms motivate smaller reusable units: copying an unknown word cannot supply every required transliteration or grammatical change.

  23. SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing

    Kudo and Richardson's 2018 system paper addresses dependence on language-specific preprocessing, including separate word segmenters and hand-written detokenization rules. SentencePiece supports training BPE or Unigram segmentation directly from raw sentences. Its model artifact includes vocabulary entries, segmentation parameters and compiled normalization rules, addressing reproducibility problems caused by separately configured preprocessing tools. The paper's reconstruction contract preserves normalized text; it does not promise recovery of distinctions removed before segmentation.

  24. tiktoken educational byte-pair encoding implementation

    The educational encoder splits text with a configured regular expression, converts each region to UTF-8 bytes and begins with individual-byte pieces. It repeatedly merges the eligible adjacent pair with the smallest stored rank, then looks up the final pieces' IDs. Encoding uses fixed ranks; its separate trainer counts corpus pairs and updates the segmented training data after each merge. An illustrative consequence is that ranks bc before ab segment abc as a|bc when no further merge exists, whereas left-to-right longest matching chooses ab|c. Ranked merging therefore need not equal longest vocabulary matching.

  25. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    Byte-pair encoding (BPE) repeatedly merges frequent adjacent token pairs, growing the vocabulary while shortening the corpus representation.

  26. Neural Machine Translation of Rare Words with Subword Units

    The paper adapts byte-pair compression to character-sequence segmentation. It initializes words as characters plus an end-of-word marker, counts adjacent pairs weighted by word frequency, merges the most frequent pair and repeats. Algorithm 1 uses low:5, lower:2, newest:6 and widest:3. In that initial corpus, e–s and s–t each have weighted count nine, illustrating why a reproducible walkthrough must specify tie handling. This implementation excludes pairs crossing word boundaries. Learned operations are then applied to new words rather than relearned from each input.

  27. How LLMs work for Web Devs: GPT in 600 lines of Vanilla JS

    The demonstrated GPT-2 tokenizer uses the trained merge vocabulary and rankings to turn new text into the model's existing tokens.

  28. BERT original WordPiece tokenizer implementation

    BERT's WordpieceTokenizer chooses the longest vocabulary match from the current position, then advances and repeats. Noninitial pieces use the continuation prefix ##. Its documented example segments unaffable into un, ##aff and ##able. If any remaining span cannot be matched, the implementation emits the unknown token for the entire word rather than retaining the partial segmentation. It also maps words beyond its configured character limit to the unknown token.

  29. Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates

    The proposed Unigram tokenizer assigns each vocabulary piece a probability and scores a segmentation by multiplying its pieces' probabilities. The best segmentation maximizes that score over candidate segmentations and can be found with the Viterbi algorithm. The same vocabulary can therefore admit several segmentations with different scores; the paper also describes sampling alternatives. This differs from choosing merges by BPE rank or greedily selecting the longest next piece.

  30. Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates

    Taku Kudo’s July 2018 ACL paper treats alternative segmentations as useful training variation. Sampling them improves translation robustness, particularly in lower-resource and out-of-domain experiments. Without sampling, Unigram and BPE achieve broadly comparable translation scores; the benefit is therefore not simply replacing BPE with another deterministic encoder.

  31. Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation

    Yonghui Wu and colleagues’ 2016 GNMT report explicitly adopts WordPiece from Google’s Japanese/Korean speech-recognition work to address rare-word translation. Shared source and target segmentation helps the model learn copying, while word-boundary markers support reconstruction. Its implementation still maps excluded rare characters to an unknown character. The experiments compare word, character, mixed and 8K–32K WordPiece vocabularies. On WMT English–French, the character model achieves translation quality close to WordPiece but takes 1.0530 CPU seconds per sentence versus 0.2118 for WPM-32K, illustrating the cost of longer sequences.

  32. A Neural Network for Machine Translation, at Production Scale

    On September 27, 2016, Google Brain researchers Quoc Le and Mike Schuster announced GNMT and stated that Google Translate’s mobile and web applications were already using it for all Chinese-to-English machine translations. They identified handling rare words through smaller units as one contributing development, while acknowledging remaining dropped words and mistranslated names or rare terms.

  33. Transformers Tokenizer API

    Transformers exposes decoding options that remove special tokens and clean tokenization spaces, so decoded output depends on more than the ID sequence. Adding vocabulary entries assigns new IDs and requires resizing the model's token embedding matrix to match the tokenizer. Added tokens are treated differently from entries governed by the underlying segmentation algorithm. apply_chat_template returns the conversation's token IDs, including control tokens, and accepts tool definitions as additional template inputs.

  34. tiktoken Encoding API implementation

    tiktoken distinguishes ordinary text encoding from explicitly allowed special-token recognition. By default, encode rejects recognized special-token spellings; disallowed_special=() treats them as ordinary text, while allowed_special permits reserved IDs. decode first reconstructs bytes and then decodes UTF-8, replacing invalid sequences by default; decode_single_token_bytes preserves a token's bytes. Independently decoding fragments can therefore lose information. decode_with_offsets maps a token beginning inside a multibyte character to that character's index. encode_with_unstable exposes stable prefix tokens and possible completions, demonstrating that an unfinished suffix need not retain its segmentation.

  35. tiktoken encoding regression tests

    The tests specify GPT-2 encoding of hello world as [31373,995] and cl100k_base encoding as [15339,1917]. GPT-2 encodes 0 as [15] but 00 as [405]: joining two separately encoded zeros changes both segmentation and count. Consequently, decoding [15,15] to 00 and re-encoding need not preserve the original IDs. For cl100k_base, today followed by newline-space has three tokens, while adding another newline produces two. The thumbs-up emoji is three tokens in its fixture. The suite also checks whitespace and multilingual text round trips and explicit special-token policies.

  36. Python codecs: Incremental Encoding and Decoding

    An incremental decoder retains state across calls, including undecoded input, so concatenating its outputs matches decoding the concatenated input. The final call must set final=True, which flushes buffered data and invokes error handling if an incomplete byte sequence remains. Strict handling raises an error; replacement handling inserts U+FFFD for decoding errors. This supplies a standard implementation mechanism for receiving UTF-8 bytes in fragments without treating every fragment as a complete string.

  37. Claude Platform: Streaming messages

    Claude's streaming interface delivers named server-sent events containing JSON. A text_delta carries a text string, illustrated by the fragment ello frien, rather than a token ID. Content-block events, message updates, pings and errors have distinct roles. Usage counts in message_delta are cumulative. Consequently, applications should accumulate text deltas and read usage accounting rather than count delivery events as model tokens.

  38. Utilities for Generation: TextStreamer and TextIteratorStreamer

    Transformers streamers receive generated token IDs and decode them for delivery. TextStreamer buffers until text forms complete words; end() flushes remaining cached text. TextIteratorStreamer instead puts printable text in a queue for a downstream consumer, with a configurable queue timeout for separately threaded generation. Thus a generation step, decoded text fragment and consumer observation are distinct events; one delivered fragment need not equal one token. Incremental delivery can expose a prefix before generation finishes.

  39. Language Models are Unsupervised Multitask Learners

    Tokenization represents text as a sequence of vocabulary symbols rather than necessarily whole words. GPT-2 uses byte-level byte-pair encoding: a 256-byte base supports arbitrary text, while frequency-based merges create longer tokens, subject to character-category restrictions. Autoregressive modeling factorizes sequence probability as P(x1,…,xn)=∏i Pθ(xi|x<i). Generation repeatedly predicts a next-token distribution conditioned on the supplied prefix and previously generated tokens. Task instructions and examples can therefore change the conditional distribution without changing θ. GPT-2's zero-shot evaluations modify neither learned parameters nor architecture; request text changes the inputs and resulting activations, not the trained weights.

  40. Transformers: greedy and sampled token selection

    Greedy decoding chooses the highest-probability next token at each step. Multinomial sampling draws a token from the vocabulary probability distribution, so lower-probability tokens can be selected. Transformers enables ordinary sampling with do_sample=True and num_beams=1. Combined with the transformer's autoregressive architecture, the selected token becomes part of the input for the next prediction. Greedy selection removes this token-draw randomness but does not establish semantic correctness or globally maximize the probability of an entire sequence.

  41. Hugging Face Tokenizers: NormalizedString implementation and alignment tests

    NormalizedString retains original and normalized strings with an alignment entry for each normalized byte, and distinguishes Original from Normalized ranges. Its NFKC slicing test starts with mathematical double-struck text 𝔾𝕠𝕠𝕕 𝕞𝕠𝕣𝕟𝕚𝕟𝕘. Original range [0,4) retrieves original 𝔾 and normalized G; normalized range [0,4) retrieves normalized Good and original 𝔾𝕠𝕠𝕕. These are UTF-8 byte coordinates: the same numerical range selects different spans depending on its coordinate system.

  42. Transformers: Utilities for Tokenizers

    from_pretrained accepts a revision identifying a branch, tag or commit, and initialization arguments can override special-token settings. Pinning repository artifacts therefore does not by itself freeze caller-supplied configuration. The API documents return_offsets_mapping as character start/end pairs available through fast tokenizers. It separately warns that encoding individual chat messages may be imperfect when a template's conversation prefix cannot be distinguished from message-start material.

  43. Transformers: model-specific chat serialization

    A chat template converts ordered role/content messages into the token sequence a causal model continues, inserting model-specific role markers, message boundaries and special tokens. Models fine-tuned from the same base can require different formats: Mistral-Instruct brackets user messages with instruction delimiters, while Zephyr uses explicit speaker markers. The guide warns that incompatible control tokens degrade performance. Where the format requires it, add_generation_prompt=True appends the assistant-start marker; omitting it can cause continuation of the user's message instead of a reply. Some templates need no such marker. Templates already supply required special tokens: use apply_chat_template(tokenize=True), or tokenize the rendered string with add_special_tokens=False to avoid duplicated beginning/end tokens.

  44. Chat templates — Transformers

    Chat roles and message contents are serialized into a token sequence using a model-specific template. Control tokens can mark message boundaries and speaker roles; even models derived from the same base can require different formats. A generation prompt marks the start of a new assistant response, while continuing a final message serves a different purpose. Templates already include necessary special tokens, so adding them again during a second tokenization step can duplicate boundaries and harm behavior. A chat API abstraction does not exempt the input from the underlying sequence format.

  45. Mistral-7B-Instruct-v0.1 tokenizer configuration at b54db9339734a22dd2b55531bd8146540729fbb8

    This pinned configuration assigns BOS <s> ID 1 and EOS </s> ID 2, enables automatic BOS insertion and disables automatic EOS insertion. Its template separately emits BOS, brackets user content with instruction delimiters and appends EOS after assistant content. Applying the inspected template by hand to user Hi, assistant Hello, user Bye gives <s> [INST] Hi [/INST] Hello</s> [INST] Bye [/INST]. This template does not reference add_generation_prompt, so that option adds no separate assistant prefix.

  46. Llama 3.3 Prompt Formats

    Llama's documented format distinguishes prompt start, role-header boundaries, padding and ending markers. The guide describes end_of_text as a base-model stopping marker, eot_id as completion of an assistant turn and eom_id as a handoff point during interaction. Its instruct example serializes system and user messages with headers and endings, then leaves an assistant header ready for continuation. Padding makes sequences the same length within a batch.

  47. Transformers GenerationConfig: output reservation and termination

    Generation selects tokens from successive vocabulary scores using the decoding configuration. max_new_tokens caps generated tokens without counting prompt tokens. Consequently, setting it to R reserves output length but does not itself establish that prompt length P plus R fits the model's context. eos_token_id identifies one or more end-of-sequence tokens, allowing generation to stop before the cap; minimum-length and other stopping controls can alter termination. stop_strings supplies additional textual stopping conditions. Reaching the output cap bounds the generation loop but does not establish that the response is complete. Application inference: validate the combined prompt/output budget before generation rather than treating an output-only limit as a context check.

  48. Fixing bugs in Gemma, Llama & Phi-3

    Check that training and inference insert the same single beginning-of-sentence (BOS) token where the model requires one.

  49. Fixing bugs in Gemma, Llama & Phi-3

    Use distinct padding and end-of-sequence (EOS) token IDs when the training loss masks tokens by the padding ID.

  50. SFT Trainer: objective, shifting, and masking

    For prompt x and target response y, supervised fine-tuning minimizes negative conditional log likelihood: L = -sum_t m_t log pi_theta(y_t | x,y_<t), optionally normalized by the count of included tokens. The mask m_t excludes padding and can exclude prompt or non-assistant tokens. Each prediction conditions on the demonstrated prefix, rather than a prefix sampled from the model; this is teacher forcing. The loss rewards probability assigned to the demonstrated next token, not execution success or truth directly. Current TRL supports completion-only and assistant-only loss with dataset/template requirements. Changing masking changes which behavior receives direct supervision, even when the visible example text is identical.

  51. Language Model Tokenizers Introduce Unfairness Between Languages

    The study compares tokenized lengths of parallel sentences from FLORES-200, using 2,000 sentences translated into 200 languages. It defines tokenizer parity through the ratio of token counts for corresponding translations and observes substantial differences across the evaluated tokenizers and languages. For tokenizers with unknown symbols, it excludes language results exceeding its unknown-character threshold. The authors acknowledge that topic coverage, English-centric named entities and alternative translations can affect the measured ratios.

  52. Training an LLM from Scratch, Locally

    Byte pair encoding (BPE) builds reusable tokens from recurring character patterns in the training data.

  53. Training an LLM from Scratch, Locally

    An uncommon variable name need not have its own vocabulary entry; it can split into smaller pieces, increasing inference work.

  54. Language Model Tokenizers Introduce Unfairness Between Languages

    Table 1 reports cl100k_base token-count premiums relative to English of 1.60 for French, 1.58 for German and 2.30 for Japanese on FLORES-200. These provide representative numerical examples of equivalent translated content occupying different token budgets.

  55. How Good is Your Tokenizer? On the Monolingual Performance of Multilingual Language Models

    The paper defines subword fertility as the average number of subwords produced per tokenized word. Its separate continued-word metric measures how often words split into multiple pieces. The analysis uses training and development portions of specified Universal Dependencies v2.6 treebanks and finds different fragmentation patterns across languages and monolingual versus multilingual tokenizers. Fertility measures segmentation granularity under that word denominator; it is distinct from the paper's downstream task evaluations.

  56. OpenAI API: Counting tokens

    OpenAI documents POST /v1/responses/input_tokens as accepting Responses-format inputs and returning the exact input count the model will receive, including role and boundary formatting absent from locally tokenized content. Tools and schemas also contribute. This is a provider-specific counting contract, distinct from the supplied Claude documentation's estimate contract. The guide additionally states that output usage can include invisible channel, tool-call and message-formatting tokens even when reasoning_tokens is zero. Output-token limits cover those generated tokens as well as visible text; the difference is not a fixed overhead.

  57. CUTE: Measuring LLMs’ Understanding of Their Tokens

    Lukas Edman, Helmut Schmid and Alexander Fraser’s November 2024 CUTE paper tests orthographic knowledge—the spelling and character composition of text. With four demonstration examples, evaluated models perform well at spelling tokens but struggle more with character insertion, deletion, substitution and swapping than with corresponding word operations. Knowing a token’s spelling therefore does not establish reliable character manipulation, while successful spelling contradicts a categorical claim that subword models cannot access character information.

  58. CharBench: Evaluating the Role of Tokenization in Character-Level Tasks

    Omri Uzan and Yuval Pinter’s August 4, 2025 preprint distinguishes character counting from locating characters within words. Across its evaluated models, token count and average characters per token correlate relatively weakly with correctness. Word length and the required count matter more for counting tasks. For positional tasks, longer tokens containing the queried character correlate with lower accuracy, particularly for GPT-4o. Tokenization’s relationship to errors consequently depends on the task rather than following a universal fewer-tokens-is-better rule.

  59. Transformers: chat templates serialize conversation history

    A chat model still receives a token sequence. A chat template turns role-labelled messages into that sequence, adding model-specific control tokens that mark speakers and message boundaries. Retained user messages, assistant messages and instructions therefore consume input tokens alongside the latest question. The rendered template, including any assistant-generation prefix, determines the effective input. Counting only visible message text can miss control-token overhead. Stored conversation history is not automatically identical to the history actually serialized for a particular inference call.

  60. Understanding and counting tokens — OpenAI

    Tokens are the units a model processes: a token can represent a character, word fragment, whole word or punctuation, and spaces affect segmentation. Counts depend on the model encoding, language and surrounding text; token counts are not word counts. Counting only plain text can omit message formatting, tool definitions, schemas and non-text inputs. Reasoning models can generate internal reasoning tokens that are not visible answer text but still count toward output usage. An input count does not predict output length.

  61. AI Engineering 101

    The workshop treats tokenization as model-coupled and counts encoded tokens per document before processing.

  62. Claude Platform: Token counting

    Claude's counting endpoint accepts structured message inputs, including system prompts and tool definitions, rather than only message-content strings. The documentation explicitly describes the returned input count as an estimate that can differ slightly from the input count used when creating a message. Counts may include automatically added system material. This provides a concrete distinction between counting a specified representation and guaranteeing an eventual provider request count.

  63. Transformers LlamaConfig: supported sequence positions

    LlamaConfig defines max_position_embeddings as the maximum sequence length for the model and separately documents RoPE parameters for positional scaling. Application budgeting inference: let C be the supported limit for the exact checkpoint and positional configuration, P the length of the complete tokenized prompt, and R the reserved generated-token count; enforce P+R<=C. P includes template/control tokens, system instructions, conversation and retrieved text. Count the final serialized token IDs rather than characters or independently tokenized fragments. If the budget fails, remove or summarize selected material, reduce retrieval or reserve fewer output tokens, then serialize and count again.

  64. Conversation state: managing the context window — OpenAI

    The context window limits tokens used in one request, including supplied input and generated output; applicable reasoning tokens also consume capacity. Instructions, conversation history, retrieved material and tool results supplied to that invocation therefore share its input budget. A simple worked design reserves generated-token capacity before allocating remaining space to input, while also respecting the model's separate output limit. For a reasoning model, reserve space for hidden reasoning as well as the visible answer without counting the same output tokens twice. Persisting a conversation does not make its usable context unbounded.

  65. Claude context windows and cached-token accounting

    Cached prefixes still occupy the context window. System instructions, tool definitions, messages and tool results consume capacity, and generated output also occupies the window. A useful planning constraint is I + O <= W, where I is counted input, O is generated output and W is the model's context capacity. Caching changes processing cost, not this capacity requirement. Inputs exceeding the window are rejected; generation at the limit follows model-specific overflow behavior.

  66. Padding and truncation — Transformers

    Tokenizer truncation limits the input representation before model execution. With truncation enabled, max_length specifies the retained length or defaults to the model maximum when available. For paired sequences, longest_first repeatedly removes tokens from the longer sequence; only_first and only_second select the sequence eligible for truncation. No truncation is the documented default. Removing input tokens discards evidence; it is different from limiting newly generated output tokens. A tokenizer setting does not determine whether a remote API rejects or truncates an oversized request.

  67. Claude Platform: Stop reasons and fallback

    Claude distinguishes natural completion through end_turn from reaching the requested output cap through max_tokens and filling the context window through model_context_window_exceeded. These reasons can accompany successful API responses, so HTTP success does not establish that the answer is complete. During streaming, stop_reason begins as null and is supplied through message_delta.

  68. Transformers GenerationConfig: stopping and output budgets

    Generation can end on an end-of-sequence token, a configured stop string, a length limit, or other stopping criteria. max_new_tokens limits generated tokens independently of prompt length; max_length includes the prompt. These are upper bounds, not promises to produce that many tokens. max_time is not a hard deadline: generation finishes its current pass after the allotted time. For ordinary single-beam generation, do_sample selects sampling versus greedy decoding. An application should distinguish normal completion from length truncation, cancellation and failure rather than interpreting every returned prefix as a completed answer.

  69. Lost in the Middle: How Language Models Use Long Contexts

    The paper tests multi-document question answering and synthetic key-value retrieval while controlling context length and where relevant information appears. Reordering the answer-containing document changes its position without changing the desired answer. Several evaluated models performed better with evidence near the beginning or end than in the middle; results varied by model and task. This separates fitting tokens inside a supported context window from reliably retrieving and using their information. It motivates controlled position and distractor tests rather than assuming nominal length measures effective use.

  70. Claude Platform: Pricing

    The inspected table prices Claude Sonnet 4.6 standard input at $3 and output at $15 per million tokens; cache reads cost $0.30, five-minute writes $3.75 and one-hour writes $6 per million. A constructed request with 1,000 ordinary input tokens and 200 output tokens therefore costs $0.006 before other charges. The tool-use table specifies 497 additional system-prompt tokens for this model with auto tool choice and at least one tool. At the ordinary input rate, that overhead alone adds $0.001491, excluding tool definitions and results.

  71. Claude Platform: Prompt caching

    Claude reports cache reads, cache creation and ordinary input as separate input categories. Its input_tokens field excludes tokens read from or written to the cache. Total input is cache_read_input_tokens plus cache_creation_input_tokens plus input_tokens. The documentation's example has 100,000 cache-read tokens, no cache creation and 50 ordinary input tokens, totaling 100,050 input tokens. Reading only input_tokens would therefore substantially understate the request representation.

  72. GenAI-Perf: latency and throughput measurement

    GenAI-Perf defines TTFT as first-response receipt minus request-send time, and request latency as final-response receipt minus send time. Its inter-token latency divides the interval between successive responses by the latter response's generated-token count. Output-token throughput is total generated tokens divided by benchmark duration; request throughput is final responses divided by duration. A p99 latency is the 99th percentile of the specified latency observations, not an average. The tool supports concurrency, request rate, warmup count, measurement intervals, and input/output-length controls. Reproducible comparisons must report those settings and the workload/tokenizer.

  73. Byte Latent Transformer: Patches Scale Better Than Tokens

    Artidoro Pagnoni and colleagues at FAIR introduced BLT in a December 13, 2024 preprint. It addresses the long sequences produced by byte-level modeling by grouping bytes into variable-length patches without a fixed patch vocabulary. A small byte model estimates next-byte uncertainty to choose boundaries, concentrating expensive processing where prediction is harder. Experiments extending to eight billion parameters demonstrate feasible scaling and improved results on tested noisy-input and character tasks relative to the paper’s token-based baselines.

  74. Unicode Emoji 15.1: emoji ZWJ sequences

    Unicode's versioned emoji data identifies 👩‍💻, woman technologist, as the sequence U+1F469 U+200D U+1F4BB. It provides a concrete three-code-point emoji for distinguishing displayed text from its underlying sequence.

  75. MCP = Mega Context Problem - Matt Carey

    Creating and loading a separate tool for every API endpoint can make the tool descriptions themselves exceed a practical context budget.