Contents
  1. The sequence computation
    1. What a transformer computes
    2. The arrays and their parameters
    3. Why attention emerged
  2. Attention and sequence structure
    1. Supplying sequence order
    2. Matching and transmitted content
    3. Computing the attention update
    4. Restricting information access
    5. Relative position in matching
  3. Building contextual states
    1. Several mixtures in one layer
    2. The complete block
    3. Context across layers
    4. Three architecture families
  4. Prediction, training and generation
    1. Reading out vocabulary scores
    2. Predicting recorded successors
    3. Producing an unknown continuation
  5. Architectural reach and limits
    1. Reach, work and storage
    2. When longer context helps
    3. Interpreting attention patterns
  6. Tokenization: How Text Becomes the Units Models Learn and Generate
    1. Overview
  7. 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
  8. 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
  9. Reconstruction and source locations
    1. What decoding preserves
      1. Reconstruct bytes before characters
    2. Offsets need a coordinate system
      1. Name the coordinates
  10. Conversation structure
    1. Special tokens and chat templates
      1. Serialization is checkpoint-specific
      2. Three kinds of ending
      3. Do not format twice
  11. 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
  12. 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
  13. Check understanding
  14. Open questions
  15. Selected talks
  16. References
  17. Talk library
← All topics

Transformers & attention

A transformer is a model architecture that builds a numerical state for each element of a sequence using information from other elements. These contextual states support tasks such as predicting the next token or locating an answer in a passage. Following how information moves between positions explains why changing the input can change a prediction, and why supplying information does not guarantee that the model uses it correctly.

The sequence computation

What a transformer computes

Interpreting a sequence requires more than identifying its individual elements. In a sentence, nearby descriptions can change what a verb implies. A model therefore needs a contextual representation: a numerical state that depends on an element and the information available at its position. Attention builds such states by combining information across positions with weights that depend on the input.

For text, the starting elements are tokens, sequence units identified by integers. A token need not be a whole word; Tokenization explains how text becomes these IDs. A transformer converts the IDs into vectors, repeatedly transforms those vectors, and passes the resulting states to an output component. A language model produces scores for possible next tokens. Other models use contextual states for classification or locating an answer inside a passage.

A forward pass applies the model's operations to supplied inputs. During ordinary inference, its fitted parameters stay fixed while the intermediate states change with the input. Changing a passage can therefore change a prediction without retraining. This distinction will recur throughout the chapter: parameters specify learned transformations; the current sequence supplies the information those transformations process.

The arrays and their parameters

A vector is an ordered array of numerical coordinates. An embedding table stores one learned vector per vocabulary entry. If the vocabulary contains vv entries and each vector has dd coordinates, the table EE has shape v×dv\times d. A token ID selects a row; the magnitude of the ID has no feature meaning. Stacking the selected vectors for nn sequence positions produces a matrix XX of shape n×dn\times d.

For a small example, let the selected rows be E[2] = [1, −1] and E[7] = [0, 2]. The input IDs [2, 7, 2] produce:
Sequence positionToken IDSelected vector
02[1, −1]
17[0, 2]
22[1, −1]

Repeated IDs initially select identical rows. Their later states can differ once position and context enter. The table contains parameters, fitted numbers shared across inputs; the selected and transformed arrays are activations, intermediate values computed for this input. Their learned coordinates are not manually assigned labels such as tense or importance. Parameters and modeling assumptions explains the shared-parameter distinction; Vectors and coordinate spaces develops representation geometry.

A linear projection forms new coordinates from weighted sums of existing ones. A dot product multiplies corresponding coordinates and sums them: [1, −1] · [2, 3] = 2 − 3 = −1. In Y=XW+bY=XW+b, an n×dn\times d input and d×rd\times r weight matrix yield an n×rn\times r output; bb adds a learned offset. The same transformation applies separately to every row. It changes features without exchanging information between positions. Here weights use the mathematical XWXW convention; libraries may store them transposed.

Why attention emerged

Early neural translation systems made the information-access problem concrete. An encoder processes a source sequence; a decoder produces a target sequence. In a recurrent network, a numerical state passes from one position to the next. A decoder could receive a fixed-dimensional summary of the source, but that made the summary responsible for preserving everything subsequent predictions might need.

From source summaries to pretrained contextual states

  1. September 2014Sequence to Sequence LearningTwo recurrent networks encode a source into a fixed-dimensional summary and generate a target from it.Sources & context

    Contributors: Ilya Sutskever, Oriol Vinyals and Quoc Le, Google.

    What changed: Their five-model ensemble exceeded the reported non-neural English–French translation baseline; reversing source order helped. Fixed-summary models achieved useful results, including on long sentences. This work and learned alignment developed concurrently.

  2. September 2014 preprintBahdanau attentionEach target prediction forms its own weighted summary of contextual source states.Sources & context

    Contributors: Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio.

    What changed: Learned alignment supplied adaptive source access within recurrent translation. The September 2014 preprint preceded ICLR 2015 publication; the two 2014 approaches developed concurrently.

  3. June 2017TransformerReplaced recurrence with attention, parallelizing supplied sequence positions.Sources & context

    Contributors: Ashish Vaswani and colleagues.

    What changed: Demonstrated strong translation results.

  4. June 2018GPTGenerative pretraining makes a causal Transformer a reusable starting point for language-understanding tasks.Sources & context

    Contributors: Alec Radford and colleagues, OpenAI.

    What changed: The reported improvements followed task-specific training on labeled examples.

  5. October 2018 preprintBERTBidirectional pretraining builds token states from both left and right context.Sources & context

    Contributors: Jacob Devlin and colleagues, Google.

    What changed: Bidirectional Encoder Representations from Transformers introduced reusable contextual states. Conference publication followed in 2019.

Follow the concurrent recurrent approaches of 2014 through attention-centered sequence processing and reusable pretrained representations. Spacing is not to scale.

