Concepts / Input Embeddings

Input Embeddings

Positional embeddings are vectors that represent the position of tokens in a sequence, and they are created with torch.nn.Embedding(context_length, output_dim).

  • 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 Vectors Need a Position Signal

A language model does not read a sentence as a single lump. It receives a sequence of tokens, and each token is turned into a vector. Those token vectors describe what each token means. What they do not, by themselves, describe is where each token sits in the sequence. The word at the start of a sentence and the same word at the end would look identical to the token vector alone. Input embeddings are the piece of the pipeline that fills this gap.

This article follows the code first. You will build a small set of positional embeddings, read the shape of the result, and then see how that result combines with token embeddings. The goal is not to memorize a recipe but to be able to trace each step and say what the numbers in the shape mean.

What Positional Embeddings Carry

Definition

Positional embeddings are vectors that represent the position of tokens in a sequence. They are created with torch.nn.Embedding(context_length, output_dim).

Positional embeddings are one half of the input representation. The other half is the set of token embeddings, which carry the semantic meaning of each token. Think of the two as answering different questions. Token embeddings describe meaning. Positional embeddings describe location. Input embeddings are the combined result that the rest of the model consumes.

Building the Positional Lookup Table

The positional embedding layer is built with torch.nn.Embedding, given two numbers. The first is context_length, which is how many positions the model handles. The second is output_dim, which is the size of each vector. The layer behaves like a table with one row per position. Each row is a learned vector of length output_dim.

The positions themselves are supplied by torch.arange(context_length). This produces the sequence of position indices 0 through context_length minus 1. Passing those indices into the layer returns the row for each position. So position 0 looks up row 0, position 1 looks up row 1, and so on. Each position gets its own vector.

python
Output (expected)
torch.Size([4, 256])
Notes on the code
  • context_length sets how many rows the table has, one per position
  • output_dim sets the length of each row
  • torch.arange(context_length) produces the position indices 0, 1, 2, 3
  • Passing the indices into the layer returns one row per position
position 0row 0, length 256position 1row 1, length 256position 2row 2, length 256position 3row 3, length 256next positionnext positionnext position
Each position index maps to its own row of the positional embedding tensor. Every row is a learned vector of length 256.

Reading the diagram as a lookup table helps. The index 0 through 3 is the key, and the row is the value. Nothing in the table is a token. It is purely a record of position, and each row is learned as the model is trained.

Reading the Shape of the Tensor

Because each position gets its own vector, the shape of the positional embedding tensor reflects both quantities that define it. The number of rows matches the context length, and the number of columns matches the output dimension. In the source example there are four positions, and each is represented by a 256-dimensional vector. That is why the printed shape describes four vectors of length 256.

DimensionWhat it countsSet byValue in the source example
First (rows)Positions in the sequencecontext_length4
Second (columns)Numbers in each positional vectoroutput_dim256
Whole tensorPosition vectors stacked togetherBoth values together4 by 256

Reading the positional embedding tensor shape

Worked example

Predicting the shape from two numbers

Suppose a model handles 10 positions and each positional vector has length 64. What is the shape of the positional embedding tensor?

  1. 1
    Identify the rows

    The number of rows matches the context length, which is 10 positions.

  2. 2
    Identify the columns

    The number of columns matches the output dimension, which is 64 values per vector.

  3. 3
    Combine

    Write the shape as rows then columns.

Result

The shape is 10 by 64.

Adding Positional Information to Token Vectors

The two embedding types meet at a single addition. Token embeddings and positional embeddings are added together, and the sum is called the input embeddings. The input embeddings are the embedded input examples that can be processed by the main LLM modules. The diagram below traces the path from raw text to this meeting point.

token embeddings8 by 4 by 256additionelement-wise suminput embeddings8 by 4 by 256positionalembeddings4 by 256added toadded to each batchpassed to main model
Token embeddings and positional embeddings combine by addition to produce the input embeddings. The positional tensor is shared across the batch.

