Embeddings

Embeddings

Once tokenization converts raw text strings into discrete integer token IDs, neural networks face a fundamental geometric question: how can arbitrary discrete numbers like 1923 and 4812 be represented in a space where mathematical operations like vector addition, dot products, and gradient updates carry semantic meaning?

The most basic representation is a one-hot vector , where an index is represented by an array of zeros with a single at position . While straightforward, one-hot encodings suffer from two critical flaws:

  1. Orthogonality and Semantic Blindness: The dot product between any two distinct one-hot vectors is identically zero: In one-hot space, cat is just as distant from kitten as it is from refrigerator. The model cannot share statistical learning across semantically related words.
  2. The Curse of Dimensionality: In modern LLMs with vocabulary size (e.g. LLaMA 3), a single one-hot vector requires 128,000 sparse dimensions per token, wasting memory and computation.

Dense embeddings resolve this by projecting discrete tokens into a continuous coordinate space (typically ). In this continuous space, tokens become dense vectors whose geometric distances (Euclidean norm) and angular orientations (cosine similarity) reflect linguistic meaning and functional relationships.


From Discrete Tokens to Continuous Vectors

The embedding layer operates as an efficient table lookup into a learned parameter matrix :

SymbolTensor ShapeGeometric & Computational Role
Sparse One-Hot Basis Vector: All-zero vector of length with a single at index . Orthogonal across all distinct tokens ().
Learned Embedding Matrix: Parameter table storing a -dimensional coordinate vector for each of the vocabulary tokens.
Dense Token Embedding: Retrieved in time via direct row gather (mathematically identical to without sparse matrix multiplication).
Cosine Similarity: Normalized inner product measuring directional alignment between two vectors independent of their Euclidean magnitude.

Equivalence of Sparse One-Hot Multiplication and O(1) Row Gather (V = 4, d = 3)

One-Hot e1T(1 × 4)0100×Embedding Table WE(4 × 3)+0.10+0.90+0.20+0.80+0.10-0.50+0.75+0.15-0.45-0.60+0.40+0.70WE[1] GatherO(1) SliceDense Vector x1("cat")(1 × 3)+0.80+0.10-0.50
Figure 1 (Direct Row Gather): Multiplying sparse one-hot row by zeros out every row except index . Hardware kernels bypass the multiply-adds entirely and copy contiguous row in time.

Vector Geometry & Memory Layout

To see how embedding matrices are indexed and how semantic similarity is quantified geometrically, consider a toy embedding space with vocabulary size and hidden dimension :

1. Embedding Matrix Structure

The model maintains a learned weight matrix , where each row stores the 3D coordinate vector for one vocabulary token:

Row Index ()TokenDim 1 ()Dim 2 ()Dim 3 ()Row Vector
Row 0the
Row 1cat
Row 2sat
Row 3dog
Row 4mat

2. Memory Lookup & Gather

When the sequence [cat, dog] (token IDs [1, 3]) enters the model, the embedding layer retrieves rows 1 and 3 directly from memory:

Mathematically, this lookup is equivalent to multiplying a one-hot row vector by the weight matrix :

In GPU kernels, this is executed as an pointer-offset memory gather, bypassing sparse matrix multiplication entirely.

3. Measuring Semantic Similarity

How close are cat and dog in this continuous coordinate space?

  1. Dot Product (Projection Alignment):

  2. Vector Magnitudes (Euclidean Norms):

  3. Cosine Similarity (Angular Affinity):

A cosine similarity of indicates that both coordinate vectors point in nearly identical directions, reflecting their shared linguistic status as animals. In contrast, comparing cat against the grammatical function word the yields , demonstrating functional orthogonality.


Interactive Embedding Space Simulator

Embedding Space Training & Vector Analogy Simulator

Watch random initial vectors organize into semantic clusters during training, forming geometric parallelograms where linear offsets encode analogies.

Training Progress: 100%
Dim 1 (Semantic)Dim 2
+0.982
Same Cluster: Synonyms and shared contexts pull vectors toward nearly identical angles.
+0.140
Unrelated: Unrelated concepts remain nearly orthogonal in high-dimensional space.
+0.990
Linear Analogy (): Parallel offset vectors connect man → woman and king → queen.
Converged Manifold (100%): Feline nouns cluster in the bottom-left while royalty/gender pairs form a geometric parallelogram in the upper-right. Converged
Training Epoch:

Memory Optimization & Normalization

In production LLMs, the embedding table and residual stream rely on three critical architectural optimizations to minimize VRAM footprint and stabilize deep gradient flow:

MechanismMathematical FormulationHardware & Optimization Impact
1. Weight Tying
(Press & Wolf 2017)
Reuses the transposed input embedding matrix for the final LM head projection. At , saves 524M parameters (1.05 GB in FP16).
2. Variance Scaling
(Vaswani et al. 2017)
Embedding weights initialized with have coordinate magnitude . Multiplying by restores unit variance before adding positional signals.
3. Pre-RMSNorm
(Zhang & Sennrich 2019)
Eliminates mean-centering from LayerNorm, requiring only a single reduction pass across dimension and cutting GPU HBM bandwidth overhead.

Key Papers & References