Meaning as geometry: embeddings
In the first part we saw that a language model reads neither letters nor words: it reads tokens, and each token is just an integer, its position in the vocabulary. But a number like 4821 says nothing. It does not say that “cat” is more like “dog” than “fridge”, nor that “king” and “queen” have something in common.
One more step is needed: turning each token into something that carries an idea of meaning. That something is an embedding, a vector of numbers. And with vectors something lovely happens: meaning becomes geometry. Similar words become nearby points, and some relationships become directions in space.
From a number to a vector
The mechanism, at first, is almost trivial. The model holds a large table, the embedding table: one row for every token in the vocabulary, and each row is a list of numbers (a few hundred or a few thousand). When token number 4821 arrives, the model goes to row 4821 and copies it. That is all: it is a simple lookup, like finding an entry in a dictionary.
The interesting part is where those numbers come from. Nobody writes them by hand: at the start of training they are random, and they are corrected, a little at a time, together with all the other weights of the network, by gradient descent (we covered it in the article on optimisers). The model arranges the rows of the table in whatever way is most useful for its task, which is predicting text. And to predict text well, it pays for words used in similar ways to have similar vectors.
“The company it keeps”: word2vec and analogies
The underlying idea is old: in 1957 the linguist J. R. Firth wrote that you shall know a word by the company it keeps. This is the distributional hypothesis: two words that appear in the same contexts (“the ___ barks”, “I take the ___ for a walk”) tend to have close meanings.
In 2013 Tomas Mikolov and colleagues, with word2vec, turned this intuition into a practical, efficient method: a small neural network learns a vector for each word by trying to guess the neighbouring words in millions of sentences. The result surprised everyone. Not only did “dog” end up near “cat”, but some relationships showed up as constant shifts. The example that became famous is:
king − man + woman ≈ queen
You take the vector for “king”, subtract the one for “man”, add the one for “woman”, and the word closest to the result is “queen”. As if space contained a “male → female” direction, and another one for “country → capital”.
It is worth being honest, though: the effect is less neat than it is often made out to be. The calculation usually excludes the three starting words (otherwise the closest word would often be “king” itself), many analogies do not work at all, and the results depend heavily on the data. It is a fascinating property, not a law.
There is also a flip side: embeddings learn from texts, and texts contain our biases. Researchers have measured vectors in which certain jobs sit closer to “man” and others to “woman”, simply because that is how they appeared in the data. The model has no opinions: it hands back, in geometric form, what it has read.
The cosine and the thousand dimensions
How do we measure how “close” two vectors are? The most common way is cosine similarity: it looks at the angle between the two arrows and ignores their length. If they point the same way it is 1, if they are perpendicular it is 0, if they are opposite it is −1. As a formula it is the dot product of the two vectors divided by the product of their lengths, but the intuition is enough: direction counts, not how long the arrow is.
The trouble is that these arrows live in spaces with hundreds or thousands of dimensions, which nobody can picture. To look at them we use reduction techniques such as PCA (which finds the two directions in which the points are most spread out) or t-SNE (which tries to preserve each point’s neighbours). They are very useful, but they distort: two words close on the map may be far apart in the real space, and vice versa. A two-dimensional map is a photograph from one angle, not the landscape.
One more warning: the individual dimensions of a real embedding have no name. There is no “gender” or “animal” column. The information is spread out and mixed across all the coordinates.
Embeddings that depend on context
word2vec gives each word a single vector. But think of “bank”: “we sat on the bank of the river” and “I opened a bank account” use the same word for two different things. A single vector has to make an awkward average of the two meanings.
In modern language models the embedding table is only the starting point. The token’s vector enters the stack of layers of the Transformer, and each layer modifies it by looking at the other words in the sentence. At the output, “bank” next to “river” and “bank” next to “account” have become different vectors: contextual embeddings. The mechanism that lets each word “look at” the others is called attention, and it will be the subject of part four.
The same principle works for whole sentences too. There are models trained specifically to produce one vector per sentence, so that sentences with the same meaning end up close together even when they use different words. This is the basis of semantic search: instead of looking for the exact words, you look for the text whose vector is closest to the question’s. We will come back to it in part six, when we give the model documents to consult.
A toy space to explore
The demo below is a toy space, built by hand precisely to see these ideas. Each word has a vector of 8 numbers with a readable meaning (royalty, gender, age, person, animal, food, technology, place). The map is a real PCA computed in the browser.
What to try in the demo
- Tap a word on the map: lines connect it to the 5 words with the highest cosine, and on the right its vector appears as a strip of bars.
- Look at the starting analogy, king − man + woman: the dashed arrow from “man” to “king” is copied starting from “woman” and lands near “queen”.
- Press Another example to try bull − man + woman, puppy − dog + cat, lion − king + queen. Then make up your own: you will notice that many combinations give meaningless results.
- Select “bread” or “computer”: some words have identical vectors, because 8 features are not enough to tell them apart. That is why real embeddings have hundreds of dimensions.
- Read the percentage at the bottom of the map: it is the share of variance the PCA manages to show. The rest is hidden, and indeed two words close on the map are not always similar in the table.
In Python
With the sentence-transformers library a few lines are enough to turn sentences into vectors and compare them:
from sentence_transformers import SentenceTransformer, util
# a small, fast model for sentence embeddings
model = SentenceTransformer("all-MiniLM-L6-v2")
sentences = [
"The cat is sleeping on the sofa.",
"A kitten is napping on the couch.",
"The bank has raised interest rates.",
"My mortgage will cost more this year.",
"It will rain across the region tomorrow.",
]
# every sentence becomes a vector
vectors = model.encode(sentences, convert_to_tensor=True)
print(vectors.shape)
# cosine similarity between all pairs of sentences
sim = util.cos_sim(vectors, vectors)
# the most similar pair (excluding each sentence with itself)
pairs = [(i, j) for i in range(len(sentences)) for j in range(i + 1, len(sentences))]
i, j = max(pairs, key=lambda p: sim[p[0], p[1]].item())
print(f"{sim[i, j].item():.2f} {sentences[i]} <-> {sentences[j]}")
The first line printed is the shape of the matrix, torch.Size([5, 384]): five sentences, each turned into a vector of 384 numbers. The second shows the most similar pair, which will almost certainly be the cat and the kitten, even though they share hardly any words.
To me, embeddings are the most elegant idea of the whole journey: they turn something as elusive as meaning into distances and directions you can compute. If you want to go further, chapter 9 of my book Deep Learning con Keras e Tensorflow (in Italian) is devoted to natural language processing. But a vector for each word, on its own, writes nothing. In the next part we will see how a model uses these vectors to do the one thing it really knows how to do: predicting the next word.