Skip to the content

fatehi.devx2Learning

Deep learning

Tokens and embeddings

How a text becomes the vectors a model computes with: it is cut into tokens, each token’s id picks a row of the embedding matrix, and a special token can hold the place of an input that is not text.

A model computes with vectors, not words: this is how a text becomes those vectors, and how a prompt can hold a place for an input that is not text.

A model reads numbers, not words

A language model is a mathematical function: numbers go in, numbers come out, and in between they pass through matrix multiplications, additions and non-linear functions such as the softmax and the activation functions of neural networks. Every step works on numbers, so before a model can do anything with a sentence, the sentence has to become numbers. This page follows that conversion from the start: how a text is cut into tokens, how each token gets a number, and how that number becomes the vector the model actually computes with.

Begin with the question of where to cut. Suppose we cut a text into single characters. The vocabulary would be tiny, a few hundred characters, but every text would become very long, and a single character such as “e” tells the model almost nothing on its own. Suppose instead we cut it into whole words. Now each unit carries meaning, but the vocabulary would have to contain every word of every language, and a word the model never met in training, a new name or a typo, would have no entry at all.

Language models take a middle path. A program called a tokenizer cuts the text into tokens: common words stay whole, and rare words are spelled out from smaller tokens that occur often elsewhere. “the” is one token, “reads” may be two tokens, “read” and “s”, and an unusual word may take four or five. The set of all tokens a tokenizer knows is its vocabulary, usually some tens of thousands to a few hundred thousand tokens, and every token in the vocabulary has a fixed number, its id. After tokenization, a sentence is a list of ids. The figure below shows this for a short sentence: six tokens, six ids.

An id is only a label: token 10 is not “more” than token 2 in any useful sense. So the model’s second step replaces each id by a vector, a list of a few thousand numbers. These vectors are stored in a table, the embedding matrix, which has one row for every token in the vocabulary; the id says which row to read. That row is the token’s embedding. Nobody writes these numbers by hand. They start out random and are adjusted while the model is trained, and tokens that are used in similar ways end up with similar embeddings.

Two consequences are worth keeping in mind. First, the lookup ignores context: the token “bank” gets the same embedding in “river bank” and in “bank account”. Telling the two apart is the work of the layers that come after the lookup, above all attention. Second, the list of embeddings is all the model ever sees of the text: whatever did not survive tokenization and lookup does not exist for the model.

Follow one token through the lookup. The tokenizer cuts “a model reads the DNA” into six tokens; the word “reads” becomes two of them, “read” and “s”. Take “model”: it has the id 10, so the model reads row 10 of the embedding matrix E, and that row is the token’s embedding. This toy vocabulary has 30 tokens and its embeddings have 6 numbers, filled in at random; a real model’s embedding matrix has a row for each of its tens or hundreds of thousands of tokens, and a few thousand numbers in each row. A ␣ marks a space that belongs to the token.

Cutting a text into tokens

How does a tokenizer decide which tokens to keep? The most widely used answer is byte-pair encoding, or BPE (Sennrich, Haddow and Birch, 2016). BPE learns its vocabulary from a large collection of text, its training text, before the language model itself is trained. The idea is simple: start from single characters, and again and again join the pair of neighbouring tokens that occurs most often.

Watch it on a small example. Suppose the training text contains the words “low”, “lower” and “lowest” many times. At the start, every word is spelled in characters: l o w, l o w e r, l o w e s t. BPE counts every pair of neighbouring tokens. The pair “l o” occurs in all three words, so it becomes a new token, “lo”. Counting again, “lo w” is now the most frequent pair, and “low” becomes a token. A few steps later “er” is a token too, and “lower” is written as two tokens, “low” and “er”. Each of these joins is called a merge. BPE stops after a number of merges chosen in advance, and the tokens it has built by then form the vocabulary. Frequent words end up as a single token; rare words stay split into smaller tokens.

Two details make this work in practice. Merges never join tokens across the boundary between two words, and the tokenizer marks where each word begins or ends, so that the text can be put back together exactly from its tokens. And to tokenize a new text, the tokenizer applies the merges it has learned, in the order in which it learned them. The cell Byte-pair encoding, learned from a small text, under Try it, runs the whole procedure, so you can watch the vocabulary grow merge by merge.

One problem remains: a character that never appeared in the training text, an emoji or a letter from another alphabet, has no token. Byte-level BPE, introduced for GPT-2 (Radford et al., 2019), solves this by working on bytes instead of characters. A computer stores text with the Unicode standard, usually in its UTF-8 encoding, which writes every character as one to four bytes: a Latin letter such as “a” takes one byte, “é” two, a Chinese character three and most emoji four. There are only 256 possible bytes, so if those 256 bytes are the starting tokens, every text can be tokenized, in the worst case byte by byte.

