Embeddings
A token's meaning starts as one row of a table. Where the geometry comes from, which distance to use, and how embeddings power retrieval.
Jump to a section
A table with one row per token
The first layer of Llama 3 8B is a table with 128,256 rows and 4,096 columns, one row for each token in its vocabulary. That is about 525 million parameters, and running the layer does no arithmetic at all: token ID selects row , and the 4,096 numbers in that row are the token's starting vector.
Formally, an embedding layer is a matrix , with the vocabulary size and the embedding width. Looking up row is the same as multiplying a one-hot vector for by , which is why the table trains by gradient descent like any other weight matrix. In practice no one builds the one-hot vector; the lookup reads one row, 8 KiB in bf16 for Llama 3 8B.
Because only the rows for tokens in a batch take part in the forward pass, only those rows receive a gradient. A token that never appears in training keeps its initial values, apart from any weight decay.
The same idea extends past tokens. A sentence or document encoder also maps an input to a vector, but it computes that vector with a full network rather than reading it from a table. In both cases the useful property is the geometry: inputs the training objective treats as similar end up near each other.
Where the geometry comes from
Nothing in the table's shape says that "cat" should sit near "dog". The objective decides. word2vec's skip-gram model learns two vectors per word, a center vector and a context vector , by predicting the words around each center word:
Words that appear in similar contexts get pushed toward similar vectors, because the same context vectors have to score highly against both.
The denominator sums over the whole vocabulary for every training pair, which is too expensive at scale. Mikolov et al. replaced it with negative sampling: score the true context word against the center word, and push down the scores of words drawn from a noise distribution, the unigram frequencies raised to the 3/4 power. They found between 5 and 20 useful for small datasets and as low as 2 to 5 for large ones. This changes the objective. It is not an unbiased estimate of the full-softmax loss.
Some trained spaces show analogies such as . That is an empirical pattern in particular spaces, not a property every embedding must have.
Closeness depends on the metric
Two scores dominate. The dot product depends on both direction and length. Cosine similarity divides the length out and compares direction only:
The choice changes the answer. Take , and . By dot product with , scores 2 and scores 1. By cosine, scores 1 and scores . By Euclidean distance, both are exactly 1 away from . The same three points give three different rankings: first, first, and a tie.
Compare directions in a vector space
Similarity depends on the angle between the reference and comparison vectors.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
Supplied three-dimensional coordinates, not embeddings inferred from words. Camera projection does not change the computed similarity.
Authored analytic exampleExperiment with related Studio inputs
Select a comparison vector and rotate the scene. The cosine similarity is independent of the camera angle.
Illustrative coordinates, not embeddings inferred from these labels. The faint background cloud is decorative.
Normalizing every vector to unit length makes dot-product and cosine rankings identical, and Euclidean distance then ranks the same way too, since for unit vectors. But normalizing throws away magnitude, and in some spaces vector length carries information, such as how frequent a token is. Use the metric the model and its index were trained for, and evaluate on real query-document pairs.
From one vector per word to one per occurrence
A static embedding such as word2vec gives each word one fixed vector. "Bank" gets a single row whether the sentence is about rivers or money, so that row ends up as a blend of both senses.
In a Transformer the table lookup is only the starting point. Attention mixes in information from the surrounding tokens, layer after layer, so the same token ID ends up with a different representation in every context. These contextual vectors can separate the two senses of "bank", though nothing guarantees they do it correctly in every sentence.
Sentence and document embedding models build on the contextual version. They pool or train a single vector for a whole passage, and search and retrieval-augmented generation use them to find passages whose vectors sit near the query's vector, instead of matching keywords.
Many models also reuse the table at the other end. The original Transformer shared one matrix between the input embedding and the pre-softmax projection, which turns the output logits into dot products between the final hidden state and every token's embedding. Llama 3 8B keeps the two separate, which is why its vocabulary costs about a billion parameters rather than half that.
In code
The metric example in plain Python:
1import math
2
3def dot(x, y): return sum(p * q for p, q in zip(x, y))
4def norm(x): return math.sqrt(dot(x, x))
5def cosine(x, y): return dot(x, y) / (norm(x) * norm(y))
6def euclidean(x, y): return norm([p - q for p, q in zip(x, y)])
7
8a, b, c = (1, 0), (2, 0), (1, 1)
9assert dot(a, b) == 2 and dot(a, c) == 1
10assert cosine(a, b) == 1 and abs(cosine(a, c) - 1 / math.sqrt(2)) < 1e-12
11assert euclidean(a, b) == euclidean(a, c) == 1
12
13unit = lambda x: [v / norm(x) for v in x]
14for x in (b, c): # for unit vectors, squared distance is 2 - 2 cos
15 assert abs(euclidean(unit(a), unit(x)) ** 2 - (2 - 2 * cosine(a, x))) < 1e-12And an embedding table in PyTorch. The cosine at the end is only a calculation: freshly initialized rows carry no learned meaning.
1import torch
2import torch.nn.functional as F
3from torch import nn
4
5vocab_size, dim = 10000, 64
6embed = nn.Embedding(vocab_size, dim) # the lookup table E (V × d)
7
8ids = torch.tensor([42, 7, 1001])
9vectors = embed(ids) # (3, 64): one row per id
10assert vectors.shape == (3, 64)
11
12# Cosine calculation only: these randomly initialized vectors have no learned semantics
13a, b = embed(torch.tensor(42)), embed(torch.tensor(7))
14similarity = F.cosine_similarity(a, b, dim=0) # scalar in [-1, 1]Where it goes wrong
Closeness read as meaning. A high similarity says the training objective treated two inputs alike. It does not prove they mean the same thing, or that one answers the other.
Mixed embedding models. Vectors from different models, or different versions of one model, live in unrelated spaces. Comparing them gives numbers with no meaning, so after a model change the usual fix is to re-embed the whole index.
The wrong metric for the index. A model trained with cosine and an index searched by raw dot product can return a different top result, as the three-point example shows.
Small pictures of big spaces. A two- or three-dimensional illustration can show one relationship clearly. It cannot show the rest of a 4,096-dimensional geometry, and projections can put far-apart points next to each other.
Sources and further reading
- Mikolov et al., Distributed Representations of Words and Phrases: skip-gram, negative sampling, and empirical analogies.
- Llama Team, The Llama 3 Herd of Models (2024): the 128K vocabulary and 4,096-wide model used for the numbers above.
Keep going
Ask your own question about Embeddings, or start a guided session on it: six short pages, from the big picture to code you can run.