Concepts / Absolute Positional Embeddings

Absolute Positional Embeddings

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

  • 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 Token IDs Need Vectors

What do you think happens?

A batch of 8 samples with 4 tokens each goes into an embedding layer with a 256-dimensional output. What shape do you expect the output to have before reading on?

Reveal answer
Answer:

The output has shape 8 × 4 × 256.

The layer keeps the batch and sequence dimensions of the input and appends the embedding dimension, so every one of the 32 token IDs becomes a 256-value vector.

A tokenizer turns text into integers. Each integer is a token ID that names one entry in a fixed vocabulary. On its own, though, an integer 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 this lesson the 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.

Tracing One Token ID Through the Table

Think of the embedding layer as a table with one row for every possible token ID. The vocabulary size sets how many rows the table holds, and the output dimension sets how long each row is. When a token ID arrives, the layer does not compute anything complicated. It selects the row whose position matches that ID and returns the vector stored there. The row is the vector that a given token ID maps to.

token ID 3one integerID 0256-value rowID 1256-value rowID 2256-value rowID 3256-value vectorID 50,256256-value rowselects row
How does a single integer token ID select one specific row of the embedding table and turn into a vector? Here token ID 3 picks out row 3, and the other rows are not used for that token.

The lookup happens for each entry in the input independently. Two tokens with different IDs select different rows, and each selected row is a full 256-value vector. The embedding table is the only place those vectors live, which is why the layer is described by its two dimensions alone.

Building the Layer from Two Numbers

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: the weight matrix has $50{,}257 \times 256$ entries, with 50,257 rows and 256 columns. Reading the arguments in order is the first check to make whenever you build one of these layers.

python
Output (expected)
torch.Size([50257, 256])
Notes on the code
  • vocab_size sets the number of rows, one for each possible token ID
  • output_dim sets the length of each row, the embedding size of every token
  • The weight shape confirms rows first, then columns

Shape of a Batch After Embedding

The batch passed to the layer is a two-dimensional grid of token IDs. Each row holds one text sample, and each column holds one 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.

batch: 8samplesbatch: 8samplessequence: 4token positionssequence: 4token positionsembedding: 256new axis
How do the dimensions change from a batch-by-sequence grid of IDs to a three-dimensional tensor, and which axis is added? The batch and sequence axes are kept, and an embedding axis of length 256 is appended.
Worked example

Predicting the output shape for an 8 by 4 batch

A data loader returns a batch of 8 samples with 4 token IDs each. The embedding layer is torch.nn.Embedding(50257, 256). What shape does the output have, and how many 256-value vectors does it contain?

  1. 1
    Read the input shape

    The grid has 8 rows (samples) and 4 columns (positions), so the input shape is $8 \times 4$.

  2. 2
    Keep the batch and sequence axes

    The embedding layer preserves the batch dimension (8) and the sequence dimension (4). Grid positions do not move.

  3. 3
    Append the embedding dimension

    The output dimension of 256 is appended as a new last axis, giving $8 \times 4 \times 256$.

  4. 4
    Count the vectors

    There are $8 \times 4 = 32$ token IDs, and each one becomes a 256-dimensional vector.

Result

The output tensor has shape $8 \times 4 \times 256$, containing 32 vectors of length 256.

python
Output (expected)
torch.Size([8, 4])
torch.Size([8, 4, 256])
Notes on the code
  • randint draws random IDs in the valid range 0 to 50,256 to stand in for a real batch
  • Calling the layer on the grid replaces every integer with its vector
  • The final axis equals the output dimension, 256

Where a Shape Mismatch Shows Up

When you check embedding output, verify the input shape first, then confirm that the final axis equals the output dimension. Tracing the pipeline from the token ID tensor forward shows where a problem first appears. The input shape is set by the data loader, so it is the first place to look. The next place is the embedding layer, whose weight matrix is fixed by the two constructor arguments.

Token ID tensorshape 8 × 4Embedding layer50,257 rows × 256 columnsEmbedding outputshape 8 × 4 × 256Position embeddinglayermust also use 256Combined outputsums need matching sizeIDs index rowsappends 256adds toadds to
Starting from the token ID tensor, which step first produces incompatible dimensions if the vocabulary size or output dimension is set wrongly? The first incompatible step is the one whose dimensions disagree with the step before it.

If the vocabulary size is smaller than the largest token ID in the batch, some IDs have no row in the table to select. If the output dimension is set to a value other than 256 in only one of the two embedding layers, the outputs have different final axes and cannot be combined. In both cases the problem appears at the layer whose arguments were set incorrectly, not at the layer after it.

Adding Position Information Later

The token embedding layer treats each token by its identity alone. It does not record where in the sequence a token sits. 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. That second layer supplies position information, and it is the subject of the next step in the lesson.

Both layers must share the 256-dimensional size so that their outputs can be combined. This is the reason the output dimension is a shared design choice rather than a free setting for each layer. The position vector and the token vector for the same slot in the grid are added together, which is why matching final axes matter before any combination happens.

Mistakes With Embedding Dimensions

Most errors in this step come from reading the constructor arguments in the wrong order or from assuming the output keeps the input's shape. The items below are the ones most likely to cost time.

  • Common mistake

    Assuming the embedding output has the same shape as the token ID grid

    What it looks like

    Expecting an 8 × 4 grid to come back as 8 × 4 after the layer runs.

    Why it fails

    The layer appends an embedding axis, so the output gains a third dimension.

    Do this instead

    Expect $8 \times 4 \times 256$ and check that the final axis equals the output dimension.

  • Common mistake

    Swapping vocabulary size and output dimension

    What it looks like
    Writing torch.nn.Embedding(256, 50257) for this lesson.
    Why it fails

    The first argument sets the number of rows, and the second sets the length of each row.

    Do this instead

    Use torch.nn.Embedding(50257, 256) so the layer has one row per token ID and 256 values per row.

  • Common mistake

    Setting the vocabulary size without checking the tokenizer

    Why it fails

    IDs outside the layer's row range have no vector to select.

    Do this instead

    Make the vocabulary size cover every ID the tokenizer can produce, here 0 to 50,256.

  • Common mistake

    Changing the output dimension in one embedding layer only, so the two layers cannot be combined

Predicting Shapes Before Running the Layer

MEDIUM

A data loader returns a batch of 16 samples with 6 token IDs each, and the embedding layer is torch.nn.Embedding(50257, 256). Predict the output shape, then identify which axis is new. Finally, state which step would first fail if the layer were built with torch.nn.Embedding(256, 50257).

Hints
  • Keep the batch and sequence axes from the input before adding anything.
  • The new axis is the last one and has the length of the output dimension.
  • Check which argument sets the number of rows and which sets the row length.

Key Takeaways

  • A token embedding is a vector representation of a token ID, created with torch.nn.Embedding, which replaces each integer with a learned vector.
  • The constructor torch.nn.Embedding(vocab_size, output_dim) sets the layer shape: vocab_size gives the number of rows and output_dim gives the length of each row. In this lesson those are 50,257 and 256.
  • An embedding layer keeps the batch and sequence axes and appends the embedding axis, so an 8 × 4 grid of IDs becomes an 8 × 4 × 256 tensor.
  • When checking output, verify the input shape first, then confirm the final axis equals the output dimension; a mismatch first appears at the layer whose arguments are wrong.
  • Absolute positional embeddings come from a second embedding layer with the same dimension, so that position vectors and token vectors can be combined.

Related concepts

More concepts starting with A