Embeddings: Meaning as Vectors
Introduction
Tokenization: How Text Becomes Numbers (BPE) ended with a list of numbers. GPT-2's tokenizer turns " cat" into token 3797, and that number is a label, nothing more: the ids on either side of it, 3796 and 3798, are the pieces "rief" and "esc". Nothing in 3797 says cat.
An embedding gives every token a row of numbers, a vector. In an embedding made for comparing words, tokens used in similar places get vectors that point in similar directions, and related becomes an angle you can measure.
A transformer's first layer starts from this idea, and so do semantic search and RAG.
You'll learn:
- how an id becomes a vector, in a real model's table;
- why words used alike get close vectors, counted from these very lessons;
- what the famous king and queen arithmetic does, and where it fails;
- the two kinds you will meet: token embeddings inside a model and text embeddings for search;
- how cosine similarity measures closeness, in code you run yourself.
From Arbitrary IDs to Meaningful Vectors
A model keeps its embeddings in a table: one row for each token of its vocabulary, one column for each number. Reading a token's vector is looking up its row by its id. The Transformer paper says it in passing: "we use learned embeddings to convert the input tokens and output tokens to vectors". Learned is the point: nobody types these numbers in; training sets them.
A real table is on this laptop. Whisper is OpenAI's speech recognizer, and its English-only models write their transcripts with GPT-2's tokens; its paper says they use "the same byte-level BPE text tokenizer" as GPT-2. The table of Whisper base.en holds 51,864 rows of 512 numbers. Row 3797, for " cat", begins -0.0083, 0.0154, 0.0072. Rows 3796 and 3798 hold numbers of the same kind, and their places in the table say nothing about cats.
How many numbers a token gets is a choice made with the model: 512 in Whisper base (the width in its paper's Table 1), 768 in the smallest GPT-2 (its paper's Table 2), and 128 in the vectors counted below. A row of that many numbers is a point in a space of that many dimensions.
The Meaning Space
Why would training put related tokens close together? Because of a fact about language that linguists noticed long before neural networks. Jurafsky and Martin's textbook puts it in one line: "Words that occur in similar contexts tend to have similar meanings." They call it the distributional hypothesis, and trace it to Joos, Harris and Firth in the 1950s.
So vectors can be built from contexts directly, and that is how the vectors on this page were made. We took the prose of every lesson file in CodePeet's courses, 2,146 files and 3,215,334 words, and counted how often each of the 20,000 most frequent words stands within 4 words of each other word. The counts were weighted to reward pairs that meet more often than chance (positive pointwise mutual information) and cut down to 128 numbers a word by a matrix factorization. It is no neural network, but it is close kin to one: Levy, Goldberg and Dagan point out that word2vec's training, in effect, factorizes a matrix of the same kind of weighted counts.
The words nearest database, by the cosine defined below, are databases 0.74, postgresql 0.68, mysql 0.64, sql 0.59 and relational 0.58. Nobody told the counts that PostgreSQL is a database; the words around it did. The words nearest king are rook 0.92, castling, bishop, pawn and passant: of the 88 times the prose says king, 72 are in seven lessons on designing a chess game. A vector holds the use of the text it was learned from.

