Concepts / Creating Token Embeddings for LLM Training

Creating Token Embeddings for LLM Training

The need for embeddings comes from the combination of two facts: the network is trained by backpropagation, and backpropagation only works on quantities that can change gradually. Neither fact alone produces the requirement.

  • 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…

Asking What the Model Can Learn From

Imagine you want to build a model that predicts the next piece of text. Before you can decide how that model should be built, you need to answer a more basic question: what kind of data can the model actually learn from? This article approaches that question from the training side. We start by asking what happens during training, and then work backward to see why the data the model reads has to take a particular form.

The central claim is short. A continuous vector representation, also called an embedding, is necessary because GPT-like LLMs are deep neural networks trained with the backpropagation algorithm. Each part of that sentence does work. The architecture determines what the model is made of, the training algorithm determines how the model improves, and the combination of the two is what makes the vector form necessary.

What do you think happens?

Before reading on: if the model reads a word written as plain text, could training nudge that word a little, the way it nudges a number?

  • Yes, a word can be nudged a small amount just like a number

  • No, a plain word has no graded scale of change

Reveal answer
Answer:

No, a plain word has no graded scale of change

A symbol such as a word written as plain text does not offer a graded scale. You cannot be a little more or a little less than the word cat in the way a number can be a little larger than another number. That is why the model needs a continuous numeric form to train on.

Why Training Needs Numbers That Change Gradually

Training a network means repeatedly comparing its output with a desired result, measuring the error, and then nudging the network's internal settings so the error gets a little smaller. Backpropagation is the algorithm that works out how much each internal setting should be nudged, by passing information about the error backward through the network. A nudge only makes sense when the quantities being adjusted are numbers that can change by small amounts.

The consequence for representation follows directly. If the model is trained by backpropagation, then the values it processes must also be numeric and continuous, so that small changes in the settings lead to small, measurable changes in the computation. A continuous vector gives the training process a space where gradual adjustment is possible. Without that space, there is nothing for backpropagation to measure and adjust in a graded way.

Key point

The need for embeddings comes from the combination of two facts: the network is trained by backpropagation, and backpropagation only works on quantities that can change gradually. Neither fact alone produces the requirement.

Tracing One Training Pass

A deep neural network is built as a sequence of layers. Each layer takes the output of the one before it and passes a transformed result forward. The word deep refers to having many such layers stacked together. GPT-like LLMs belong to this family, which is why they are described as deep neural networks rather than as simple one-step models.

The layered structure is the reason depth matters for training. Each layer has internal settings that can be adjusted, and the whole stack has to be adjusted together so that the final output moves toward the desired result. Keeping track of how a change in an early layer affects the final output is exactly the job that backpropagation handles.

Follow a single training step in order. The step begins with a forward pass, where values enter at the input and move through each layer until the network produces an output. The output is compared with what it should have been, which gives an error. The error is then sent backward through the layers, and each internal setting receives an adjustment. The next forward pass uses the updated settings, and the cycle repeats many times.

The adjustments happen at the end of the pass, in the settings that backpropagation reaches. The forward pass itself does not change those settings. This is the point in the cycle where numeric values change, and it only works because those values are numbers that can move by small amounts.

What a Token Embedding Is

A tokenizer turns text into integers. Each integer is a token ID that names one entry in a fixed vocabulary. An integer by itself carries no information about how one token relates to another, so a model cannot do much arithmetic with it directly. The usual remedy is to replace each ID with a vector, which is a list of numbers that the model can learn to adjust during training. That replacement is called a token embedding.

Definition

A token embedding is a vector representation of an input token, created in PyTorch with an Embedding layer.

In the lesson these token IDs come from the BPE tokenizer built earlier in the course, and the vocabulary has 50,257 entries. The embedding size is set to 256 dimensions. The source describes this as much smaller than the 12,288 dimensions used by the original GPT-3 model, yet still a reasonable size for experimentation on ordinary hardware. The 256 figure is a practical choice for learning, not a claim about what production models use.

How One Token ID Selects a Row

The embedding layer holds a table with one row for every possible token ID. Looking up a token ID means selecting the single row with that index. The row is the vector that the token ID maps to, and its length is set by the output dimension. In the lesson, every row has 256 values, so a token ID that picks a row returns a 256-value vector.

The token embedding layer treats each token by its identity alone. It does not record where in the sequence a token sits. Position is a separate matter: the source notes that a GPT-style absolute embedding approach needs a second embedding layer with the same embedding dimension as the token embedding layer, and both layers must share the 256-dimensional size so their outputs can be combined.

Dimensions of the Embedding Layer

The layer is defined by two numbers: the vocabulary size, which is the input dimension, and the output dimension, which is the embedding size. The constructor call takes the form torch.nn.Embedding(vocab_size, output_dim). In the lesson the first argument is 50,257 and the second is 256. These two numbers fully determine the layer's shape.

Formula, step by step
  1. 1
    V is the vocabulary size, which sets the number of rows, one for each possible token ID.
  2. 2
    d is the output dimension, which sets the length of each row.
  3. 3
    In the lesson V is 50,257 and d is 256, so the layer holds 50,257 rows of 256 values each.

