How LLMs Represent Language: From Text to Tokens and Embeddings


On this page

1. From text to numbers

Suppose we ask a language model:

Review the delivery notification component for refactoring.

The neural network needs numerical inputs before it can perform any calculation. How does that sentence become something it can process?

In What Is an LLM?, we followed a request through the whole generation process. Here, we are going to slow down at its entrance: how text becomes tokens, how those tokens acquire IDs, and how the model looks up their initial numerical representations.

Text passes through tokenization to token IDs, embedding lookup, and input embeddings. These stages are highlighted as this article's scope. Transformer processing and next-token prediction follow afterward.
We follow the highlighted stages from a written request to its input embeddings. Later processing uses those vectors to predict the next token.

We’ll inspect these first stages using the small base checkpoint SmolLM2-135M. The checkpoint already contains learned model parameters and comes with a matching, trained tokenizer. We’ll follow our requests through these components, stepping back along the way to explain how their vocabulary and embedding values were learned. We’ll use the following two requests:

Review the delivery notification component for refactoring.
Review the customer churn number for Q3.

We’ll stop at the input embeddings. How transformer layers use context to update token representations will be the subject of a separate article.

2. Tokenization — breaking text into units

A tokenizer converts text into discrete pieces called tokens and maps them to integer IDs. A piece can represent a word, part of a word, punctuation, or a sequence including whitespace. The set of available tokens forms its vocabulary.

How does a vocabulary get built?

Before following our request through the trained tokenizer, let’s step back and see how its vocabulary is built. For a tokenizer such as SmolLM2’s, this involves training on a large collection of text, called a corpus. Different approaches choose pieces of different sizes. We can group them into three broad approaches:

Approach Basic idea Main trade-off
Word-level Use whole words as tokens. A large vocabulary is needed, and unfamiliar words may have no entry.
Character-level Use individual characters as tokens. A smaller vocabulary can represent many words, but produces longer sequences.
Subword Use reusable pieces, including whole words and smaller fragments. Balances vocabulary size and sequence length; the resulting pieces do not always match grammatical word parts.

Subword vocabularies can be constructed using algorithms such as Byte Pair Encoding (BPE), WordPiece, and Unigram. We’ll examine BPE because it is widely used in language models and is the approach behind our SmolLM2 tokenizer. Hugging Face’s tokenization overview describes these algorithms.

Before applying a subword algorithm, many tokenizers first split text into larger chunks using rules—for example, separating groups of letters, numbers, or punctuation. This step is called pre-tokenization. It establishes boundaries within which the subword algorithm operates.

During BPE tokenizer training, frequent adjacent units within those chunks are repeatedly merged to form additional vocabulary entries. Let’s walk through a small example to see how that works.

low    lower    lowest    slow    slower

For this illustration, treat each word as a separate pre-tokenized chunk and start with individual characters. Count adjacent pairs within each word: l + o occurs five times, and o + w also occurs five times. We choose l + o first to break the tie. After merging it, count again; units produced by earlier merges now participate in subsequent pairs.

Character-level BPE training on five words. Merge l and o five times, then lo and w five times, then low and e three times. The diagram shows every word's units after each merge.
Each vertical bar separates current units. Pair counts are recomputed after each merge; all five words remain in the training corpus.

After three rounds, the new unit lowe appears in three of our five training words. lower is represented as lowe | r, while lowest is lowe | s | t. The awkward-looking lowe is useful evidence: BPE learns recurring sequences, and those sequences do not have to match grammatical word parts.

We stop after three rounds to keep the demonstration readable. Real training commonly uses a target vocabulary size and additional stopping conditions, such as a minimum pair frequency. The vocabulary includes starting units and special tokens as well as learned merged entries; its size is not simply the number of merges.

Characters in the illustration, bytes in the real tokenizer

SmolLM2 uses GPT-2-style byte-level BPE. Within each pre-tokenized chunk, it starts from UTF-8 byte representations rather than the individual characters used in our last example. A byte is an eight-bit unit with 256 possible values. UTF-8, a standard way to encode text, represents A using one byte, é using two, and 🙂 using four.