The figure draws four of those neighbourhoods as islands, placed by a flat picture of their 128 numbers: read the places as near or far, and the numbers as exact.
Doing Math on Meaning
Relationships can be directions too. Mikolov and colleagues at Google, whose methods became the word2vec package, report that the vector for King, minus the one for Man, plus the one for Woman, "results in a vector that is closest to the vector representation of the word Queen". The difference between two words is an arrow; carry it to a third word and see what lies at its end.
The same test on the vectors counted from these lessons, leaving out the three words it is given (as the test must, since the nearest word is usually one of them):
- bigger minus big plus small: nearest smaller, cosine 0.53;
- reads minus read plus write: nearest writes, 0.86;
- faster minus fast plus slow: nearest slower, 0.66;
- king minus man plus woman: nearest rook, 0.73, not queen.
The three that work pair a word with another form of itself, like a relation Jurafsky and Martin list among those that do well ("verbs/nouns with their inflected forms"); for other relations, they write, "the parallelogram method with embeddings doesn't work as well". The fourth fails here for the reason king's neighbours gave: in these lessons king is a chess piece, and woman appears 3 times. The arithmetic shows what the text taught the vectors, and nothing more.
One step separates these vectors from the ones inside a modern model. A token's row in the table is the same in every sentence; a transformer's layers then change each token's vector by the words around it, so the same token leaves them as different vectors in different sentences: bank beside river, bank beside account. Ethayarajh measured how far that goes: in ELMo, BERT and GPT-2, "less than 5% of the variance in a word's contextualized representations can be explained by a static embedding for that word". How the layers do it is the subject of The Transformer Architecture — The Big Picture and Self-Attention, Intuitively.
Two Flavors: Token Embeddings vs Text Embeddings
You will meet embeddings in two roles.
Token embeddings, inside a model. The table above is the model's first layer: each token's row is what goes into the transformer. Do not expect such a table to be a ready map of meaning. In Whisper base.en's table the raw cosine between " cat" and " dog" is 0.795, lower than half of all pairs of tokens picked at random (their median is 0.867), and 11,050 of the other 50,256 tokens stand nearer to cat than dog does. Whisper also scores its next token with the same table (its model file stores one as an alias of the other). In models trained to generate text with one table tied to both ends that way, Gao and colleagues found that "most of the learnt word embeddings tend to degenerate and be distributed into a narrow cone". The table serves the model; it was not trained to make your cosines meaningful. Embedding Pitfalls (Domain Mismatch, Dimensionality) takes up what such a cone does to similarity thresholds.
Text embeddings, for your applications. Another kind of model is trained for exactly that: it turns a whole sentence or document into one vector, so that texts with similar meaning get a small angle between them. Reimers and Gurevych built Sentence-BERT to give "semantically meaningful sentence embeddings that can be compared using cosine-similarity". The simplest text vector, the average of its words' vectors, does far worse: on the STS benchmark's test set in their paper, averaged GloVe word vectors scored 58.02 and SBERT-NLI-base 77.03 (Spearman's rank correlation with the benchmark's labels, times 100).
Text embeddings are the engine of semantic search and RAG: embed the question, embed your documents, and fetch the documents whose vectors stand nearest the question's. The RAG & Retrieval Systems course builds that, from From Words to Vectors (Depth) to Building a Semantic Search Engine from Scratch.
Measuring Similarity
To turn close into a number, embeddings are compared by cosine similarity: the cosine of the angle between two vectors, which is their dot product divided by both their lengths. Jurafsky and Martin give its range: "The cosine value ranges from 1 for vectors pointing in the same direction, through 0 for orthogonal vectors, to -1 for vectors pointing in opposite directions." It ignores length and keeps direction. That matters, because a plain dot product, as they put it, "favors long vectors", and frequent words get long ones.
In code, with numpy:
import numpy as np
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
a = np.array([3.0, 4.0])
for b in ([6.0, 8.0], [4.0, -3.0], [-3.0, -4.0]):
print(b, round(float(cosine(a, np.array(b))), 2))It prints:
[6.0, 8.0] 1.0
[4.0, -3.0] 0.0
[-3.0, -4.0] -1.0[6.0, 8.0] is twice [3.0, 4.0] and scores 1.0; [4.0, -3.0] stands at a right angle and scores 0.0; [-3.0, -4.0] points the other way and scores -1.0.
Opposite directions are not opposite meanings. Opposites are used in the same places (a fast car, a slow car), so their vectors point the same way. In the vectors counted from these lessons fast and slow score 0.75 and good and bad 0.55, while two words picked at random score a median of 0.04, and 95 pairs in 100 stay below 0.22. A low cosine says two words are used in different places; it does not say they mean opposite things. Semantic Similarity: Cosine, Dot & Euclidean compares cosine with the other measures.
See It in Code: Vectors From Your Own Python
You can count vectors like these yourself, with no model and no key. Every Python carries a documented standard library; this program reads the docstrings in its top-level modules on your machine, counts which words stand within four words of which, weights the counts as above and keeps 64 numbers a word, then prints each word's four nearest by cosine. It needs numpy (pip install numpy). Save it as embed_stdlib.py and run python3 embed_stdlib.py:
# Word vectors counted from your own Python's docstrings: no model, no key.
import ast, collections, pathlib, re, sys, sysconfig
import numpy as np
lib = pathlib.Path(sysconfig.get_paths()["stdlib"])
docs = []
for path in sorted(lib.glob("*.py")):
try:
tree = ast.parse(path.read_text(encoding="utf-8"))
except (SyntaxError, UnicodeDecodeError):
continue
for node in ast.walk(tree):
kinds = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
if isinstance(node, kinds) and ast.get_docstring(node):
docs.append(re.findall(r"[a-z]+", ast.get_docstring(node).lower()))
# 1. count which words stand within four words of which
V = 2000
counts = collections.Counter(w for d in docs for w in d)
vocab = [w for w, _ in counts.most_common(V)]
idx = {w: i for i, w in enumerate(vocab)}
M = np.zeros((V, V))
for d in docs:
ids = [idx.get(w, -1) for w in d]
for i, a in enumerate(ids):
for b in ids[max(0, i - 4):i] + ids[i + 1:i + 5]:
if a >= 0 and b >= 0:
M[a, b] += 1
# 2. weight the counts (positive PMI), then keep 64 numbers a word
pw = M.sum(1) / M.sum()
pc = M.sum(0) ** 0.75
pc = pc / pc.sum()
with np.errstate(divide="ignore"):
P = np.maximum(np.log(M / M.sum() / np.outer(pw, pc)), 0)
U, S, _ = np.linalg.svd(P)
W = U[:, :64] * np.sqrt(S[:64])
W = W / np.linalg.norm(W, axis=1, keepdims=True)
# 3. a word's nearest words, by cosine
def nearest(word, k=4):
s = W @ W[idx[word]]
return ", ".join(f"{vocab[i]} {s[i]:.2f}" for i in np.argsort(-s)[1:k + 1])
print(f"Python {sys.version.split()[0]}: {len(docs)} docstrings, {M.sum():.0f} pairs")
for word in ["true", "add", "thread", "error"]:
print(f"{word:>7}: {nearest(word)}")Run in zsh on Python 3.14.7, with numpy 2.4.4 and with numpy 2.4.3, it printed the same both times:
Python 3.14.7: 3738 docstrings, 866022 pairs
true: false 0.79, is 0.63, boolean 0.57, bool 0.57
add: subtract 0.65, radd 0.58, constant 0.55, multiply 0.51
thread: lock 0.82, acquired 0.73, waiting 0.72, reentrant 0.72
error: errors 0.74, exception 0.70, raised 0.67, detected 0.65The word nearest true is false, and the word nearest add is subtract: opposites again, because docstrings use them in the same sentences. thread sits with lock, acquired and waiting, and error with errors, exception and raised. Small words such as is turn up because they stand beside nearly everything. Another version of Python holds other docstrings, so your numbers can differ.
It's Use, Not Spelling
A word-level embedding never sees letters. Each word is one row, found by its id, so spelling cannot pull two words together or push them apart: python and java share no letter and score 0.95 in the counted vectors, because these lessons use them the same way. database and databases score 0.74 because they keep the same company, not because they look alike.
That is what text embeddings are trained for, and why semantic search can find a passage that shares few words with the question, where a search for the question's words would miss it.
Try It: Find the Neighbours
Here are the vectors counted from these lessons. At first the six words you can pick are named on the map, each beside its own row of 128 numbers. Pick a word and lines go out to its five nearest, in order, with their exact cosines as bars. Pick a direction and the arrow from one word to another is carried over to a third, drawn out to where it lands, and the word nearest that point lights up.
Try database, then king: what kind of king do these lessons know? Then try each direction. Three land where you expect; one lands on rook.

