Skip to content
ImagineWorld

Embeddings and Vector Spaces

node_idnode-book_llm-systems-engineering_module-03-embeddings-and-vector-spaces
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleEmbeddings and Vector Spaces
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Every neural network that processes language must first confront a basic engineering problem: the model can only operate on numbers, yet language arrives as discrete symbols with no inherent numerical structure. Converting text into integer token IDs solves half of this problem, but those integers carry no information about what any given word means or how it relates to other words. Embeddings resolve the remaining half by mapping each token ID to a dense vector of floating-point values that encode aspects of meaning in a form the model can manipulate mathematically. The resulting arrangement of vectors, known as an embedding space, is where semantic relationships become geometric ones, allowing the model to treat similarity and analogy as simple arithmetic on coordinates. Understanding how embeddings work is central to understanding what a large language model is actually doing when it processes text, because every computation inside a transformer (as discussed in Module 04) operates on these vector representations instead of on words themselves. This module examines the mechanics of the embedding lookup and the geometric properties of the vector spaces it produces, along with the reasons modern models rely on representations whose meaning changes depending on surrounding context.

A token ID on its own is an arbitrary integer. The ID assigned to the token “cat” might be 8,432 while “dog” might be 17,209, and these numbers tell a model nothing about the creatures they refer to. Numerical closeness between IDs carries no semantic meaning, since tokenizer vocabularies are typically built by frequency counts or merge order, which has no inherent connection to what any token signifies. To give the model something it can actually work with, each token ID is used as an index into a large matrix called the embedding matrix, where every row corresponds to one token in the vocabulary and contains a fixed-length vector of floating-point numbers (Bengio et al., 2003).

The embedding lookup itself is one of the simplest operations in the entire model. Given a token ID, the model retrieves the row at that index from the embedding matrix, producing a dense vector of perhaps 768 or 4,096 values depending on model size. This vector becomes the initial representation of that token as it enters the transformer stack. The embedding matrix itself is a learned parameter of the model, meaning its values begin as small random numbers and are gradually adjusted during training so that each row comes to encode useful information about the token it represents (Bengio et al., 2003).

d = embedding dimension (768)
┌──────────────────────────────────┐
┃│ 0.12 -0.45 0.07 … 0.31 │
┃│ -0.02 0.55 -0.19 … 0.04 │
┃│ 0.44 0.09 0.73 … -0.22 │
┃│ -0.31 0.18 0.02 … 0.65 │
┌────────────┐ ┃├──────────────────────────────────┤ ┌───────────┐
│ Token ID │──── row i ──▶ │ 0.87 -0.12 0.34 … -0.59 │ ─────▶ │ X ∈ ℝ^d │
│ i = 2174 │ ┃├──────────────────────────────────┤ └─────┬─────┘
└────────────┘ ┃│ 0.05 -0.27 0.41 … 0.13 │ ↓
V = vocab size ┃│ 0.60 0.34 -0.08 … -0.59 │ ┌─────────────────────┐
(50,257) ┃│ -0.14 0.22 0.57 … 0.09 │ │ Transformer Layer 1 │
┃│ 0.29 -0.63 0.11 … 0.38 │ └─────────────────────┘
└──────────────────────────────────┘

[!visual-conversion] The highlighted row i is exact. The other cell values are faint filler in print and were read at high contrast; treat them as illustrative.

Figure 1-6. Embedding Matrix Lookup from Token ID

Because the embedding matrix is learned alongside the rest of the model, the vectors it produces are shaped by whatever objective the model is trained on. In a language model trained to predict the next token, the embedding vectors come to reflect patterns of co-occurrence and substitutability, so that tokens appearing in similar contexts end up with similar vectors. This is what makes the lookup operation meaningful. A single integer index, which carries no semantic weight on its own, becomes a rich numerical fingerprint that captures how a token behaves across the training corpus.

What Vector Spaces Represent and Why They Work

Section titled “What Vector Spaces Represent and Why They Work”

Once tokens are represented as vectors, the collection of all those vectors forms a geometric space. Each token occupies a point in this space defined by its coordinates, and the relationships between points carry meaning that the model can exploit. Two vectors that point in similar directions are understood by the model as semantically related, while vectors pointing in very different directions are treated as unrelated. The standard measure of similarity used in practice is the cosine of the angle between two vectors, which captures directional alignment independent of magnitude (Mikolov et al., 2013a).

One of the more striking properties of well-trained embedding spaces is that relationships between concepts often correspond to consistent directions in the space. The classic demonstration, reported by Mikolov and colleagues, showed that arithmetic on word vectors could recover meaningful analogies: subtracting the vector for “man” from the vector for “king” and adding the vector for “woman” produces a result close to the vector for “queen” (Mikolov et al., 2013b). This regularity emerges without being explicitly programmed. The training objective, which simply rewards predicting words that appear in appropriate contexts, is enough to produce a space in which certain linguistic relationships become encoded as translations along particular directions.