BPE learns merges between these bytes and previously merged sequences. The four bytes representing 🙂 might become one token or remain split across several tokens, depending on the learned rules. Because this tokenizer can represent every byte value, unfamiliar text can still be encoded using smaller pieces. The GPT-2 tokenizer documentation describes this approach.

These vocabulary entries and merge rules are learned during tokenizer training and then reused when processing new text.

From text pieces to IDs

Now let’s return to our request and apply the already trained SmolLM2 tokenizer. It uses its existing vocabulary and merge rules to produce the following ten tokens and their IDs; no tokenizer training takes place here. The quoted decoded pieces preserve leading spaces:

Decoded piece Token ID
'Review' 21465
' the' 260
' delivery' 7037
' notification' 24408
' component' 5077
' for' 327
' ref' 930
'act' 471
'oring' 1522
'.' 30

Notice that refactoring spans three tokens: ' ref', 'act', and 'oring'. The leading space belongs to the first piece.

Several other pieces in the table also include a leading space. Can that space and the following word form one token? Let’s compare three variations using the same SmolLM2 tokenizer:

Input text Token ID
Review 21465
review 13286
 Review (with a leading space) 6769

Each input produces one token. Changing the capitalization or adding a space changes the byte sequence, and these three sequences have distinct entries in this tokenizer’s vocabulary. For Review, the space and word are represented together by one token, rather than separate space and word tokens.

The tokenizer displays that combined entry internally as ĠReview, where Ġ represents the leading space. This is why a token’s displayed spelling can look different from the original text.

The tokenizer has now done its part: it has converted our request into token IDs using its existing vocabulary and rules. It does not create the embedding vectors. Those belong to the language model and are learned during model training, separately from the tokenizer’s vocabulary construction.

Let’s follow these token IDs into the model to see how each one selects a numerical vector.

3. Embeddings — from token IDs to vectors

The embedding matrix

A token ID tells us which vocabulary entry we have, but its numerical distance from another ID says nothing useful about how those tokens relate. We need a representation whose values can be adjusted during training, helping the model learn patterns in language and use those patterns to predict text.

The model therefore maps each token ID to a learned vector—an ordered list of numbers—called an input embedding. This is the token’s initial representation before transformer processing. Those numbers give the network values it can combine and transform during its calculations. The vectors are stored as rows in an embedding matrix:

E∈RV×dE \in \mathbb{R}^{V \times d}

Take it one symbol at a time. EE names our matrix. The symbol ∈\in means “belongs to,” and R\mathbb{R} denotes real numbers. VV is the number of embedding rows, and dd is the number of values in each row. For our SmolLM2 checkpoint, the number of rows matches the tokenizer’s vocabulary size. Other models may reserve additional rows. We are describing a real-valued matrix with VV rows and dd columns.

For a small illustration, let’s use an embedding matrix with V=6V = 6 and d=4d = 4. The token IDs and vector values in this table are illustrative:

Illustrative token ID Token label Four-value vector
0 Review [0.2, -0.1, 0.5, 0.3]
1 the [0.7, 0.3, -0.2, 0.1]
2 delivery [-0.4, 0.8, 0.1, 0.6]
3 component [0.6, -0.5, 0.9, -0.3]
4 customer [0.3, 0.2, -0.6, 0.8]
5 churn [-0.2, 0.4, 0.7, 0.1]

For an input containing token IDs [0, 2, 3], we select the corresponding three rows in that order. We retrieve three vectors from the six-row table, each containing four values:

Input token IDs 0, 2, and 3 select the corresponding highlighted rows from the six by four illustrative embedding matrix E. The resulting array X contains three four-value vectors, in input order. E remains unchanged.
Token IDs select rows; they do not change the embedding matrix. The resulting input array preserves the token order. All displayed IDs and values are illustrative.

For an input containing nn tokens, let tit_i be the token ID at position ii. Its embedding lookup is:

xi=E[ti],X∈Rn×dx_i = E[t_i], \qquad X \in \mathbb{R}^{n \times d}

E[ti]E[t_i] selects a row, producing vector xix_i. Collecting the vectors for nn input tokens gives XX.

Vocabulary size, vector width, and input length are three separate quantities. PyTorch’s embedding layer implements this lookup.

How embeddings are learned

The illustrative embedding matrix above shows what a lookup returns. In a language model, these values are learned. Before training, the embedding matrix is initialized with starting values. Its entries are trainable parameters, adjusted alongside the weights in the transformer layers.

During language-model training, the model assigns probabilities to possible next tokens. A loss measures how well those probabilities match the actual next token in the training text. Gradients indicate how changes to parameters affect that loss, and an optimizer uses those gradients to adjust the parameters. One such update is called an optimizer step.

During training, the model embeds patterns of language into these vectors, learning about each token from how it is used across the training text.

If you’re curious to see an update for yourself, the companion notebook linked at the end includes a separate training demonstration using a newly initialized 6 × 4 embedding table: six illustrative token IDs, each associated with a four-value vector. This demonstration updates that table (it does not change SmolLM2’s parameters).

The example selects token ID 2 and uses an artificial target vector, [1, 0, 0, 0], to make one training update visible. After one optimizer step, the selected vector moves toward that target:

Row Before the optimizer step After the optimizer step
Token ID 2 [-0.849, -1.217, -0.081, 1.361] [-0.756, -1.156, -0.077, 1.293]

These values come from the notebook’s illustrative training example, rounded to three decimal places. The notebook also verifies that an unused row remains unchanged.

During actual language-model training, embedding updates are guided by the model’s token-prediction loss rather than an assigned target vector. Hugging Face’s causal language-modeling guide explains that prediction objective.

During ordinary inference—using a trained model to make predictions—the checkpoint’s learned parameters remain unchanged. Reading another prompt does not retrain its embedding table.

Inspecting SmolLM2’s input embeddings

Now let’s return to our request and retrieve its input embeddings from the already trained SmolLM2 checkpoint.

Inspecting the loaded SmolLM2 checkpoint gave an embedding matrix with 49,152 rows and 576 columns. The first five IDs of our example request—[21465, 260, 7037, 24408, 5077]—therefore retrieve an array of shape 5 × 576. We can inspect that directly after loading the model.

This snippet uses the model, tokenizer results, and PyTorch imported as torch earlier in the companion notebook.

embedding_layer = model.get_input_embeddings()
with torch.no_grad():
    vectors = embedding_layer(torch.tensor(token_ids_input_a[:5]))
print(tuple(vectors.shape))

Its output is:

(5, 576)

For Review, the first four measured coordinates were [0.07812, -0.13672, -0.11816, 0.04858], rounded to five decimal places. The vector has another 572 coordinates. Inspecting those numbers alone does not tell us that a column means “software” or “business.” Their usefulness comes from how the trained network uses them together.

Why input embeddings are not enough

Both our requests start with Review, ID 21465. Both retrieve exactly the same input embedding. At lookup time, E[21465] has no input describing the later delivery notification or customer churn tokens.

The lookup uses only the token ID; it does not combine information from other tokens in the request. That happens during the transformer processing that follows. Our experiment demonstrates only that the same token ID retrieves the same input embedding.

4. What comes next?

We started with a written request and followed it into the model: text became tokens, tokens became IDs, and those IDs selected learned vectors from an embedding matrix.

The model now has a vector for each input token, but the lookup alone has not combined information across the sequence. For our delivery request, how does it bring together the representations of delivery, notification, and refactoring to make a useful prediction?

That is the next stage we’ll explore: how transformer layers use information from earlier token positions to update these representations and predict what comes next.


The companion notebook and setup instructions contain the experiments. Measurements use revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2, Torch 2.8.0, and Transformers 4.57.6. The notebook records the complete environment and distinguishes illustrative values from checkpoint measurements.