From there BPE merges bytes exactly as it merged characters. The two bytes of “é” occur together so often that they soon become one token; a common Chinese character becomes one token after two merges; a rare emoji may stay split into its four bytes. A token can therefore hold only part of a character. That does no harm, because the model reads and writes tokens, and the bytes are turned back into characters only when a text is shown. GPT-2 adds one rule: before merging, the text is split into words, numbers and punctuation, so that a merge never joins a letter to a punctuation mark or a digit.

That rule relies on spaces to find the words, which suits English but not languages written without spaces between words, such as Chinese and Japanese. SentencePiece (Kudo and Richardson, 2018), a toolkit used for the tokenizers of Llama 2, Gemma and many other models, takes the opposite approach: it does not split the text into words first. It treats the space as an ordinary character, written ▁, and learns its tokens from the raw text, so that a token may carry the space in front of a word with it. Because the space is kept as a symbol of its own, a text and its tokens can always be turned into each other exactly. SentencePiece can learn its vocabulary with BPE or with a second method, the unigram language model, which starts from a large vocabulary and removes the tokens that matter least. By default it also puts a ▁ in front of every text, so that a word at the start of a text is tokenized the same way as the same word after a space.

Tokenizers in the literature and in today’s models

BPE, byte-level BPE and SentencePiece are behind most of today’s models, but they are not the only methods, and every family of models trains its own tokenizer, with its own vocabulary and its own rules for spaces, numbers and code. The list below collects the tokenizers that mattered in the research literature and those behind widely used models; each has a page of its own.

Show the tokenizers

Methods

  • Byte-pair encoding (BPE): merge the most frequent pair of symbols, again and again (Sennrich, Haddow and Birch, 2016).
  • Byte-level BPE: BPE that starts from the 256 byte values, so that no text needs an unknown token (GPT-2, Radford et al., 2019).
  • WordPiece: merges chosen by how much they raise the likelihood of the text rather than by count; the tokenizer of BERT.
  • Unigram language model: start from a large vocabulary and remove the tokens that matter least, keeping a probability for each token (Kudo, 2018).
  • SentencePiece: a toolkit that works on raw text with the space as a symbol, training BPE or unigram vocabularies (Kudo and Richardson, 2018).
  • tiktoken: OpenAI’s fast byte-level BPE library, also used by other model families.

Tokenizers of major model families

  • OpenAI: byte-level BPE throughout, with a vocabulary that grew from 50,257 tokens in GPT-2 to about 100,000 in GPT-3.5 and GPT-4 and about 200,000 from GPT-4o on.
  • Anthropic (Claude): not published; counts of tokens are available through the API.
  • Meta (Llama): a SentencePiece BPE vocabulary of 32,000 tokens for Llama 1 and 2; a tiktoken-based vocabulary of about 128,000 tokens from Llama 3 on.
  • Mistral: SentencePiece vocabularies in its first models, then Tekken, a tiktoken-based tokenizer.
  • Google (Gemini, Gemma): a SentencePiece vocabulary of about 256,000 tokens.
  • DeepSeek: byte-level BPE with a vocabulary of about 128,000 tokens in DeepSeek-V3.
  • Alibaba (Qwen): byte-level BPE with about 151,000 tokens in Qwen2 and Qwen3, larger in later models.
  • Z.ai (GLM): the tokenizer of the GLM models.
  • Moonshot AI (Kimi): the tokenizer of the Kimi models.
  • MiniMax: the tokenizer of the MiniMax models.

Without a fixed vocabulary of words

  • Byte- and character-level models: models that read single bytes or characters, such as ByT5 and CANINE, at the price of much longer sequences.
  • Tokenizer-free models: models that group bytes into patches inside the model, such as MegaByte and the Byte Latent Transformer.

Beyond text

  • Images: cut into square patches, one vector each (the Vision Transformer), or turned into a grid of discrete codes by a learned codebook (VQ-VAE and VQGAN), so that an image becomes a sequence like a sentence.
  • Video: patches that span a few frames as well as a stretch of the picture.
  • Sound and speech: neural audio codecs such as SoundStream and EnCodec turn a waveform into a few streams of discrete codes; speech units are learned from clustered speech features (HuBERT).
  • Music: notes and their timing written as events (from MIDI), or the codes of an audio codec.
  • DNA: fixed words of k letters (k-mers), BPE over the four letters, or one token per letter (DNA encoders).
  • Proteins: one token per amino acid; their three-dimensional structure, too, can be written as discrete tokens.
  • Molecules: written as text strings, SMILES or SELFIES, and tokenized like text.
  • Time series: values scaled and rounded into a fixed set of bins, so that a language model can forecast them.
  • Robot actions: movements cut into discrete steps and written as tokens, so that one model can read a camera image and write an action.

From ids to vectors

We can now write the lookup precisely. Call the number of tokens in the vocabulary V, and the length of each embedding d. The two belong to different parts: V is set by the tokenizer, while d is chosen when the language model is designed and is called the language model’s width. The embedding matrix E holds one embedding per row, and the vector that enters the model at position t is the row of the token that stands there:

E∈ℝV×d,xt=E[idt]=eidtTE