Dimension 2
│ ╭─────────────────────────────╮
│ │ woman ● ● queen │
│ │ ╱ ╱ │
│ │ man ●╱ king ● │
│ ╰─────────────────────────────╯ ┌─────────────────────────────────────────────┐
│ │ v(king) - v(man) + v(woman) = v(queen) │
│ │ v(France) - v(Paris) + v(Rome) = v(Italy) │
│ └─────────────────────────────────────────────┘
│ ╭─────────────────────────────╮
│ │ Paris ● ● Rome │
│ │ ╱ ╱ │
│ │ France ●╱ Italy ● │
│ ╰─────────────────────────────╯
└──────────────────────────────────────────────────────── Dimension 1 (PCA projection)

[!visual-conversion] In print a 2-D scatter: two dashed clusters, each with two parallel offset segments (man→woman ∥ king→queen; France→Paris ∥ Italy→Rome). Positions are schematic.

Figure 1-7. Vector Arithmetic and Analogical Structure in Embedding Space

The reason vector spaces work so well for representing language lies in the flexibility of high-dimensional geometry. A sufficiently large space can accommodate many distinct relationships at once, with different directions capturing different aspects of meaning such as gender or tense. The model does not need to be told which direction corresponds to which concept. Through training, it discovers an arrangement of vectors that allows its predictions to be as accurate as possible, and that arrangement turns out to encode a great deal of structure that humans recognize as semantic.

The number of values in each embedding vector, known as the embedding dimension, is a principal design choice when configuring a language model. Small models might use 256 or 512 dimensions, while larger models commonly use several thousand. Each dimension can be thought of as an axis along which the model is free to encode information, so increasing dimensionality gives the model more room to represent fine distinctions between tokens and more capacity to express subtle relationships that lower-dimensional spaces cannot accommodate.

At the same time, higher dimensionality is not free. Every additional dimension increases the size of the embedding matrix in proportion to the vocabulary size, and it enlarges every downstream matrix that operates on these vectors inside the transformer. This increases both memory consumption and training cost. The practical question when choosing an embedding dimension is whether the additional capacity yields enough improvement in model quality to justify the added expense.

Embeddings learned by neural networks are dense representations, meaning that most or all of the values in each vector are non-zero. This distinguishes them from older sparse approaches such as one-hot vectors, which devote each dimension to a single token and fill the remainder with zeros. Dense vectors are far more efficient because each dimension can participate in encoding many different features of meaning, and each token’s representation can draw on the full width of the vector. The shape of a dense embedding space is therefore continuous and populated throughout, with tokens distributed across regions that reflect how they are used in training data.

The geometry of a dense embedding space also allows smooth interpolation between points. Two tokens whose meanings overlap partially can sit near each other without occupying exactly the same location, and the space between them can represent intermediate shades of meaning. This continuity is what allows models to generalize: even if a particular phrase was never seen during training, its representation will lie in a region populated by similar phrases, and the model’s behavior in that region will be shaped by what it learned from those neighbors (Bengio et al., 2003).

Early approaches to word embeddings, including word2vec and GloVe, assigned each word a single fixed vector regardless of how it was used in a sentence (Mikolov et al., 2013a; Pennington et al., 2014). Under this scheme, the word “bank” would have one vector that had to somehow accommodate both the financial institution and the edge of a river. These static embeddings captured average usage across the training corpus and proved useful for many downstream tasks, though their fixed nature limited how well they could handle words whose meaning depends heavily on context.

Modern transformer-based models produce contextual embeddings instead. When a token enters the model, it begins with a static lookup from the embedding matrix, but as it passes through the layers of the transformer, its representation is continuously updated based on the other tokens in the sequence. By the time the token reaches the final layer, its vector reflects the specific surrounding context in which the word appeared. The word “bank” in a sentence about rivers will end up with a different internal representation than the same word in a sentence about loans, even though both started from the same row of the embedding matrix (Peters et al., 2018).

This capacity for context-dependent representation is what allows transformer models to handle the ambiguity and polysemy that pervade natural language. The attention mechanism, which is covered in detail in the following module, is the component responsible for mixing information across tokens so that each position’s vector can absorb relevant signal from its neighbors. Contextual embeddings were first popularized by models such as ELMo and BERT, and their success marked a clear improvement over static approaches across a wide range of language tasks (Peters et al., 2018; Devlin et al., 2019).

It is worth noting that the initial embedding lookup still matters inside a transformer, even though the representations evolve through the layers. The static embedding at the input sets the starting point for each token’s journey through the model, providing a prior on what the token tends to mean before any context is considered. Training adjusts these initial vectors so that they serve as good launching points for the contextualization process that follows. The final vector a token carries at the output of the model is therefore the product of both its learned identity and everything the attention mechanism has layered onto it as the sequence was processed.

Understanding embeddings as the substrate on which all transformer computation occurs is central to forming an accurate picture of what a language model does. Every operation inside the model, from the attention mechanism through to the final prediction at the output, is ultimately arithmetic performed on these vectors. The quality of the embedding space, including its dimensionality and its capacity to reflect context, collectively determines what the model can represent and what it can learn to do. When a language model appears to understand a sentence, what it is actually doing is navigating a high-dimensional geometry that training has shaped so that meaningful things sit near one another.