The useful thread is adaptive information access. Attention first complemented recurrence, then became the central interaction mechanism of a different architecture. Its matching rule, permitted sources and output use remain separate design choices.

Attention and sequence structure

Supplying sequence order

Array positions are visible to your program, but they do not automatically become features in its numerical transformations. With unrestricted attention and no positional signals, rearranging the input rows rearranges their output representations correspondingly. This is permutation equivariance. It does not mean the output array remains unchanged. The statement also does not cover arbitrarily rearranging tokens while holding a causal visibility pattern fixed.

One solution adds a position vector to each token vector. An absolute position is an index within the sequence. GPT-2 uses a learned position table distinct from its token table: position selects a row from one, token identity selects a row from the other, and their coordinates are added.

For symbolic tokens A and B, exchanging their positions changes the pairings:
Input orderState at position 0State at position 1
A, BE[A] + P[0]E[B] + P[1]
B, AE[B] + P[0]E[A] + P[1]

Position vectors can also be fixed: the original Transformer added sine/cosine patterns at different frequencies. GPT-2 instead learned them. Both supply position; neither addition determines permitted attention connections.

Matching and transmitted content

Attention separates deciding where to read from deciding what to transmit. A query scores candidate information. A key is the representation compared with that query. A value supplies content to the resulting mixture. Keys and values stay paired by source position, but serve different roles.

Self-attention projects the same sequence states separately into Q, K and V. Projection parameters are shared across inputs; these activations depend on the input. Omitting optional biases:

Q=XWQ,K=XWK,V=XWV.Q=XW_Q,\qquad K=XW_K,\qquad V=XW_V.

Different projections make permitted query–key comparisons directed: q_i · k_j need not equal q_j · k_i. The names denote numerical roles, not questions or database identifiers.

Matching functions were already a design choice in recurrent attention. Effective Approaches to Attention-based Neural Machine Translation, by Minh-Thang Luong, Hieu Pham and Christopher Manning at Stanford in September 2015, compared dot-product and learned compatibility functions, alongside global and local source access. Its improvements also involved feeding attention-informed states into subsequent decoding. Transformer attention adopts a particular matching-and-aggregation construction from this broader design space.

Computing the attention update

Each query–key dot product produces a compatibility score. Softmax exponentiates a row of scores and divides each result by their sum, yielding positive weights totaling one. Those weights multiply the corresponding value vectors, which are summed into one output vector per query. Attention therefore produces a mixture, rather than selecting only the highest-scoring source.

Dividing scores by dk\sqrt{d_k}, the square root of query/key width, counters variance growth under independent, zero-mean, unit-variance coordinates, avoiding sharply concentrated softmax weights with little sensitivity during learning.

S=QK⊤dk,Aij=eSij∑r=1seSir,O=AV.S=\frac{QK^\top}{\sqrt{d_k}},\qquad A_{ij}=\frac{e^{S_{ij}}}{\sum_{r=1}^{s}e^{S_{ir}}},\qquad O=AV. Here K⊤K^\top exchanges K's rows and columns. For each query i, softmax normalizes its scores across the s source positions; A_ij is the weight assigned to source j.
Ignoring batch and head axes, let L be the query count, s the source count and d_v the number of coordinates in each value:
ArrayShape
Queries Q; keys KL × d_k; s × d_k
Scores S; weights AL × s
Values V; output Os × d_v; L × d_v

For a numerical example, take scaled scores [0, 0] and values [2, 0] and [0, 4]. Exponentiation gives [1, 1]; normalization gives [0.5, 0.5]. The output is 0.5[2, 0] + 0.5[0, 4] = [1, 2]. Increasing one score redistributes weight across the row. The weights allocate content; they do not express confidence that the content is true.

Scores allocate weight; values supply content

Change a scaled score to redistribute attention. Change a value coordinate to alter the content being mixed.

Source 1
Weight 0.5
Source 2
Weight 0.5
Weighted output: [1, 2]
These example scaled scores give equal weights and output [1, 2]. Change a score to redistribute weight, or change a value to alter the output without changing weights. The controls change calculation inputs, not learned parameters.

Restricting information access

An attention mask specifies permitted query–source pairs. In causal self-attention, a position may read itself and earlier positions, but cannot read later ones. Its state can then predict the next token without seeing that target. A small learned attention weight is not a prohibition: the architecture must exclude the forbidden connection.