Mental-Model Corrections
- Embeddings are the start, not the understanding. They are the input to the layers that do the work.
- Close means used alike, not the same. Fast and slow sit at 0.75: nearness says two words keep the same company.
- A model's own token table is not a similarity tool. In Whisper's, 11,050 tokens stand nearer to cat than dog does. Compare meanings with a model trained for text embeddings.
- Vectors from different models do not mix. Whisper's rows have 512 numbers and the counted ones 128. Even at the same length, no number means the same thing in two models: turning the counted vectors by a rotation keeps every cosine and changes every number (database's first three go from
-0.296, 0.213, 0.102to-0.049, 0.109, 0.068). Embed everything you compare with the same model. - More numbers cost more. Each vector is stored and compared number by number, so a longer one costs more room and time; whether it finds better neighbours is a measurement to make, and Matryoshka & Quantized Embeddings (Cost/Scale) takes it up.
Check Yourself
Six questions, each answered by the runs above.
Check embeddings
1 / 6Multiple choice
" cat" is token 3797. What does the number 3797 tell a model about cats?Multiple choice
Multiple choice
Multiple choice
Multiple choice
Multiple choice
Key Takeaways
- An embedding gives every token a row of learned numbers; the id only says which row.
- Words used in the same contexts get vectors at a small angle: close means used alike, opposites included.
- Cosine similarity measures that angle: 1 for the same direction, 0 at a right angle, -1 for opposite directions.
- A direction can carry a relation, as in Mikolov's king and queen, but only as far as the text the vectors came from.
- Token embeddings feed a model; text embeddings are trained for search and RAG. Compare vectors from one model only.
Next: The Transformer Architecture — The Big Picture, where these vectors go into the layers.