Concepts / Input Tokenization and Embedding

Input Tokenization and Embedding

The tokenized text enters at the embedding stage, which is why the input connects to the embedding layers first.

  • Programming
Interactive lab

Try it: Text Vectorization: Tokens to Vectors

The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.

How it works

  1. Standardize: lowercase and delete punctuation.
  2. Split on whitespace into tokens.
  3. Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
  4. Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
  5. Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.

Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.

Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.

Educational simulation

Loading the simulation…

Why a Language Model Needs Numbers

Every time a chatbot answers you, it is producing text in small pieces, one word or token after another. A GPT model is built for exactly that job. The letters stand for Generative Pretrained Transformer, and the model is a large deep neural network whose purpose is to generate new text one token at a time.

A large language model cannot read a sentence the way you do. Before any learning can happen, text has to be turned into a form that a deep learning model can process. This article follows that preparation in two stages. The first stage converts raw text into discrete integer identifiers. The second stage converts those identifiers into continuous vectors that a model can work with. As you read, keep one question in mind: what does the text look like after each step?

The Shape of a GPT Model

A natural first question is how a system that large can be understood at all. The answer is that the design is less tangled than its size suggests. Many of its parts are the same piece repeated over and over, so once you understand one repeated unit and how the units are wired together, most of the architecture comes into focus.

Think of a building made of identical floors. An architect only needs to draw one floor in detail and then specify how many times to stack it. A GPT-style model works in a similar spirit. Its core contains one or more transformer blocks, and each transformer block contains a masked multi-head attention module. Adding more blocks makes the model deeper without requiring a new kind of part.

Beyond the transformer blocks, a GPT model has embedding layers before them and output layers after them. The embedding layers turn tokenized text into numerical vectors. The transformer blocks do the main processing, and the output layers produce the model's result. The masked multi-head attention module is treated in this course as a finished component that gets placed inside the transformer block; its internal arithmetic is studied separately.

GPT modelouter containerEmbedding layerstokenized text to vectorsMasked multi-headattentioninside each blockTransformer blocksone or more, repeatedOutput layersproduce the resultcontainscontainscontainscontains
Which components sit inside which: the masked multi-head attention module lives inside each transformer block, and the transformer blocks sit between the embedding layers and the output layers.

Read the diagram as a set of nested containers. The whole model is the outer box. Inside it are the embedding layers, one or more transformer blocks, and the output layers. Inside each transformer block is the masked multi-head attention module. The tokenized text enters at the embedding stage, which is why the input connects to the embedding layers first.

Tracing an Input Through the Model

Take the tokenized input 'Every effort moves you'. It moves forward through the model in a fixed order. It enters the embedding layers first, then passes through the transformer blocks, where the masked multi-head attention module does its work, and it arrives at the output layers last.

Tokenized inputEvery effort moves youEmbedding layerstoken IDs to vectorsTransformer blockmasked multi-head attentioninsideMore transformerblockssame unit, stackedOutput layersproduce the model resultOutputresult of the modelenterspasses torepeatsarrives atproduces
What happens to the input tokens step by step: embedding lookup, then the repeated transformer blocks, then the output layers that produce the final scores.

This order tells you which stage hands its result to which other stage. It does not show the arithmetic inside a transformer block. Keeping the stages separate in your head makes the rest of the chapter easier to follow.

From Raw Text to Token IDs

The first step is tokenization. Raw text is broken into tokens, and a token can be a word or a character. After that, each token is converted into an integer representation called a token ID. So the pipeline runs from a string of characters, to a list of tokens, to a list of integers.

Raw textEvery effort moves youTokensEvery, effort, moves, youToken IDsone whole number per tokentokenizationeach token to integer
How a sentence changes form as it is split into tokens and each token is mapped to an integer ID.

Notice that the output of tokenization is discrete. Each token ID is a whole number that names one token. The text is no longer a continuous stream of characters, but a sequence of labels drawn from a fixed set.

Tokenization is the general process of breaking text into tokens. Byte pair encoding (BPE) is one specific tokenizer that performs that process, and it is the approach used for LLMs such as GPT-2 and GPT-3.

Handling Words the Tokenizer Has Never Seen

A tokenizer built only on whole words runs into trouble when it meets a word it has never seen. The BPE tokenizer handles this efficiently. It breaks an unfamiliar word down into subword units or, if necessary, into individual characters. The unknown word does not have to be discarded, because its pieces can still be represented.

Here is how the fallback works in principle. Start with an unfamiliar word. If the whole word is not in the vocabulary, look for smaller pieces that are. If even those pieces are not known, keep splitting until each remaining unit is a single character. Every stage of this process produces a unit the tokenizer can still represent, so nothing is lost.

Token IDs Versus Embedding Vectors

Token IDs are integers, and integers alone are not a rich representation for a deep learning model. An embedding layer in PyTorch solves this by functioning as a lookup operation. It takes a token ID and retrieves the vector that corresponds to it. The retrieved embedding vectors provide continuous representations of tokens, and this is crucial for training deep learning models such as LLMs.

