Embeddings
Neural networks need vectors, but words, tokens, users and products are discrete symbols. An embedding maps each symbol to a learned dense vector. Mathematically it is just a matrix whose rows are looked up by index, which is the same as multiplying a one-hot vector by a weight matrix. Training places related symbols near each other, so that geometry (dot products, cosine similarity) carries meaning.
A lookup is a matrix product
With a vocabulary of size and embedding dimension , the embedding matrix is . The embedding of token is row :
where is the one-hot vector. Multiplying by a one-hot vector would waste multiplications per token, so frameworks implement it as indexing. The gradient follows: only the rows that were looked up receive gradient (a sparse gradient), and a row used several times in a batch accumulates them.
import numpy as np
rng = np.random.default_rng(0)
V, d = 6, 3
E = rng.normal(size=(V, d))
tokens = np.array([2, 5, 2])
onehot = np.eye(V)[tokens]
print("lookup equals one-hot product:", np.allclose(E[tokens], onehot @ E))
G = np.ones((3, d)) # upstream gradient for the 3 positions
dE = np.zeros_like(E); np.add.at(dE, tokens, G) # scatter-add into the looked-up rows
print("gradient rows (token 2 used twice):\n", dE)
print("same as one-hot^T @ G:", np.allclose(dE, onehot.T @ G))lookup equals one-hot product: True
gradient rows (token 2 used twice):
[[0. 0. 0.]
[0. 0. 0.]
[2. 2. 2.]
[0. 0. 0.]
[0. 0. 0.]
[1. 1. 1.]]
same as one-hot^T @ G: True
Similarity
The usual measure is the cosine similarity (Angles and Orthogonality), insensitive to vector length. Retrieval systems normalize embeddings to unit length so that the dot product is the cosine. Famous word-embedding results show linear structure: , because a consistent relation corresponds to a consistent direction.
import numpy as np
# Hand-built 4-D embeddings with dimensions (royal, male, female, food)
E = {"king": [0.9, 0.8, 0.1, 0.0], "queen": [0.9, 0.1, 0.8, 0.0], "man": [0.1, 0.9, 0.1, 0.1],
"woman": [0.1, 0.1, 0.9, 0.1], "apple": [0.0, 0.1, 0.1, 0.9]}
E = {w: np.array(v) for w, v in E.items()}
cos = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
target = E["king"] - E["man"] + E["woman"]
for w in E:
print(f"cos(king - man + woman, {w:5s}) = {cos(target, E[w]):+.3f}")cos(king - man + woman, king ) = +0.585
cos(king - man + woman, queen) = +0.995
cos(king - man + woman, man ) = +0.154
cos(king - man + woman, woman) = +0.772
cos(king - man + woman, apple) = +0.078
How embeddings are learned
- As the first layer of a model: a language model's input embedding is trained by backpropagation with everything else.
- By prediction (word2vec): make the dot product large for words that co-occur, small for random pairs; the result implicitly factorizes a matrix of word-context statistics.
- By contrast (sentence and image embeddings): a softmax cross-entropy over a batch where the matching pair is the correct "class" (InfoNCE):
with temperature . CLIP trains image and text encoders this way so that their embeddings share one space.
Embeddings in a transformer
A transformer's token embedding maps ids to -vectors; the output layer maps final hidden states back to logits, often with the same matrix (weight tying: logits ), which saves parameters. For a 50k vocabulary and , the table alone has 38.6M parameters (Counting Parameters). Position information must be added separately (Positional Encodings).
In software
nn.Embedding(V, d)(withpadding_idx, andsparse=Truefor sparse gradients);F.normalizefor unit vectors.- Vector databases index normalized embeddings for fast approximate nearest-neighbor search.
- See Generative AI and LLMs for embedding APIs and retrieval-augmented generation.
Exercises
Exercise 1: Table size
How many parameters does an embedding table for and have, and how much memory in bf16?
Answer
131,072,000 parameters, about 262 MB.
Solution
; times 2 bytes bytes.
Exercise 2: Cosine similarity
Compute the cosine similarity of and .
Answer
.
Solution
Dot product ; both norms are 3.
Exercise 3: InfoNCE (code)
For a batch of 3 pairs with unit-vector embeddings, compute the InfoNCE loss with when every equals its and the pairs are orthogonal to each other.
Answer
About : nearly perfect.
Solution
Similarities are 1 on the diagonal and 0 elsewhere, so each loss is .
import numpy as np
U = V = np.eye(3)
S = U @ V.T / 0.1
loss = np.mean(np.log(np.exp(S).sum(1)) - np.diag(S))
print(f"{loss:.2e}")9.08e-05
Test yourself
An embedding lookup is equivalent to…
- a softmax
- multiplying the one-hot vector of by
- a convolution
- sorting the vocabulary
Which rows of an embedding table receive gradient in a training step?
- All rows
- Only the rows of tokens that appeared in the batch
- Only the first row
- None
Weight tying in a language model means…
- all layers share weights
- the input embedding matrix is reused as the output projection
- embeddings are frozen
- the vocabulary is shared between languages