A=softmax⁡sources(S+M),Mij={0allowed,−∞excluded.A=\operatorname{softmax}_{\mathrm{sources}}(S+M),\qquad M_{ij}=\begin{cases}0&\text{allowed},\\-\infty&\text{excluded}.\end{cases} Exclusion precedes normalization. In the two-source example, excluding the second source changes weights to [1, 0] and the output to [2, 0]. At least one source must remain allowed per computed row.

Padding adds artificial fillers when batching unequal sequence lengths. A padding mask excludes those source positions; a causal mask excludes future connections. Combine the exclusions when both apply. Source masking does not itself discard padded query outputs or their losses. Boolean conventions also differ: True means allowed in PyTorch's scaled-dot-product attention interface, but excluded in MultiheadAttention's Boolean masks.

Causal visibility with a padded source

Example

The current position remains visible, while future inputs and padding are excluded for different reasons.

Allowed pairs include the diagonal

Green regions are allowed; orange regions are future sources; purple is padding. Text labels distinguish every region.

-0.750.3751.52.6253.75-0.750.12511.8752.75Source position (position)Query position (position)Allowed at query 0Allowed at query 1Allowed at query 2Future at query 0Future at query 1Excluded paddingAllowedAllowedAllowedFutureFuturePadding
  • 1. Allowed at query 0
  • 2. Allowed at query 1
  • 3. Allowed at query 2
  • 4. Future at query 0
  • 5. Future at query 1
  • 6. Excluded padding
Read coordinates and regions as data

X: -0.75–3.75 position; Y: -0.75–2.75 position, increasing down. Equal scale on both axes.

Allowed at query 0 (polygon)

(-0.45, -0.45); (0.45, -0.45); (0.45, 0.45); (-0.45, 0.45)

Allowed at query 1 (polygon)

(-0.45, 0.55); (1.45, 0.55); (1.45, 1.45); (-0.45, 1.45)

Allowed at query 2 (polygon)

(-0.45, 1.55); (2.45, 1.55); (2.45, 2.45); (-0.45, 2.45)

Future at query 0 (polygon)

(0.55, -0.45); (2.45, -0.45); (2.45, 0.45); (0.55, 0.45)

Future at query 1 (polygon)

(1.55, 0.55); (2.45, 0.55); (2.45, 1.45); (1.55, 1.45)

Excluded padding (polygon)

(2.55, -0.45); (3.45, -0.45); (3.45, 2.45); (2.55, 2.45)

Allowed: (0, 0)

Allowed: (0.5, 1)

Allowed: (1, 2)

Future: (1.5, 0)

Future: (2, 1)

Padding: (3, 1)

Positions 0–2 contain A, B and C; source 3 is padding. Query 1 predicts C but cannot read source 2. Only real query rows are shown.

Keep three decisions separate: position describes placement, attention masking controls access, and loss selection determines which predictions receive a training penalty. Removing a prediction from the loss does not stop another position from reading its input. Separate visibility from scoring develops this distinction.

Relative position in matching

Position can affect compatibility directly. Relative position describes the displacement between query and source indices. In T5, a learned scalar bias selected by that displacement is added to the attention score before softmax. Offsets are grouped into buckets, so multiple distances can share a bias. This differs from adding a vector to the initial token state: the positional term modifies a relationship between two positions.

Rotary Position Embedding, or RoPE, rotates pairs of projected query/key coordinates. Jianlin Su and colleagues introduced it in RoFormer in April 2021. For column vectors q and k, let R_m rotate a coordinate pair according to position m:

(Rmq)⊤(Rnk)=q⊤Rn−mk.(R_mq)^\top(R_nk)=q^\top R_{n-m}k. The positional term depends on displacement. Different coordinate pairs use different rotation frequencies.

A shared position shift preserves matching

Example

Both vectors rotate while their angle and dot product remain unchanged.

m=0, n=1

Relative displacement: 1.

-1.3-0.6500.651.3-1.3-0.6500.651.3First coordinate (dimensionless)Second coordinate (dimensionless)Rotated queryRotated keyQK
  • 1. Rotated query
  • 2. Rotated key
Read coordinates and regions as data

X: -1.3–1.3 dimensionless; Y: -1.3–1.3 dimensionless, increasing up. Equal scale on both axes.

Rotated query (polyline)

(0, 0); (1, 0)

Rotated key (polyline)

(0, 0); (0.6, 0.8)

Q: (1.05, -0.15)

K: (0.65, 1)

m=1, n=2

Same relative displacement.

-1.3-0.6500.651.3-1.3-0.6500.651.3First coordinate (dimensionless)Second coordinate (dimensionless)Rotated queryRotated keyQK
  • 1. Rotated query
  • 2. Rotated key
Read coordinates and regions as data

X: -1.3–1.3 dimensionless; Y: -1.3–1.3 dimensionless, increasing up. Equal scale on both axes.

Rotated query (polyline)

(0, 0); (0, 1)

Rotated key (polyline)

(0, 0); (-0.8, 0.6)

Q: (0.15, 1.1)

K: (-1, 0.75)

One illustrative coordinate pair: q=(1,0), k=(0.8,−0.6), rotation 90° per position. Shifting m,n together preserves dot product 0.6.

These mechanisms enter at different locations: absolute vectors alter initial states, scalar biases alter scores, and RoPE alters the vectors being compared. They still feed a weighted-value computation. Numerical precision matters in that path: Daniel Han describes a reduced-precision implementation in which distinct large position indices collapsed to the same value, losing positional distinctions. A mathematically suitable representation still needs faithful numerical execution.

Building contextual states

Several mixtures in one layer

Each attention head separately projects Q/K/V and computes weights. Concatenating h mixtures of shape n×dvn\times d_v gives n×(hdv)n\times(hd_v); learned projection restores width d. Conventionally, dv=d/hd_v=d/h.

The same sequence positions participate in every head. What varies is their projected representation and resulting allocation of attention. Heads therefore offer multiple learned interaction patterns within one layer; they are not separate complete language models. In Ishan Anand's spreadsheet demonstration, one head shows an interpretable pronoun–antecedent pattern, while others lack such an obvious reading. A head receives no guaranteed linguistic job title.

The study Are Sixteen Heads Really Better than One? removed heads from trained translation and BERT models. Many removals had little effect, while some encoder–decoder attention layers relied substantially on multiple heads. Head count alone therefore does not establish how many indispensable functions a model learned. Pruning a trained model also differs from training a smaller model from the outset.

The complete block

Attention supplies an update, but a block also needs to preserve and transform the state receiving it. A residual connection adds a branch's result to its input: y=x+F(x)y=x+F(x). Matching dimensions make this elementwise addition possible. The identity path lets the branch learn a correction to an existing representation. It neither guarantees a small correction nor skips execution of the branch. Deep Residual Learning established this construction in deep image networks.

Layer normalization, or LayerNorm, controls feature scale separately at each position: it subtracts the vector's coordinate mean, divides by its standard deviation with a numerical safeguard, then applies learned scale and bias. Pre-normalization places this operation before each transformed branch; post-normalization places it after residual addition. One pre-normalization block is:

U=X+Attention⁡(LayerNorm⁡(X)),Y=U+FFN⁡(LayerNorm⁡(U)).U=X+\operatorname{Attention}(\operatorname{LayerNorm}(X)),\qquad Y=U+\operatorname{FFN}(\operatorname{LayerNorm}(U)). X, U and Y retain shape n × d. The residual paths carry the accumulated state around the normalized branches.

A feed-forward network, or FFN, transforms each position independently using shared parameters. A common version, also called a multilayer perceptron or MLP, applies two affine transformations separated by a nonlinear activation. The intervening nonlinearity prevents the pair from collapsing into one affine transformation. In nanoGPT, feature width expands from d to 4d and returns to d. Attention mixes positions; this network processes features at each position.

Two updates to the carried state

Normalization belongs to each transformed branch; residual additions preserve a direct path.

Input X: n × d
LayerNormAttention branch
Multi-head attentionAcross positions
Add → U: n × d
LayerNormFFN branch
Feed-forward networkWithin each position
Add → Y: n × d
A pre-normalization block. Attention exchanges information across positions; LayerNorm and FFN operate per position. Both additions preserve n × d.
Read the diagram as text
  • Input X: n × d.
  • LayerNorm. Attention branch
  • Multi-head attention. Across positions
  • Add → U: n × d.
  • LayerNorm. FFN branch
  • Feed-forward network. Within each position
  • Add → Y: n × d.
  • Input X: n × d → LayerNorm: Branch input.
  • LayerNorm → Multi-head attention: Normalized states.
  • Multi-head attention → Add → U: n × d: Attention update.
  • Input X: n × d → Add → U: n × d: Identity path.
  • Add → U: n × d → LayerNorm: Branch input.
  • LayerNorm → Feed-forward network: Normalized states.
  • Feed-forward network → Add → Y: n × d: Feature update.
  • Add → U: n × d → Add → Y: n × d: Identity path.

Normalization variants change the branch computation. Root mean square normalization, or RMSNorm, divides by a scale derived from the average squared coordinate and applies learned gains; unlike LayerNorm, it does not subtract the mean. LLaMA, documented by Hugo Touvron and colleagues at Meta AI in February 2023, combines input normalization using RMSNorm with RoPE. This is a concrete block variant, not evidence that either choice alone explains its performance.

When reading code, locate both addition points and inspect what each branch receives. Training an LLM from Scratch, Locally makes the central change explicit: replacing X with an attention result differs from adding that result to X.

Context across layers

Stacking blocks composes learned transformations. Later queries, keys and values come from states that earlier blocks have already contextualized. Blocks repeat an operation pattern, but normally have distinct parameters. GPT-2 Small, for example, uses twelve separately parameterized blocks; depth does not mean repeatedly applying one shared set of weights.

Consider a permitted dependency: position 0 contributes to position 1 in one layer, then position 1 contributes to position 2 in the next. The second interaction can transmit information originating at position 0. Under a causal mask, each edge travels from an equal or earlier source position, so composing edges cannot create access to a future token. Feature transformations and residual additions process what those interactions deliver.

The accumulated per-position state is often called the residual stream. For the same token at the same position in two different prefixes, its initial lookup vector can remain identical while subsequent states differ. This input sensitivity under fixed parameters enables prompting and in-context learning. A token state is also distinct from a deliberately constructed whole-item embedding.

Depth and generation count are separate dimensions. Passing through another block refines representations within one forward pass; it does not append another token. An inspection technique called a logit lens applies the model's output mapping to intermediate states, turning them into scores for candidate vocabulary tokens. This reveals how candidate rankings change across layers, but does not establish a universal sequence of linguistic stages or a complete causal explanation.

Three architecture families

The same components support different information paths and outputs:
FamilyInformation accessTypical readout
Encoder-onlySupplied context on both sidesClassification or passage boundaries
Decoder-onlyCurrent position and preceding prefixNext-token scores
Encoder–decoderEncoded source plus causal target prefixConditional target generation

Cross-attention matches target queries to source keys/values: target-by-source weights. The original decoder orders masked self-attention → cross-attention → FFN, each followed by residual addition and LayerNorm.

A decoder-only model such as early GPT removes the need for a separate source encoder and cross-attention path. Its causal blocks build representations for predicting successive tokens. The original GPT work also used these representations for supervised downstream tasks, showing that a causal architecture was useful beyond producing free-running continuations.

BERT builds states from both left and right context. Its added classification token, CLS, supplies a final state for classification; another output head predicts answer boundaries in a passage. Pretraining predicts selected corrupted tokens, so this visibility need not expose unchanged answers. Compared with a left-context-only model, BERT improved the reported development-task results, but the experiment changed both visibility and objective. Changing a trained model's mask alone would not reproduce it.

Architecture identifies the information path, not every interface convention. Models sharing a family can require different chat templates, normalization operations and positional handling. A reusable runtime must preserve the computation expected by each checkpoint.

Prediction, training and generation

Reading out vocabulary scores

An output head maps contextual states to task predictions. For next-token generation, the language-model head reads the state at the last input position, after the final block and normalization, and projects it to one score per vocabulary entry. These unnormalized scores are logits. The state supplies features for this scoring operation; choosing a token from the scores is a separate step.

z=hWout+b,pj=ezj∑r=1vezr.z=hW_{\mathrm{out}}+b,\qquad p_j=\frac{e^{z_j}}{\sum_{r=1}^{v}e^{z_r}}. Here h is a final normalized width-d row, W_out has shape d × v, z contains vocabulary logits, and p_j is the next-token probability for vocabulary entry j.
Softmax appears twice, with different meanings:
LocationNormalized axisMeaning
AttentionPermitted source positionsCoefficients for a value mixture
Language headVocabulary entriesProbabilities for the next token

Some models tie the output weights to the input embedding table. In GPT-2's JavaScript walkthrough, the final state is dotted with each embedding row. This is often called unembedding, but it does not invert the preceding contextual transformations. The demonstration selects the largest logit; softmax would preserve that ranking.

These probabilities describe possible next tokens under the model. They do not certify that a statement assembled from those tokens is factually supported.

Predicting recorded successors

During training, a recorded sequence supplies reference predecessors and correct successors. Teacher forcing means conditioning a prediction on those recorded predecessors rather than on the model's earlier sampled choices. A loss penalizes predictions against their targets. The model can calculate many such predictions together because their reference inputs are already known.

For the symbolic recorded sequence [A, B, C, D], inputs [A, B, C] align with targets [B, C, D]:
PositionInputPermitted prefixTarget
0AAB
1BA, BC
2CA, B, CD

B is both position 0's target and position 1's input. That is safe because position 0 cannot read position 1, directly or through later layers. Target shifting establishes which answer belongs to each prediction; causal masking separately enforces the information boundary. Omitting either can produce the wrong training problem.

Positions can be processed together within a layer, while the next layer still depends on the preceding layer's results. Loss computation and parameter updates are subsequent operations. A token omitted from loss can still supply context—for example, instruction tuning can score response tokens while retaining the prompt as input. Build targets from text explains objective construction beyond this alignment.

Producing an unknown continuation

Autoregressive generation repeatedly predicts from an existing prefix, selects a token, and appends it. Greedy selection chooses a maximum-probability token; sampling draws according to a selection distribution. The chosen token becomes part of the next input, so later predictions depend on earlier selections.

For a symbolic example, a model receives [A, B] and a selection yields C. The next prediction receives [A, B, C]; suppose its selection yields D. The second input could not be assembled before C was chosen. Training instead already has the reference C. Both processes use the same kind of forward computation, but only training performs a parameter update.

Generation ends when a stopping condition is met, such as an end-of-sequence token, a configured stop string or an output-length limit. A length cutoff can interrupt an unfinished answer; stopping does not certify completeness or correctness. Selection and stopping covers decoding controls, while Reconstructing generated text explains converting IDs back into text.

A key–value cache retains per-layer K and V activations. Under causal attention, appending tokens cannot change earlier states, so their projections can be reused when the prefix, parameters and positional treatment remain compatible. Processing the newly appended token computes its Q/K/V, adds its K/V to the cache, and uses its query to read retained history. Caching avoids recomputing earlier states; ordinary full-history attention still does work over the retained sources. See What the KV cache retains.

At each layer, processing C adds its key and value to retained rows A and B. Its query still attends over the available history. Reuse requires compatible prefix, positions and parameters.

Architectural reach and limits

Reach, work and storage

Dense attention compares every query with every permitted source. For N positions, unrestricted attention has N² pairs; diagonal-inclusive causal attention has N(N+1)/2. Both grow quadratically. At fixed feature widths, projections and per-position feed-forward work instead grow linearly with position count. These are operation counts, not predictions of complete-model latency.

Exact pair counts for two example lengths:
PositionsUnrestrictedCausal
41610
86436

Longformer combines local windows, restricting reads to neighbors, with global positions that read and are readable everywhere. Layers expand the receptive field—inputs influencing a state. Fixed window width and global-position count give linear interaction growth, without reproducing dense attention. This bidirectional pattern needs modification for causal decoding.

FlashAttention preserves dense attention while avoiding storage of the complete score matrix. Its exact algorithm retains quadratic arithmetic, with linear additional memory at fixed head width; floating-point results can differ. Restricting connections and changing storage are therefore different interventions.

If a fixed checkpoint must preserve dense outputs and arithmetic is affordable, removing connections changes the computation you intended to preserve. An implementation that avoids large intermediates addresses the storage problem directly. Online state and tiled attention explains that mechanism. Execution limits and Road to 5 Million Tokens connect sequence growth to practical bottlenecks.

Tiled dense attention retains every permitted pair while changing intermediate storage, with equivalent mathematics up to floating-point differences. Sparse attention changes the connections themselves. The bidirectional grid is a small schematic; running normalization combines all tiles.

When longer context helps

A context window describes a supported sequence allowance. Counting complete requests explains what consumes it. Allocating additional cache slots does not extend a model's positional support. Conversely, a windowed layer can retain only recent states while processing a longer overall sequence. Storage capacity and sequence support answer different questions.

Length extrapolation evaluates beyond training lengths without further adaptation. Attention with Linear Biases, or ALiBi, adds a distance penalty with a fixed slope per head before softmax. Its controlled WikiText-103 experiments showed stronger extrapolation than the compared positional methods. The measure was perplexity—next-token predictive fit—not arbitrary answer accuracy. A position formula being computable at an unseen index does not establish reliable use there.

Position Interpolation instead rescales positions into a pretrained RoPE model's original range and then fine-tunes it. Its historical LLaMA experiments extended a 2,048-token window to as much as 32,768, evaluating language modeling, retrieval and summarization. This was adaptation, not unchanged-checkpoint extrapolation; some original-window benchmarks degraded. Extending the accepted range and retaining earlier capabilities both need assessment.

Even within an accepted window, available evidence can be used unevenly. Lost in the Middle moved relevant information within multi-document question-answering and key-value retrieval inputs. Several tested models performed better with evidence near the beginning or end than in the middle, with results depending on model and task. The controlled variable was evidence placement; this was not proof of a universal position curve or of literal deletion of middle tokens.

RULER extends single-item retrieval tests to variable-chain tracing, aggregation and question answering with distractors. In its evaluated models, success at simple retrieval could coexist with deterioration on harder long-context tasks. Effective context length therefore needs a task, scoring rule and performance threshold. Test the operations your application requires, with workload coverage and input arrangement treated explicitly.

Interpreting attention patterns

An attention map displays mixing coefficients for one input, head and layer. Contribution also depends on the values and output projection. For a scalar example of transformed contributions, weights [0.9, 0.1] multiplying values [0.01, 10] yield contributions [0.009, 1]. The smaller weight contributes more. Attention is Not Only a Weight found analogous distinctions in BERT: some heavily attended special tokens and punctuation had comparatively small transformed-vector contributions. Neither contribution size nor coefficient size alone establishes the final prediction's cause.

Attention is not Explanation, by Sarthak Jain and Byron Wallace in 2019, challenged direct interpretation of attention weights. In recurrent-model experiments, weights aligned inconsistently with gradient or token-removal measures, and substantially different attention distributions could preserve nearly identical predictions. These results concern the studied models and tests; they do not directly measure modern Transformer stacks.

Attention is not not Explanation, Sarah Wiegreffe and Yuval Pinter's 2019 response, examined uniform baselines, variation across initializations and transferred attention distributions. Their recurrent-model results supported testing whether an interpretation is useful in a particular setting rather than accepting a universal verdict. The disagreement helps distinguish a visible pattern from a carefully specified explanation claim.

An ablation removes or disables a component and measures the resulting behavior. Head-removal experiments test dependence under that intervention and on those inputs. They do not assign an immutable purpose to the head.

For implementation diagnosis, controlled dependencies can be more decisive than a heatmap. With identical parameters, earlier tokens and positions, changing only a future token should not change an earlier causal prediction beyond numerical tolerance when randomness is disabled. An observed change justifies investigating an unintended information path. Comparing intermediate outputs layer by layer can locate where implementations first diverge; changing the sampling rule or which targets receive loss does not repair that forward-pass dependency.

Tokenization: How Text Becomes the Units Models Learn and Generate

Overview

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. Reliable length transfer remains difficult because positional adaptation and task competence can change separately. Progress would preserve short-input capabilities while improving retrieval and multi-step use of longer inputs under controlled comparisons.

  2. Which sparse connections preserve necessary dependencies across workloads? Pair counts alone cannot establish usefulness.

  3. Faithful explanations must connect intermediate mixtures to downstream behavior despite interacting components. Progress would produce interpretations that predict controlled intervention outcomes on new inputs, with explicit limits on their scope.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

21 matching talks

Every catalogued talk on this subject: Infrastructure & deployment →

TalkSpeakerEventYear
Ishan AnandAI Engineer World's Fair 20242024
Isaac RobinsonAI Engineer Europe 20262026
Phoebe KlettAI Engineer World's Fair 20242024
Diego CarpinteroAI Engineer Europe 20262026
Filip MakraduliAI Engineer World's Fair 20252025
Mark MoyouAI Engineer World's Fair 20242024
Rémi LoufAI Engineer World's Fair 20242024
Devendra Chaplot, Devendra Singh ChaplotAI Engineer World's Fair 20242024
Nupur SharmaAI Engineer Europe 20262026
Leo PekelisAI Engineer World's Fair 20242024
Gagan Bhat, Isabella Kai HeAI Engineer World's Fair 20262026
Kyle KranenAI Engineer World's Fair 20252025
Skills are the New SDKs

Transcript reviewed

Elvin AghammadzadaAI Engineer World's Fair 20262026
AI Engineering 101

Cited in this entry

Noah HeinAI Engineer Summit 20232023
Jamie Neuwirth, Zack WittenAI Engineer World's Fair 20242024
Philipp KrennAI Engineer World's Fair 20252025
Yesu FengAI Engineer World's Fair 20252025
Olive SongEvent unknownUnknown
Freddy LecueEvent unknownUnknown
Thomas Wolf, Olive SongEvent unknownUnknown
Morgan SuoEvent unknownUnknown

References

Coverage and source review
Processed transcripts
20 processed in full · 6 in the curated path
Automated source review
Passed
Metadata candidates
7 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. Spreadsheets-are-all-you-need: Decoding the Decoder LLM without de code

    https://www.youtube.com/watch?v=NamKkerrlnQ&t=403

  2. PyTorch MultiheadAttention

    https://docs.pytorch.org/docs/2.13/generated/torch.nn.modules.activation.MultiheadAttention.html

  3. nanoGPT train.py

    https://raw.githubusercontent.com/karpathy/nanoGPT/master/train.py

  4. RoFormer: Enhanced Transformer with Rotary Position Embedding

    https://arxiv.org/html/2104.09864v5

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=3669

  6. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=1933

  7. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    https://aclanthology.org/N19-1423.pdf

  8. Optimizing LLMs for Speed and Memory

    https://huggingface.co/docs/transformers/main/en/llm_tutorial_optimization

  9. PyTorch Embedding

    https://docs.pytorch.org/docs/2.13/generated/torch.nn.modules.sparse.Embedding.html

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=2846

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=2424

  12. Linear — PyTorch documentation

    https://docs.pytorch.org/docs/main/generated/torch.nn.Linear.html

  13. Sequence to Sequence Learning with Neural Networks

    https://arxiv.org/pdf/1409.3215

  14. Neural Machine Translation by Jointly Learning to Align and Translate

    https://arxiv.org/pdf/1409.0473

  15. Attention Is All You Need

    https://arxiv.org/html/1706.03762v7

  16. Attention Is All You Need

    https://arxiv.org/html/1706.03762v7

  17. Improving Language Understanding by Generative Pre-Training

    https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf

  18. Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks

    https://proceedings.mlr.press/v97/lee19d/lee19d.pdf

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=3150

  20. Attention Pooling by Similarity — Dive into Deep Learning

    https://d2l.ai/chapter_attention-mechanisms-and-transformers/attention-pooling.html

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=4500

  22. Attention Is All You Need

    https://arxiv.org/html/1706.03762

  23. Effective Approaches to Attention-based Neural Machine Translation

    https://aclanthology.org/D15-1166.pdf

  24. PyTorch scaled_dot_product_attention

    https://docs.pytorch.org/docs/2.13/generated/torch.nn.functional.scaled_dot_product_attention.html

  25. Low Level Technicals of LLMs

    https://www.youtube.com/watch?v=pRM_P6UfdIc&t=2270

  26. Decoding Mistral AI's Large Language Models

    https://www.youtube.com/watch?v=AUuktOQPWYg&t=698

  27. Low Level Technicals of LLMs

    https://www.youtube.com/watch?v=pRM_P6UfdIc&t=3658

  28. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer

    https://www.jmlr.org/papers/volume21/20-074/20-074.pdf

  29. RoFormer: Enhanced Transformer with Rotary Position Embedding

    https://arxiv.org/pdf/2104.09864v1

  30. Low Level Technicals of LLMs

    https://www.youtube.com/watch?v=pRM_P6UfdIc&t=4408

  31. Low Level Technicals of LLMs

    https://www.youtube.com/watch?v=pRM_P6UfdIc&t=8779

  32. Are Sixteen Heads Really Better than One?

    https://arxiv.org/pdf/1905.10650

  33. Deep Residual Learning for Image Recognition

    https://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/He_Deep_Residual_Learning_CVPR_2016_paper.pdf

  34. On Layer Normalization in the Transformer Architecture

    https://proceedings.mlr.press/v119/xiong20b/xiong20b.pdf

  35. nanoGPT model.py

    https://raw.githubusercontent.com/karpathy/nanoGPT/master/model.py

  36. Root Mean Square Layer Normalization

    https://papers.neurips.cc/paper_files/paper/2019/file/1e8a19426224ca89e83cef47f1e7f53b-Paper.pdf

  37. LLaMA: Open and Efficient Foundation Language Models

    https://arxiv.org/pdf/2302.13971

  38. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=2300

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=4594

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

    https://www.youtube.com/watch?v=NamKkerrlnQ&t=567

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

    https://www.youtube.com/watch?v=NamKkerrlnQ&t=608

  42. Improving Language Understanding by Generative Pre-Training

    https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf

  43. Attention Is All You Need

    https://arxiv.org/html/1706.03762v7

  44. Attention Is All You Need — Figure 1 decoder architecture

    https://arxiv.org/html/1706.03762v7

  45. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    https://aclanthology.org/N19-1423.pdf

  46. The Small Model Infrastructure Nobody Built (So We Did) — Filip Makraduli, Superlinked

    https://www.youtube.com/watch?v=qdh_x-uRs9g&t=687

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=4748

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

    https://www.youtube.com/watch?v=NamKkerrlnQ&t=520

  49. Text generation — Hugging Face Transformers

    https://huggingface.co/docs/transformers/llm_tutorial

  50. Transformers T5 documentation: Training

    https://huggingface.co/transformers/v3.5.1/model_doc/t5.html

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=738

  52. Transformers GenerationConfig: stopping and output budgets

    https://huggingface.co/docs/transformers/main_classes/text_generation

  53. Transformers: why causal KV caching works

    https://huggingface.co/docs/transformers/en/cache_explanation

  54. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

    https://arxiv.org/pdf/2205.14135

  55. Longformer: The Long-Document Transformer

    https://arxiv.org/pdf/2004.05150

  56. Road to 5 Million Tokens: Breaking Barriers in Long Context Training — Max Ryabinin, Together AI

    https://www.youtube.com/watch?v=TUnPNY4E2fw&t=237

  57. Transformers: cache allocation versus retained history

    https://huggingface.co/docs/transformers/en/kv_cache

  58. Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation

    https://ofir.io/train_short_test_long.pdf

  59. Extending Context Window of Large Language Models via Position Interpolation

    https://arxiv.org/html/2306.15595v2

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

    https://arxiv.org/html/2307.03172v3

  61. RULER: What's the Real Context Size of Your Long-Context Language Models?

    https://arxiv.org/html/2404.06654v3

  62. Attention is Not Only a Weight: Analyzing Transformers with Vector Norms

    https://aclanthology.org/2020.emnlp-main.574.pdf

  63. Attention is not Explanation

    https://aclanthology.org/N19-1357.pdf

  64. Attention is not not Explanation

    https://aclanthology.org/D19-1002.pdf

  65. Low Level Technicals of LLMs

    https://www.youtube.com/watch?v=pRM_P6UfdIc&t=7547

  66. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=2170

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=946

  68. $1 AI Guardrails: The Unreasonable Effectiveness of Finetuned ModernBERTs – Diego Carpintero

    https://www.youtube.com/watch?v=YZHPEkfy2kc&t=1511

  69. $1 AI Guardrails: The Unreasonable Effectiveness of Finetuned ModernBERTs – Diego Carpintero

    https://www.youtube.com/watch?v=YZHPEkfy2kc&t=1378

  70. Why More Context Makes Your Agent Dumber and What to Do About It

    https://www.youtube.com/watch?v=EcqMYoIV57A&t=191

  71. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=3197

  72. Road to 5 Million Tokens: Breaking Barriers in Long Context Training — Max Ryabinin, Together AI

    https://www.youtube.com/watch?v=TUnPNY4E2fw&t=368

  73. Hugging Face: Tokenizers

    https://huggingface.co/learn/llm-course/en/chapter2/4

  74. Tokenization algorithms — Transformers

    https://huggingface.co/docs/transformers/tokenizer_summary

  75. OpenAI Cookbook: How to count tokens with Tiktoken

    https://developers.openai.com/cookbook/examples/how_to_count_tokens_with_tiktoken

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=2016

  77. Attention Is All You Need

    https://arxiv.org/html/1706.03762v7

  78. Unicode Glossary

    https://www.unicode.org/glossary/

  79. Unicode Standard Annex #29: Unicode Text Segmentation

    https://www.unicode.org/reports/tr29/

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

    https://www.unicode.org/faq/utf_bom.html

  81. Unicode normalization charts: Latin

    https://www.unicode.org/charts/normalization/chart_Latin.html

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

    https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/

  83. Unicode Standard Annex #15: Unicode Normalization Forms

    https://unicode.org/reports/tr15/

  84. Hugging Face Tokenizers: The tokenization pipeline

    https://huggingface.co/docs/tokenizers/en/pipeline

  85. tiktoken 0.11.0: encoding definitions

    https://raw.githubusercontent.com/openai/tiktoken/0.11.0/tiktoken_ext/openai_public.py

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=1219

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

    https://www.youtube.com/watch?v=NamKkerrlnQ&t=149

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

    https://aclanthology.org/2022.tacl-1.17.pdf

  89. SentencePiece configuration options

    https://github.com/google/sentencepiece/blob/master/doc/options.md

  90. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=594

  91. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=298

  92. Philip Gage: A New Algorithm for Data Compression

    https://jacobfilipp.com/DrDobbs/articles/CUJ/1994/9402/gage/gage.htm

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

    https://research.google/blog/excellent-papers-for-2012/

  94. Neural Machine Translation of Rare Words with Subword Units

    https://aclanthology.org/P16-1162.pdf

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

    https://aclanthology.org/D18-2012.pdf

  96. tiktoken educational byte-pair encoding implementation

    https://raw.githubusercontent.com/openai/tiktoken/main/tiktoken/_educational.py

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=1382

  98. Neural Machine Translation of Rare Words with Subword Units

    https://aclanthology.org/P16-1162.pdf

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

    https://www.youtube.com/watch?v=ZuiJjkbX0Og&t=1408

  100. BERT original WordPiece tokenizer implementation

    https://raw.githubusercontent.com/google-research/bert/master/tokenization.py

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

    https://aclanthology.org/P18-1007.pdf

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

    https://aclanthology.org/P18-1007.pdf

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

    https://arxiv.org/html/1609.08144v2

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

    https://research.google/blog/a-neural-network-for-machine-translation-at-production-scale/

  105. Transformers Tokenizer API

    https://huggingface.co/docs/transformers/main_classes/tokenizer

  106. tiktoken Encoding API implementation

    https://raw.githubusercontent.com/openai/tiktoken/main/tiktoken/core.py

  107. tiktoken encoding regression tests

    https://raw.githubusercontent.com/openai/tiktoken/main/tests/test_encoding.py

  108. Python codecs: Incremental Encoding and Decoding

    https://docs.python.org/3.13/library/codecs.html

  109. Claude Platform: Streaming messages

    https://platform.claude.com/docs/en/build-with-claude/streaming

  110. Utilities for Generation: TextStreamer and TextIteratorStreamer

    https://huggingface.co/docs/transformers/internal/generation_utils

  111. Language Models are Unsupervised Multitask Learners

    https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf

  112. Transformers: greedy and sampled token selection

    https://huggingface.co/docs/transformers/en/generation_strategies

  113. Hugging Face Tokenizers: NormalizedString implementation and alignment tests

    https://raw.githubusercontent.com/huggingface/tokenizers/main/tokenizers/src/tokenizer/normalizer.rs

  114. Transformers: Utilities for Tokenizers

    https://huggingface.co/docs/transformers/internal/tokenization_utils

  115. Transformers: model-specific chat serialization

    https://huggingface.co/docs/transformers/en/chat_templating

  116. Chat templates — Transformers

    https://huggingface.co/docs/transformers/chat_templating

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

    https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/blob/b54db9339734a22dd2b55531bd8146540729fbb8/tokenizer_config.json

  118. Llama 3.3 Prompt Formats

    https://github.com/meta-llama/llama-models/blob/main/models/llama3_3/prompt_format.md

  119. Transformers GenerationConfig: output reservation and termination

    https://huggingface.co/docs/transformers/en/main_classes/text_generation

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

    https://www.youtube.com/watch?v=TKmfBnW0mQA&t=162

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

    https://www.youtube.com/watch?v=TKmfBnW0mQA&t=344

  122. SFT Trainer: objective, shifting, and masking

    https://huggingface.co/docs/trl/sft_trainer

  123. Language Model Tokenizers Introduce Unfairness Between Languages

    https://proceedings.neurips.cc/paper_files/paper/2023/file/74bb24dca8334adce292883b4b651eda-Paper-Conference.pdf

  124. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=807

  125. Training an LLM from Scratch, Locally

    https://www.youtube.com/watch?v=UsB70Tf5zcE&t=1400

  126. Language Model Tokenizers Introduce Unfairness Between Languages

    https://proceedings.neurips.cc/paper_files/paper/2023/file/74bb24dca8334adce292883b4b651eda-Paper-Conference.pdf

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

    https://aclanthology.org/2021.acl-long.243.pdf

  128. OpenAI API: Counting tokens

    https://developers.openai.com/api/docs/guides/token-counting

  129. CUTE: Measuring LLMs’ Understanding of Their Tokens

    https://aclanthology.org/2024.emnlp-main.177.pdf

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

    https://arxiv.org/html/2508.02591v1

  131. Transformers: chat templates serialize conversation history

    https://huggingface.co/docs/transformers/chat_templating

  132. Understanding and counting tokens — OpenAI

    https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them

  133. AI Engineering 101

    https://www.youtube.com/watch?v=C0ZUdFg-iTo&t=3017

  134. Claude Platform: Token counting

    https://platform.claude.com/docs/en/build-with-claude/token-counting

  135. Transformers LlamaConfig: supported sequence positions

    https://huggingface.co/docs/transformers/en/model_doc/llama

  136. Conversation state: managing the context window — OpenAI

    https://developers.openai.com/api/docs/guides/conversation-state

  137. Claude context windows and cached-token accounting

    https://platform.claude.com/docs/en/build-with-claude/context-windows

  138. Padding and truncation — Transformers

    https://huggingface.co/docs/transformers/main/pad_truncation

  139. Claude Platform: Stop reasons and fallback

    https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons

  140. Claude Platform: Pricing

    https://platform.claude.com/docs/en/about-claude/pricing

  141. Claude Platform: Prompt caching

    https://platform.claude.com/docs/en/build-with-claude/prompt-caching

  142. GenAI-Perf: latency and throughput measurement

    https://github.com/triton-inference-server/perf_analyzer/tree/main/genai-perf

  143. Byte Latent Transformer: Patches Scale Better Than Tokens

    https://arxiv.org/html/2412.09871v1

  144. Unicode Emoji 15.1: emoji ZWJ sequences

    https://www.unicode.org/Public/emoji/15.1/emoji-zwj-sequences.txt

  145. MCP = Mega Context Problem - Matt Carey

    https://www.youtube.com/watch?v=YBYUvGOuotE&t=190