Read the two formulas from left to right. The first says what kind of object E is: a matrix of real numbers (ℝ) with V rows and d columns. Each row belongs to one token of the vocabulary, and the row’s number is that token’s id; each row holds d numbers, the token’s embedding, and d is the language model’s width. The second says how the model uses E. idt is the id of the token at position t of the text, and xt, the vector that enters the model at that position, is simply row idt of E, written E[idt]. The last form says the same thing as a product. eidt is a one-hot vector: V numbers, all 0 except a 1 at position idt. Turned on its side, from a column into a row (the T, for transpose), and multiplied with E, it keeps exactly one row of E and drops all the others, so the result is again the token’s embedding, a vector of d numbers. To review: vectors, matrices and the matrix product.

Writing the lookup as a matrix product is more than a notational trick. It means that E is an ordinary matrix of weights, which gradient descent adjusts in the same way as every other matrix in the model. Notice also what the lookup leaves out: it says nothing about where a token stands in the text. The order of the tokens is added separately, by position encoding. Finally, the width d is the same at every position and in every layer: each block of a transformer takes in one vector of d numbers per position and gives out one vector of d numbers per position. This sameness is what makes it possible to place a vector of the right width at any position, and even at any depth inside the model, without the language model’s machinery noticing anything unusual about its shape.

Special tokens and placeholders

Besides the tokens that ordinary text is cut into, every vocabulary contains special tokens: tokens whose ids the tokenizer never produces from ordinary text. They exist so that a program can mark things in a prompt that are not part of the text. Chat models use special tokens to show where each turn of a conversation begins and ends (answering a multiple-choice question). Other special tokens pad a batch of texts to the same length, and many vocabularies keep some special tokens unused, in reserve.

A special token is still a token of the vocabulary, so it has an id and a row in the embedding matrix like any other: its embedding is that row. Like every row, it starts out random when the language model is created, and it changes only when training shows the token to the model. A special token that marks the turns of a chat is seen many times while the model is tuned to follow conversations, so its embedding is learned. A token kept in reserve, never used in any training text, never receives a training signal at all: its row stays close to where it started, random numbers or, after the slow pull towards zero that many training methods apply to every weight, numbers near zero. Such an embedding means nothing to the model, which is exactly what a placeholder needs, but it is also why a careful program does not simply leave an unused token’s embedding in place of real input: what the model sees at that position must be supplied.

Because ordinary text never produces a special token, the token carries no meaning of its own: in a prompt it does nothing but hold a position. That makes it a useful placeholder, which we will call a slot. A slot is how a model that reads only text can be given an input that is not text, such as an image, a sound or a molecule: the prompt reserves positions with slots, and the vectors the model finds at those positions are supplied from outside (connecting encoders to language models).

One practical point decides whether this works. Tokenizers behave differently when the name of a special token, such as <|pad|>, appears in a text as ordinary characters: some turn it into the special token’s id, others cut it into ordinary tokens. A careful program therefore never relies on the tokenizer to recognise a placeholder. It cuts the prompt at each placeholder, tokenizes the parts of text between them separately, and inserts the placeholder’s id itself, so that the slots end up exactly where the program put them.

To sum up: a text becomes a list of tokens, each token becomes an embedding, and a slot is a position whose vector is supplied from outside.

Test yourself

  1. Why use a token that ordinary text never produces as a slot?

    So that the slot carries no meaning of its own: its content is whatever is placed there. An ordinary word would bring its own meaning into the prompt, and the model would read that meaning along with whatever is supplied at the position. A meaningless placeholder also gives a neutral baseline: writing nothing informative there shows what the model does without the input.

  2. A larger vocabulary makes texts shorter. Why do tokenizers not simply grow their vocabulary without limit?

    Every token needs its own row in the embedding matrix and its own score at the output, so the matrices grow with the vocabulary; rare tokens are seen too seldom in training to learn good vectors; and a long token takes uses away from the shorter tokens inside it: if “reading” is a token of its own, then every “reading” in the training text no longer counts as an occurrence of “read”, so the shorter token is seen less often and learns less. A vocabulary size is a balance between shorter sequences and these costs, which is why real models settle on some tens to a few hundred thousand tokens.

  3. A byte-pair tokenizer meets a word that never occurred in the text it learned from. What happens to the word, and why can a byte-level tokenizer always cope?

    The learned merges are applied to the word’s characters in the order in which they were learned, and the word ends up cut into the tokens they build: often a common start such as “read” or “gen” followed by shorter tokens down to single characters (the cell shows “genome” becoming “gen”, “o”, “m”, “e”). A byte-level tokenizer starts from all 256 byte values, and every text is a sequence of bytes, so in the worst case a word is spelled byte by byte: no text ever needs an “unknown” token.

  4. What does the paper share between the input and the output, and what makes that possible?

    One matrix serves as the encoder’s and the decoder’s embedding and as the weights of the linear layer before the softmax. That works because source and target use one shared vocabulary.

Where it leads

Kept in this browser only, never sent.