The addition works only when the two tensors line up. The shape of positional embeddings should match the shape of token embeddings. In the source example, the token embeddings are arranged as eight batches, each holding a 4 by 256 tensor, so the full token tensor has shape 8 by 4 by 256. The positional embedding tensor is 4 by 256. PyTorch adds that single 4 by 256 tensor to each of the eight batch entries, so every batch receives the same positional information.

The input embeddings keep the token embedding shape. In the source example that shape is 8 by 4 by 256. The addition changes the values inside each vector, but it does not change the overall shape of the result.

Worked example

Tracing shapes through the addition

Token embeddings have shape 8 by 4 by 256. Positional embeddings have shape 4 by 256. What is the shape of the input embeddings?

  1. 1
    Compare the trailing dimensions

    The positional tensor's 4 by 256 lines up with the last two dimensions of the token tensor, which are also 4 and 256.

  2. 2
    Apply the positional tensor to each batch

    The single 4 by 256 positional tensor is added to each of the 8 batch entries.

  3. 3
    Read the result

    Each batch entry keeps its shape of 4 by 256, and there are still 8 of them.

Result

The input embeddings have shape 8 by 4 by 256.

Where Shape Mismatches Show Up

The creation steps run in a fixed order: token IDs, then token embeddings, then positional embeddings, then the addition. A mismatch in context length or output dimension shows up at the step where the two tensors first have to agree. For positional information, that is the addition step, because the positional tensor is built from context_length and output_dim and must match the token tensor's shape to be combined with it.

token IDsfrom the vocabularytoken embeddingsmeaning of each tokenpositional embeddingsbuilt from context_lengthand output_dimadditionshapes must line up hereinput embeddings8 by 4 by 256 in the sourceconverted tomeetscombined withproduces
The creation steps run in order. A mismatch in context length or output dimension is first detected when the positional tensor is combined with the token tensor.
  • Common mistake

    Reading the positional tensor's rows as tokens

    What it looks like

    Seeing a 4 by 256 positional tensor and assuming four words are stored in it.

    Why it fails

    Each row is a vector for a position index, not a token. The table holds position information only.

    Do this instead

    Read the rows as positions 0 through context_length minus 1, and the columns as the values in each positional vector.

  • Common mistake

    Swapping context_length and output_dim

    What it looks like

    Building the layer with the vector length first and the number of positions second.

    Why it fails

    The shape then describes the wrong quantities, so the rows and columns no longer match the sequence and the vector size.

    Do this instead
    Pass context_length first and output_dim second, as in torch.nn.Embedding(context_length, output_dim).
  • Common mistake

    Expecting the positional tensor to replace the token embeddings

    Why it fails

    Positional embeddings describe location, while token embeddings describe meaning. Only the sum moves forward into the main model.

    Do this instead

    Keep both tensors and expect the addition to produce the input embeddings.

Predicting and Checking Positional Shapes

What do you think happens?

A program sets context_length to 4 and output_dim to 256, then prints the shape of the positional embeddings. What do you think is printed?

Reveal answer
Answer:

torch.Size([4, 256])

There are four rows, one per position, and each row is a vector of length 256.

MEDIUM

A positional embedding layer is built with context_length 6 and output_dim 128. Token embeddings have shape 2 by 6 by 128. Predict the shape of the input embeddings and state which step would fail if the layer were built with output_dim 64 instead.

Hints
  • The positional tensor has one row per position, so its first dimension is context_length.
  • The input embeddings keep the token embedding shape after the addition.
  • The mismatch would appear at the addition step, where positional and token tensors must line up.

Key Takeaways

  • Token embeddings describe what each token means, while positional embeddings describe where each token sits in a sequence.
  • torch.nn.Embedding(context_length, output_dim) builds a table with one learned row per position, and each row has length output_dim.
  • The positional embedding tensor's shape is context_length by output_dim, so the source example's 4 by 256 describes four vectors of length 256.
  • Positional embeddings are added to token embeddings, and the sum is the input embeddings, which keep the token embedding shape such as 8 by 4 by 256.
  • Shape mismatches surface at the addition step, so check context_length and output_dim against the token embedding shape there.

Related concepts

More concepts starting with I