Token ID 2a single integerRow 0[0.10, -0.40, 0.70]Row 1[0.30, 0.20, -0.90]Row 2[0.80, -0.10, 0.50]Row 3[-0.20, 0.60, 0.40]selects
How a single integer ID selects one row from the embedding matrix. The ID is a position number; the row it selects is a whole vector of continuous values.

The diagram uses an illustrative toy embedding matrix with made-up numbers; a real model's values are learned during training. The point is the mechanism: the ID 2 is a position, not a vector. The lookup picks out row 2, and that row is the vector the model works with. The integer itself is only a label, while the retrieved row carries several continuous values.

What do you think happens?

If the token ID is 2, how many numbers does the embedding vector for that token contain in the toy matrix above?

  • 1

  • 2

  • 3

  • 4

Reveal answer
Answer:

3

The ID 2 selects row 2, and each row in the toy matrix holds three values. The ID is a single number, but the vector it retrieves has three.

PropertyToken IDEmbedding vector
FormA single whole numberA list of continuous values
RoleNames one tokenRepresents that token for the model
Produced byTokenizationEmbedding lookup using the token ID
Kind of valuesDiscrete labelsContinuous representations

Token IDs and the embedding vectors they retrieve

Parameters and Weight Matrices

Parameters are the trainable internal variables adjusted during training. A useful way to picture them is as a large set of adjustable dials. Each dial starts at some value, training turns the dials a little at a time based on how wrong the model currently is, and the final settings of all the dials together determine how the model responds to input. When people talk about the size of a GPT model, they are counting these dials.

A weight matrix holds one parameter per element, so its parameter count is its number of rows multiplied by its number of columns.

Rule

Worked example

Counting the parameters in a small weight matrix

A weight matrix has 4 rows and 3 columns. How many trainable parameters does it contain?

  1. 1
    Identify the rows

    The matrix has $4$ rows.

  2. 2
    Identify the columns

    The matrix has $3$ columns.

  3. 3
    Multiply

    Each element is one parameter, so the count is $4 \times 3 = 12$.

Result

The matrix contains 12 parameters.

This chapter builds the core structure and does not yet train it or load pretrained weights. Loading pretrained weights and adapting the code to larger GPT-2 variants is deferred to a later chapter.

Mistakes Beginners Make with Tokens and Embeddings

  • Common mistake

    Treating the token ID as if it were the embedding

    What it looks like

    Assuming the model works directly with the integer 2 for a token.

    Why it fails

    The token ID is only a label. The embedding layer uses it to retrieve a vector of continuous values.

    Do this instead

    Think of the ID as a position that selects one row of the embedding matrix, and the row as the representation.

  • Common mistake

    Assuming every token is a whole word

    What it looks like

    Believing that tokenization always produces one token per word.

    Why it fails

    A token can be a word or a character, and BPE splits unfamiliar words into subword units or characters.

    Do this instead

    Expect tokens of varying size, and treat tokenization as the general process while BPE is one specific method.

  • Common mistake

    Believing unknown words are thrown away

    Why it fails

    The BPE approach keeps unfamiliar words by representing their pieces.

    Do this instead

    Remember that an unknown word is broken into known subword units or individual characters.

  • Common mistake

    Counting a weight matrix by its rows alone

    What it looks like

    Saying a 4 by 3 matrix has 4 parameters.

    Why it fails

    Each element holds one parameter, so every row contributes once per column.

    Do this instead

    Multiply rows by columns: 4 times 3 gives 12.

  • Common mistake

    Thinking the attention module is a separate stage from the transformer block, when it sits inside each block

Practice: Following Text Through the Pipeline

EASY

A weight matrix has 5 rows and 2 columns. Calculate its parameter count, then describe in one sentence how a token ID would produce a row of an embedding matrix instead of a single integer.

Hints
  • Multiply the number of rows by the number of columns.
  • The token ID selects one row, and that row is the vector used by the model.
MEDIUM

Suppose the word 'unbelievable' is not in a tokenizer's vocabulary. Describe how a BPE tokenizer could represent it using smaller known pieces, and state what happens to the pieces if none of them are known.

Hints
  • Think about subword units first, then individual characters.
  • Every unit must end up with a representation so the word is not discarded.

Key Takeaways

  • A GPT-style model is a large deep neural network that generates text one token at a time, built from embedding layers, one or more transformer blocks containing masked multi-head attention, and output layers.
  • Text is first tokenized into tokens that can be words or characters, then each token becomes an integer token ID.
  • BPE handles unknown words by breaking them into subword units or individual characters, so they are still represented.
  • An embedding layer in PyTorch uses a token ID as a lookup to retrieve a continuous embedding vector; the ID is a discrete label and the vector is the representation the model uses.
  • A weight matrix holds one parameter per element, so its parameter count is rows multiplied by columns.

Related concepts

More concepts starting with I