Introduction
In our previous lesson, we established the crucial role of the vocabulary in bridging the gap between human language and a model's numerical processing. We saw how tokenization, using a method like Byte Pair Encoding, converts raw text into a sequence of discrete integer IDs. This numerical representation, however, is arbitrary and lacks any notion of semantic meaning; the ID 45 for "cat" is no more related to the ID 52 for "feline" than it is to the ID 817 for "rocket".
Today, we will investigate the first truly transformative step inside an LLM: the token embedding layer. This lesson focuses on how these meaningless integer IDs are mapped to dense, continuous vectors that capture rich semantic information. You will learn the mechanics of this mapping, understand why these "embedding" vectors are so powerful, and see how they form the first learnable layer of the Transformer architecture. This process marks the fundamental shift from discrete symbols to a continuous, geometric space where the model can begin to reason about meaning.
From Integers to Vectors: The Embedding Layer
The core component that performs this transformation is the embedding layer. At its heart, an embedding layer is a simple but massive lookup table. This table is a matrix, let's call it , with dimensions , where:
- is the size of our vocabulary.
- is the dimensionality of the embedding vectors, a hyperparameter of the model (e.g., 768 for BERT-base, 12288 for GPT-3).
Each row of this matrix is a vector of length . The process of embedding a token is straightforward: a token with ID i is mapped to the i-th row of the matrix . This row vector is the token's embedding.
From a computational standpoint, this is a highly efficient array-indexing operation. Andrej Karpathy's video provides a clear, practical demonstration of this process in PyTorch.
Let's build GPT: from scratch, in code, spelled out.
In his video "Let's build GPT: from scratch," Andrej Karpathy explains the implementation of the embedding table.
Please watch the segment from the introduction of the token embedding table. Notice how he describes the nn.Embedding module as a thin wrapper around a tensor and how an input integer "plucks out" the corresponding row from this table. This is the fundamental mechanism.
While we think of this as a direct lookup, it's mathematically equivalent to a linear transformation. Imagine representing a token ID i as a one-hot vector: a vector of length that is all zeros except for a 1 at the i-th position. Multiplying this one-hot vector by the embedding matrix yields exactly the i-th row of .