Multiplying those two numbers gives the count of trainable values in the table: 50,257 times 256 is 12,865,792 numbers. This is arithmetic from the lesson's dimensions, not a separate figure from the source. It shows why the vocabulary size and output dimension together control how large the layer is.

Tracing a Batch Through the Embedding Layer

The batch passed to the layer is a two-dimensional grid of token IDs, with one row per text sample and one column per token position. The lesson uses a data loader to fetch a batch of 8 samples with 4 tokens each, so the input grid has shape $8 \times 4$. Every entry in that grid is one integer ID between 0 and 50,256.

python
Output (expected)
torch.Size([8, 4])
torch.Size([8, 4, 256])
Notes on the code
  • torch.nn.Embedding(50257, 256) builds the layer with vocabulary size 50,257 and output dimension 256.
  • torch.randint creates a random 8 by 4 grid of IDs in the valid range, standing in for a real batch.
  • Calling the layer on the grid returns one 256-value vector per ID.
  • The printed shapes show the input grid and the embedded result.

Calling the embedding layer on the grid replaces every integer with its 256-value vector. The grid positions do not move. The batch and sequence dimensions are preserved, and a third dimension of length 256 is appended. The result is a three-dimensional tensor of shape $8 \times 4 \times 256$, which means every one of the 32 token IDs is now a 256-dimensional vector.

Worked example

Predicting the shape for a different batch

A batch contains 3 text samples with 5 token positions each. Predict the shape of the embedding output, assuming the layer has output dimension 256.

  1. 1
    Identify the input shape

    Three samples with five positions each gives an input grid of 3 by 5.

  2. 2
    Keep the batch and sequence dimensions

    The embedding layer preserves the first two dimensions, so they remain 3 and 5.

  3. 3
    Append the embedding dimension

    Add a final axis equal to the output dimension, 256.

Result

The output shape is 3 by 5 by 256.

Misreadings of the Embedding Claim

  • Common mistake

    Thinking any numeric encoding would do, so the embedding is an arbitrary convenience.

    Why it fails

    The source ties the need to backpropagation. The vector form is required because training must adjust values in small, graded steps, and a token ID or plain symbol does not provide that graded scale by itself.

    Do this instead

    The embedding is needed because the training algorithm depends on continuous, adjustable quantities.

  • Common mistake

    Reading the claim as saying that LLMs need embeddings because they are large.

    Why it fails

    The necessity comes from the architecture and training algorithm together, namely a deep stack of layers trained by backpropagation. Size is not the stated reason.

    Do this instead

    Connect the necessity to deep layering plus backpropagation, not to scale.

  • Common mistake

    Assuming the token embedding records where a token sits in the sequence.

    Why it fails

    The token embedding layer treats each token by its identity alone. Position is handled by a separate layer that must match the embedding dimension.

    Do this instead

    Keep token identity and sequence position as two separate layers that are combined later.

  • Common mistake

    Assuming 256 is the dimension used by production models.

    Why it fails

    The source presents 256 as a practical learning choice, much smaller than the 12,288 dimensions used by the original GPT-3 model.

    Do this instead

    Treat 256 as a size chosen for experimentation on ordinary hardware.

  • Common mistake

    Dropping the batch or sequence axis when reading the output shape.

    Why it fails

    The embedding layer keeps the batch and sequence dimensions and only appends the embedding dimension, so an 8 by 4 grid becomes 8 by 4 by 256.

    Do this instead

    Read the output as the input shape with a new final axis of length 256.

Finding Where a Shape Mismatch Begins

When checking embedding output, verify the input shape first, then confirm that the final axis equals the output dimension. If the input grid has an unexpected shape, the mismatch exists before the embedding layer is called, so the embedding layer is not the place to look first. If the input is correct but the final axis is not the output dimension, then the layer's output dimension is the place to check.

Practice: Predicting and Checking Shapes

EASY

A layer is built as torch.nn.Embedding(50257, 256). You pass it a grid of token IDs with shape 6 by 10. Predict the output shape. Then state which stage you would check first if the printed output shape ended in 128 instead of 256.

Hints
  • The embedding layer keeps the first two dimensions of the input.
  • Only the final axis is set by the output dimension.
  • Start by checking the input grid before blaming the layer.
MEDIUM

Keep the vocabulary size at 50,257 but change the output dimension to 128. How many rows and how many values per row does the embedding matrix now have, and what is the total count of numbers in the table?

Hints
  • The vocabulary size still sets the number of rows.
  • The output dimension now sets the length of each row.
  • Multiply rows by row length.

Key Takeaways

  • GPT-like LLMs are deep neural networks trained with backpropagation, and that training needs continuous numeric values that can be nudged by small amounts, which is why an embedding is necessary.
  • A token embedding replaces each integer token ID with a learnable vector, and the embedding layer selects one row of its table for each ID.
  • The layer's shape is set by the vocabulary size (number of rows) and the output dimension (length of each row); in the lesson these are 50,257 and 256.
  • An embedding layer keeps the batch and sequence dimensions of the input and appends the embedding dimension, so an 8 by 4 grid of IDs becomes an 8 by 4 by 256 tensor.
  • When checking shapes, verify the input first, then confirm that the final axis equals the output dimension.

Related concepts

More concepts starting with C