Embeddings
A token ID like 4821 is just a label — the number itself says nothing about meaning. The first layer of an LLM therefore replaces each ID with an embedding: a list of numbers (a vector) that the model learned during training. Tokens used in similar ways end up with similar vectors, so meaning becomes geometry.
Vectors you can read
Real embeddings have hundreds or thousands of dimensions, and individual dimensions rarely mean anything a human can name. To build intuition, here are hand-made 4-dimensional vectors where each dimension does have a meaning:
import numpy as np
# animal pet size food
emb = {
"cat": np.array([0.9, 0.9, 0.2, 0.0]),
"dog": np.array([0.9, 0.8, 0.4, 0.0]),
"tiger": np.array([0.9, 0.0, 0.8, 0.0]),
"pizza": np.array([0.0, 0.0, 0.3, 0.9]),
"burger": np.array([0.0, 0.0, 0.3, 0.8]),
}
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
for word in ["dog", "tiger", "pizza"]:
print(f"cat vs {word:<6} {cosine(emb['cat'], emb[word]):.3f}")cat vs dog 0.985
cat vs tiger 0.625
cat vs pizza 0.049
Cosine similarity
The standard way to compare embeddings is cosine similarity: the cosine of the angle between two vectors.
cosine(a, b) = (a · b) / (|a| × |b|)| Value | Meaning |
|---|---|
| close to 1 | pointing the same way — very similar |
| around 0 | unrelated (perpendicular) |
| close to −1 | opposite directions |
Cosine ignores vector length and only looks at direction, which makes it robust when some vectors are longer than others. Many embedding APIs return vectors already normalised to length 1; then cosine similarity is simply the dot product.
Finding nearest neighbours
"Which word is most similar to X?" is answered by computing the similarity to every vector and sorting. This is exactly what a vector database does at scale (see the Vector Search lesson).
import numpy as np
words = ["cat", "dog", "tiger", "pizza", "burger"]
M = np.array([[0.9, 0.9, 0.2, 0.0],
[0.9, 0.8, 0.4, 0.0],
[0.9, 0.0, 0.8, 0.0],
[0.0, 0.0, 0.3, 0.9],
[0.0, 0.0, 0.3, 0.8]])
unit = M / np.linalg.norm(M, axis=1, keepdims=True) # normalise rows once
sims = unit @ unit.T # all pairwise cosines
query = words.index("burger")
order = np.argsort(-sims[query])
for i in order[1:]:
print(f"{words[i]:<6} {sims[query, i]:.3f}")pizza 0.999
tiger 0.233
dog 0.111
cat 0.055
Learning embeddings from context
Where do real embeddings come from? The key idea is the distributional hypothesis: words that appear in similar contexts have similar meanings. The toy below counts which words appear next to each other, then compresses the count matrix to 2 dimensions with SVD — a classic pre-neural technique. LLMs learn their embeddings differently (by gradient descent while predicting the next token), but the principle is the same.
import numpy as np
import matplotlib.pyplot as plt
sentences = [
"cat drinks milk", "dog drinks water", "cat chases mouse", "dog chases cat",
"kitten drinks milk", "puppy drinks water", "puppy chases ball", "kitten chases mouse",
"car needs fuel", "truck needs fuel", "car drives road", "truck drives road",
"dog rides car", "puppy rides truck", "cat sleeps on car", "kitten sleeps on truck",
]
vocab = sorted({w for s in sentences for w in s.split()})
index = {w: i for i, w in enumerate(vocab)}
counts = np.zeros((len(vocab), len(vocab)))
for s in sentences:
ws = s.split()
for i, w in enumerate(ws):
for j in range(max(0, i - 2), min(len(ws), i + 3)): # window of 2 words
if i != j:
counts[index[w], index[ws[j]]] += 1
U, S, Vt = np.linalg.svd(np.log1p(counts))
vectors = U[:, :2] * S[:2]
show = ["cat", "kitten", "dog", "puppy", "car", "truck", "milk", "fuel"]
fig, ax = plt.subplots(figsize=(5, 4))
for w in show:
x, y = vectors[index[w]]
ax.scatter(x, y, color="#7c3aed")
ax.annotate(w, (x, y), textcoords="offset points", xytext=(4, 4))
ax.set_title("Word vectors from co-occurrence counts (2-D)")
plt.show()
unit = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
def sim(a, b):
return unit[index[a]] @ unit[index[b]]
print(f"kitten~cat {sim('kitten', 'cat'):.2f} truck~car {sim('truck', 'car'):.2f} kitten~truck {sim('kitten', 'truck'):.2f}")
print("plotted 8 words in 2-D")kitten~cat 1.00 truck~car 1.00 kitten~truck 0.36
plotted 8 words in 2-D
Nobody told the program that kittens and cats are related — the shared contexts ("drinks milk", "chases mouse") pushed their vectors together, while vehicle words ended up in a different region.
Embeddings everywhere
| Use | How embeddings help |
|---|---|
| Inside an LLM | First layer: token ID → vector; the Transformer refines these vectors layer by layer |
| Semantic search | Embed documents and queries; return documents with the highest similarity |
| RAG | Retrieve relevant passages to put into the prompt |
| Clustering & deduplication | Group texts whose vectors are close |
| Recommendations | Suggest items whose vectors are near the user's interests |
For search you normally use a dedicated embedding model that turns a whole sentence or paragraph into one vector, rather than the per-token embeddings inside a chat model.
Note: Similar vectors mean "used in similar contexts", which is not always "means the same". Antonyms such as hot and cold often have quite similar embeddings because they appear in the same kinds of sentences.
Go further: Word Embeddings: PPMI, SVD and Word2Vec learns embeddings from co-occurrence counts and looks at the bias they pick up.
Test yourself
What does cosine similarity measure?
- The length of a vector
- The angle between two vectors (their direction)
- The number of dimensions
- The token ID difference
If all embedding vectors are normalised to length 1, cosine similarity equals…
- their sum
- their dot product
- zero
- the Euclidean distance
Why did 'kitten' and 'cat' get similar vectors in the co-occurrence example?
- They are spelled similarly
- They appear in similar contexts
- They were given the same token ID
- SVD sorts words alphabetically