This diagram illustrates the equivalence between one-hot matrix multiplication and a direct lookup. A one-hot vector for token ID '3' (which is [0,0,0,1] if the vocabulary has 4 tokens) is multiplied by the embedding weight matrix. The result is the 4th row of the matrix, which is the embedding for token '3'.
This perspective is powerful because it frames the embedding layer as a linear layer that projects tokens from an extremely high-dimensional, sparse space (where dimensions are equal to the vocabulary size) into a much lower-dimensional, dense vector space. This transition from sparse to dense representation is a cornerstone of modern NLP.
The Geometric Meaning of Embeddings
Why are these dense vectors so special? Unlike one-hot vectors, where every token is equidistant and orthogonal to every other, the vectors in a dense embedding space are learned. The values in the embedding matrix are model parameters, initialized randomly and then fine-tuned during the training process via backpropagation.
The goal of this learning process is to arrange the vectors in the -dimensional space such that their geometric relationships capture semantic similarities. This is guided by the distributional hypothesis, which posits that words appearing in similar contexts tend to have similar meanings. The training process nudges the vectors of words like "cat" and "dog" closer together, while pushing them further from "car" or "planet".
The result is a rich semantic space where directions correspond to concepts. The 3Blue1Brown channel offers a superb visualization of this phenomenon.
Transformers, the tech behind LLMs | Deep Learning Chapter 5
This video, "Transformers, the tech behind LLMs," provides an intuitive and visually striking explanation of the geometric properties of word embeddings.
Please watch the segment from embedding words as vectors. Pay close attention to the following concepts: The idea of projecting a very high-dimensional space onto a 3D slice for visualization. The classic analogy: vector('king') - vector('man') + vector('woman') ≈ vector('queen'). This shows that abstract relationships like gender can be represented by consistent vector offsets. The use of the dot product to measure vector alignment, which quantifies semantic similarity. This will become extremely important when we discuss the attention mechanism.
The idea that we can perform arithmetic on word meanings (king - man + woman) is a profound consequence of representing them as vectors in a well-structured space. This structure is not pre-programmed; it is an emergent property learned from statistical patterns in the training data.
How are Semantic Embeddings Learned?
The principles behind learning these embeddings were largely developed in models like Word2Vec, which predated Transformers. While a full derivation is outside our main path, understanding the objective function is insightful, given your background.
A common approach is the skip-gram model. Its objective is, given a center word, to predict the words that appear in its context window. The model contains two embedding matrices (one for center words, one for context words). During training, it adjusts these embedding vectors to maximize the probability of predicting the correct context words.
To formalize this, the model calculates the similarity between the center word vector and all other context word vectors using dot products. These scores are then converted to probabilities using a softmax function. The loss is the negative log-likelihood of the true context words.
For a deeper mathematical treatment, the following article provides a clear breakdown.
Week 6: The Mathematics of Tokenization and Embeddings
This Medium article by Michael Kim provides a great mathematical overview of embedding concepts, including the Word2Vec skip-gram model.
Start by reading the section Embedding Geometry, which formalizes the mapping from discrete tokens to a continuous vector space and contrasts dense embeddings with one-hot encoding. Then, for a deeper dive into the learning mechanism, study the sections Word2Vec Principles and Word2Vec Derivation. This will give you the formal objective function and explain how methods like negative sampling make the training computationally feasible, which involves a trade-off between precision and efficiency that should resonate with your systems knowledge.
In a Transformer, the embedding matrix is simply the first layer of the network, and its weights are learned jointly with all other model parameters to minimize the final language modeling loss. The same principle applies: the gradients flowing back to the embedding layer will adjust the vectors to be more useful for the downstream task of predicting the next token.
Embeddings at the Input and Output: Weight Tying
We've established that the embedding layer maps token IDs to vectors at the model's input. In the previous lesson, we also saw that the final layer of the model, the "unembedding" or language model head, does the reverse: it projects the final hidden state vector into a probability distribution over the entire vocabulary.
This involves a projection matrix of shape . Notice the dimensional symmetry with the input embedding matrix, which is . This is no coincidence. The intuition is that the vector representation a model uses to understand a token should be the same as the representation it aims to produce when generating that token.
This insight leads to a powerful optimization called weight tying. Instead of learning two separate, massive matrices, we can use a single matrix for both tasks. The output projection matrix is simply the transpose of the input embedding matrix.
Weight Tying: Sharing Embeddings Between Input and Output Layers
This article offers an excellent, in-depth explanation of weight tying.
First, read The Two Embedding Matrices to clearly distinguish the roles of the input embedding and output projection matrices. Next, study The Weight Tying Idea and The Dot Product as Similarity. This explains the core insight and how the dot product computes a similarity score between the model's final hidden state and each token's embedding. Finally, review the Implementation section to see how this is coded in PyTorch. The simplicity of using self.embedding.weight.T for the output projection is quite elegant.
Weight tying not only halves the number of parameters in these layers—saving hundreds of millions of parameters in large models—but it also enforces a consistent semantic space throughout the model, often leading to better performance and faster convergence.
Preparing the Input for the Transformer
The token embedding provides the semantic meaning of a token, but it contains no information about its position in the sequence. Because the Transformer processes all tokens in parallel, the raw embeddings for "The dog chased the cat" and "The cat chased the dog" are identical sets of vectors.
To solve this, we must explicitly inject positional information. This is typically done by creating a second vector—a positional embedding—for each position in the sequence and adding it to the corresponding token embedding.

This diagram illustrates the complete input process. After the 'Token Embedding Layer Lookup', the resulting 'Token Embeddings' are combined with 'positional embeddings' to form the final input that is fed into the Transformer's decoder layers.
This combination of semantic and positional information creates the final input representation for the Transformer block.
Let's build GPT: from scratch, in code, spelled out.
Andrej Karpathy's video also covers this final step of combining embeddings.
Watch the segment from adding positional embeddings. He introduces a separate position_embedding_table and shows how the token embeddings and positional embeddings are simply added together. This is the final step before the data enters the main Transformer blocks.
This crucial topic of how positional embeddings are generated and why they are so vital will be the entire focus of our next lesson.
Conclusion
In this lesson, we have demystified the token embedding layer, the gateway through which text enters the semantic world of a neural network. We've seen that it is much more than a simple conversion utility; it is a learnable component that shapes the very foundation of the model's understanding.
Here are the key takeaways:
- An embedding layer is a lookup table (a matrix of size ) that maps a discrete token ID to a specific row, which is its dense vector representation.
- This lookup is mathematically equivalent to multiplying a one-hot vector by the embedding matrix, effectively projecting from a sparse, high-dimensional space to a dense, lower-dimensional one.
- The embedding vectors are learned parameters whose geometric arrangement in the vector space captures semantic relationships, enabling conceptual arithmetic (e.g.,
king - man + woman ≈ queen). - In Transformers, the input embedding matrix is often tied with the output projection matrix (its transpose), which saves parameters and enforces a consistent semantic representation.
- The final input to the first Transformer block is the sum of the token embedding (what the token means) and a positional embedding (where the token is).
We have now successfully converted our token IDs into meaningful, but position-agnostic, vectors. In the next lesson, we will dive deep into the mathematics of positional encodings, exploring how we can provide the model with the sequential context it needs to understand grammar and long-range dependencies.