Transformers, Part 1: Why They Exist, and How Words Become Vectors

TL;DR

  • A language model has one job: given some text, output a probability for every possible next word.
  • RNNs did this by reading one word at a time and carrying a running summary. That summary is a bottleneck, the training signal fades over long distances, and the loop cannot be parallelised.
  • A transformer drops the loop. Every word looks at every other word directly, all at once.
  • Before any of that can happen, words have to become numbers. One-hot vectors are the obvious way to do it and they fail: they are huge, and they say every word is equally unrelated to every other word.
  • An embedding is a learned table with one short, dense vector per word. Mathematically it is a one-hot vector multiplied by a matrix, which collapses to “pick row ”.
  • Nobody designs those vectors. They are trained by the next-word objective, and words that are used the same way end up with similar vectors. We train one from scratch below and watch it happen.

This is Part 1 of a series. Each post takes one stage of the transformer, builds the intuition first, then does the math with small numbers you can check by hand, then writes the code.

The series plan

I was recently trying to understand and build intuition around Transformers from the first principle or why they exist. So i decided to write about each and step as i read about it more.

Part Stage The question it answers
1 (this post) Introduction and embeddings Why transformers, and how does a word become a vector?
2 Positional encoding How does the model know word order?
3 Self-attention How do words look at each other?
4 Multi-head attention Why look in several ways at once?
5 Feed-forward layers, residuals, normalisation What else is inside a block, and why does it train?
6 Output and training How do vectors turn back into a next word?

The plan may shift a little as the series goes on(is not written on stones after all), but the order follows the path data takes through the model.

1. The goal: just predict the next word

Strip away the hype and a language model does one thing. You give it some text() and it gives back a probability for every word in its vocabulary being the next one():

We are going to treat the model as a sealed box for now(:wink :wink):

A language model drawn as one box. The words the, cat, sat and on go in at the top. Under each word the model outputs a bar chart of probabilities over the vocabulary, and the bar for the true next word (cat, sat, on, the) is highlighted, with the note that training pushes that probability to be high.

Going from left to the right, “the box” puts out a full set of probabilities, one bar per word in the vocabulary (the bar lengths here are only illustrative). The prediction under the word may use the previous words but nothing after it, eg. the prediction under “sat” may use the first three words, and so on.

The picture shows both things we do with such a model:

  • Training. We already know the real text, so at every position we know which bar should have been tall. After “the” came “cat”, so we nudge the model to make P(“cat”) a little higher there, and likewise at every other position. One sentence gives one small lesson per word. This is the entire training signal. Nobody labels anything; the text is its own answer key.
  • Generating. We only look at the bars under the last word. Pick a word from them, append it to the text, and run the box again with the longer text. Everything a chatbot produces comes out of that loop.

What is inside the box is the subject of this whole series. Transformers are pretty recent as a technology so we will try to back and see what worked before and what were the limitations.

The simplest model that works: counting

Say we have this collection of text that we will use to train our model(a corpus). A ten-sentence corpus that we will use for the whole post:

corpus = """
the cat sat on the mat .
the dog sat on the rug .
the cat chased the mouse .
the dog chased the cat .
the cat ate the fish .
the dog ate the bone .
the king ruled the land .
the queen ruled the land .
the king wore a crown .
the queen wore a crown .
"""

Then let’s build the dumbest possible version of a model and try to show exactly what goes wrong. We will treat the corpus as a bag of words we do not care about their possition/order at all just. we just care about a unique word and how often they appeared so say in a bag we will have cat and its frequency of appearance(3). Lets build our bag of words.

import numpy as np
tokens = corpus.split()
vocab = sorted(set(tokens))
stoi = {w: i for i, w in enumerate(vocab)}   # word -> integer ID
V = len(vocab)

print(len(tokens), "tokens,", V, "unique")   # 62 tokens, 20 unique

What if we can have a model(bigram) that just asumes the next word sorely based on the one immediately before it(current word), The Markov assumption. It estimates the probability by counting how often each word follows each other word:

Here is the previous token, is the next token, and count is how often that pair appears together. For example, if “the” appears 1,000 times and is followed by “cat” 50 times, then .

The assumption:

we can impliment the model:

counts = np.zeros((V, V))
for prev, nxt in zip(tokens[:-1], tokens[1:]):
    counts[stoi[prev], stoi[nxt]] += 1

P = counts / counts.sum(axis=1, keepdims=True)   # P[i, j] = P(next = j | current = i)

That matrix P is the entire model. It has one row per current word and one column per possible next word:

The 20 by 20 bigram transition matrix for the corpus. Most rows contain a single 1. The row for “the” is outlined and spreads its probability over ten words.

Use it as a lookup table. Find the row for the word you are on(the current word), and that row is the prediction: each cell is the probability that the column’s word comes next, and every row adds up to 1. Blank cells are zero.

Most of this language is predictable. Fifteen of the twenty rows hold a single 1(the model is very sure what comes next): after “sat” comes “on”, after “wore” comes “a”, every time. All the uncertainty(the model is sure only by certain percent) sits in five rows: “the”, “cat”, “dog”, “king” and “queen”.

Take the outlined row. The word “the” appears 18 times, and here is what follows it(probability of next word given “the”):

Next word Count
cat 4 4/18 = 0.222
dog 3 3/18 = 0.167
king, queen, land 2 each 2/18 = 0.111
mat, rug, mouse, fish, bone 1 each 1/18 = 0.056

That row is a complete next-word prediction.

The same model as a picture

Here is the part of the graph you reach by starting at “the”, with only the branch through “cat” followed further:

The bigram model as a Markov chain. Ten arrows leave “the”, with probabilities from 0.22 for “cat” down to 0.06. Four arrows leave “cat”, each 0.25. From “chased” and “ate” a dashed arrow with probability 1.0 leads back to “the”.

Thicker arrows are more likely steps, and the arrows leaving any node add up to 1. Generating text is a walk through this graph: stand on a word, pick an outgoing arrow at random according to its probability, follow it, repeat.

This kind of model has a name. It is a Markov chain, and specifically a first-order one, because the next step depends only on the node you are standing on and not on the path that brought you there. That property is what makes the model so small. It is also what breaks it, and the dashed red path in the picture shows where.

Prediction: Generating text, and where it goes wrong

Now Lets generate the sentence which starts with the and have at most 12 words.We can start our output(out) at “the”, sample a next word from its row, move to that word, repeat until a full stop.

def generate(seed):
    # Seeded random number generator, so the same seed always gives the same sentence
    rng = np.random.default_rng(seed)

    # Every sentence starts with "the"; `out` collects the generated words
    word, out = "the", ["the"]

    # Keep generating until we produce a full stop or hit 12 words (a safety cap)
    while word != "." and len(out) < 12:
        # P[stoi[word]] is the row of bigram probabilities P(next | word):
        # one probability for every word in the vocabulary, summing to 1.
        # Sample an index from that distribution, then turn it back into a word.
        word = vocab[rng.choice(V, p=P[stoi[word]])]

        # Append the new word; it becomes the "previous word" for the next step
        out.append(word)

    return " ".join(out)

print(generate(1))   # the king wore a crown .
print(generate(2))   # the cat ate the cat chased the cat .

The first sample is fine. The second one is the problem in one line, and it is the dashed red path from the picture: “the” to “cat” to “ate”, then back to “the” with probability 1. Once the walk is standing on “the” again, it has no idea that a cat is already eating. It is on the same node as at the start, so it rolls the same dice as before, and this time they come up “cat” again.

Why not just remember more words?

The obvious fix is to condition on the last two words, or five or eight instead of just previous one. The table explodes:

  • With our 20 words, a 5-word context has possible rows. We have 62 tokens of data to fill them.
  • With GPT-2’s vocabulary of 50,257 tokens, even a 2-word context has billion rows.

Almost every row would be empty. And there is a second, quieter problem: the table treats every word as an unrelated symbol. Having seen “the cat sat on the mat” tells it nothing about “the dog sat on the mat”, because “cat” and “dog” are just two different row labels.

So we need two things:

  1. A way to use long context without a table that grows exponentially.
  2. A way to share what is learned between similar words.

The second one is what embeddings solve, and it is the main subject of this post. The first one is the story of RNNs and then transformers, so let’s take that first.

2. Before transformers: reading one word at a time

A recurrent neural network1 handles long context with a simple idea: keep a running summary. Read a word, update the summary, move on.

  • is the vector for the word at position .
  • is the summary of everything read so far, called the hidden state.
  • is the updated summary, which is then used to predict word .

The usual way to draw this is on the left below: one box that feeds its own output back into itself. That loop is easier to reason about if you unroll it.

A recurrent neural network drawn folded, as one box with a loop, and unrolled over three time steps. Hidden states h at t minus 2, t minus 1 and t are chained left to right. Each takes an input word from below (sat, on, the) and predicts the next word above (on, the, mat).

Read the unrolled side from left to right. At each step the box takes two things, the current word from below and the previous hidden state from the left, and produces a new hidden state. That state does two jobs: it goes up to predict the next word, and it goes right to become the memory for the next step. The copies are not separate networks. They are the same box with the same weights and , applied once per word.

Notice the only route by which an earlier word can influence a later prediction: along the blue arrows, through every box in between. For “sat” to matter when predicting “mat”, it has to survive inside , then , then .

Think of someone reading a book through a keyhole, one word at a time, with a single sticky note to write on. The sticky note is the hidden state. After each word they rewrite the note. The note has a fixed size no matter how long the book is, and the same weights are reused at every step. No exploding table.

This worked well enough to power machine translation for years.2 It also has three problems that are built into the design.

Problem 1: everything squeezes through one vector

Take this sentence:

The keys that I left on the kitchen table next to the flowers are missing.

To choose “are” over “is”, the model must still know that the subject was plural “keys”, with eleven words in between. That fact has to survive every one of those rewrites of the sticky note, competing for space with kitchens, tables and flowers. Nothing lets the model go back and look at “keys” again.

Problem 2: the training signal fades with distance

Training has the same problem in reverse. To learn that “keys” matters for “are”, the error at “are” has to travel backwards through every step in between(back propagation): in the unrolled diagram, right to left along the blue arrows. Each step multiplies it by a factor:

A product of many factors behaves like a power. If each step scales the signal by 0.9, it vanishes. If each step scales it by 1.1, it blows up:

Per-step factor After 10 steps After 50 steps After 100 steps
0.9 0.349 0.00515 0.0000266
1.0 1 1 1
1.1 2.59 117 13,800

This is the vanishing and exploding gradient problem.34 It is easy to see on a real RNN. The code below runs a random 16-unit RNN for 50 steps, then measures how much the final state depends on the state steps earlier:

rng = np.random.default_rng(0)
H, T = 16, 50
Wh = rng.normal(0, 1 / np.sqrt(H), (H, H))
Wx = rng.normal(0, 1 / np.sqrt(H), (H, H))

h, hs = np.zeros(H), []
for t in range(T):                                   # forward pass on random inputs
    h = np.tanh(Wh @ h + Wx @ rng.normal(size=H))
    hs.append(h)

J = np.eye(H)                                        # J = d h_T / d h_(T-k)
for k in range(1, 41):
    J = J @ (np.diag(1 - hs[T - k] ** 2) @ Wh)
    if k in (1, 5, 10, 20, 40):
        print(k, f"{np.linalg.norm(J):.2e}")
Steps back, Size of
1 2.39
5 0.171
10 0.0114
20 0.000401
40 0.000000397

A word that was 40 steps back influences the final state about six million times less than the previous word does. The model can barely learn from it.

LSTMs5 add gates that protect the summary and ease this a lot, but the information still travels step by step. RNN and LSTMs have so so much lore i i havent even scratched a surface of what it was capable of doing. Probably need to write about it mmh.

Problem 3: the loop cannot be parallelised

needs , which needs , and so on. A 1,000-word document takes 1,000 sequential steps, and a GPU that could do thousands of things at once spends its time waiting. That limits how much data you can train on, and data is what makes these models good.

The patch that became the whole model

In 2014, Bahdanau et al.6 added a fix for Problem 1 called attention: when producing each output word, let the model look back at all the earlier hidden states and take a weighted mix of the relevant ones, instead of relying on the last summary alone. It helped a great deal.

Three years later, Vaswani et al.7 asked the obvious follow-up. If attention is doing the heavy lifting, do we need the recurrent loop at all? Their paper is titled Attention Is All You Need, and the model in it is the transformer.

3. The transformer in one picture

A transformer removes the keyhole. Every word can look directly at every other word, in one step, and all positions are processed at the same time.

The transformer pipeline in three stages. Input: text is split into tokens, mapped to token IDs, looked up as embedding vectors, and given position information. Transformer block, stacked N times: self-attention, then a feed-forward network. Output: a probability per vocabulary word, from which the next token is picked.

Reading the diagram from left to right:

  • Input. Text is split into tokens, and each token is swapped for an integer ID. Each ID is then turned into a vector, its embedding. That highlighted row is this post. Finally, information about position is added, because the next stage has no built-in sense of order.
  • Transformer block. A stack of identical blocks refines the vectors. In each block, self-attention lets tokens exchange information, then a small feed-forward network processes each token on its own.
  • Output. The last token’s final vector is turned into a probability for every word in the vocabulary, and a next token is picked. That token is appended to the text and the whole pipeline runs again.

Here is how that compares with an RNN on the three problems above. is the sequence length.

RNN Transformer
Steps for word 1 to affect word 1
Sequential operations per layer 1, all positions in parallel
Memory of the past One fixed-size vector All previous token vectors stay available
Knows word order Yes, by construction No, it has to be added (Part 2)
Cost per layer Grows like Grows like , every pair of tokens

It is not free. Attention compares every token with every other token, so cost grows with the square of the length, and word order has to be put back in by hand. Those are the trade-offs the rest of the series deals with.

For now, look at the first few rows of the input stage. Whatever the model is, RNN or transformer, it does arithmetic, and you cannot do arithmetic on the string “cat”. Because modern computers are based on the Von Neumann architecture(:sad_face). The first thing any of these models needs is a way to turn words into numbers. That choice matters more than it looks.

4. Step zero: tokens and IDs

We already did this in the counting model. Every unique token gets an integer:

print({w: stoi[w] for w in ["cat", "chased", "crown", "dog", "king"]})
# {'cat': 4, 'chased': 5, 'crown': 6, 'dog': 7, 'king': 9}

Real models split text into sub-word pieces rather than whole words, so that rare words can be built from common fragments. GPT-2 has 50,257 such tokens. I will keep using whole words here because the idea is the same and the examples are easier to read. Tokenization is actually a very lengthy topic itself, which needs a whole blog actually

Could we just feed the ID into the network as a number? No, and it is worth seeing why. A network multiplies and adds its inputs, so it would treat the IDs as quantities:

  • “king” (9) would be more than twice as much as “cat” (4). Twice as much what?
  • The average of “cat” (4) and “crown” (6) would be 5, which is “chased”.

The IDs came from sorting alphabetically. Their order and spacing mean nothing, but a network would try to use them anyway. An ID is a name, not a measurement. We need a representation that does not invent relationships that are not there.

5. One-hot encoding: honest, but not enough

The standard way to represent a name without implying any order is a one-hot vector: a vector as long as the vocabulary, all zeros, with a single 1 at the word’s ID.

To keep the vectors small enough to print, take just the five distinct words in “the cat sat on the mat”. Sort them and give each one a slot: “cat” gets slot 0, “mat” slot 1, and so on. Each word of the sentence then becomes a row of five numbers, with a 1 in its own slot and 0 everywhere else:

The sentence “the cat sat on the mat” as one-hot vectors. A vocabulary of five words gives five slots: cat, mat, on, sat, the. Each of the six words becomes a row of five cells with a single 1 in its own slot. Both rows for “the” are identical. Below, a strip of 50,257 slots shows how long each row would be with GPT-2’s vocabulary, with only the slot for “cat” set to 1.

Two things are visible straight away. Every row is mostly zeros. And a row only says which word it is: “the” appears twice and gets exactly the same row both times. Here is the same thing in code:

small = sorted(set("the cat sat on the mat".split()))
s2i = {w: i for i, w in enumerate(small)}   # {'cat': 0, 'mat': 1, 'on': 2, 'sat': 3, 'the': 4}

def one_hot(i, size):
    v = np.zeros(size)
    v[i] = 1.0
    return v

sentence = "the cat sat on the mat".split()
X1 = np.stack([one_hot(s2i[w], len(small)) for w in sentence])
print(X1)
         cat mat on sat the
the    [[ 0.  0.  0.  0.  1.]
cat     [ 1.  0.  0.  0.  0.]
sat     [ 0.  0.  0.  1.  0.]
on      [ 0.  0.  1.  0.  0.]
the     [ 0.  0.  0.  0.  1.]
mat     [ 0.  1.  0.  0.  0.]]

(Row and column labels added by hand.) Six words in, a matrix out. This fixes the fake-ordering problem: no word is “bigger” than another. But it creates two new ones.

Problem 1: size

Each vector is as long as the vocabulary. For our six-word sentence with GPT-2’s vocabulary:

That is the long strip at the bottom of the picture: a lot of memory and multiplication spent on zeros.

Problem 2: every word is equally far from every other word

This is the one that really hurts. Take any two different one-hot vectors, say “cat” and “mat” . Their 1s are in different places, so:

a, b = one_hot(s2i["cat"], 5), one_hot(s2i["mat"], 5)
print(a @ b, np.linalg.norm(a - b))   # 0.0 1.4142135623730951

The same two numbers come out for every pair. “cat” is exactly as far from “dog” as it is from “the” or from “crown”. The representation states, as a matter of geometry, that no two words have anything in common.

That brings back the sharing problem from Section 1. Whatever the model learns about “cat” lives in the weights attached to cat’s own input slot. None of it transfers to “dog”, because the two inputs do not overlap anywhere. The model has to learn every fact once per word.

What we want is the opposite: a representation where words that behave alike sit close together, so that learning about one automatically teaches the model about its neighbours.

That does not mean throwing one-hot vectors away. They are still the right way to say which word we have. What they cannot do on their own is say anything about what the word means. The next section keeps them and puts one learned matrix after them.

6. Embeddings: a learned lookup table

Here is the idea. Give every word a short vector of real numbers, say of them, and let all the values be free. Stack the vectors into a matrix with one row per word:

That matrix is the embedding table, and row is the embedding of word . Compared with one-hot vectors:

One-hot Embedding
Length (50,257 for GPT-2) (768 for GPT-2 small)
Values A single 1, the rest 0 All real numbers, all used
Similarity between words Always 0 Anything, and it is learned
Who sets the values A fixed rule Training

With five words and , a table might start out like this (random numbers, they mean nothing yet):

rng = np.random.default_rng(42)
E = rng.normal(0, 1, (5, 3)).round(2)
print(E)
cat  [[ 0.3  -1.04  0.75]
mat   [ 0.94 -1.95 -1.3 ]
on    [ 0.13 -0.32 -0.02]
sat   [-0.85  0.88  0.78]
the   [ 0.07  1.13  0.47]]

The math: a one-hot vector times a matrix is a row lookup

Embeddings do not replace one-hot vectors so much as absorb them. Multiply the one-hot vector for “sat” by :

Every row is multiplied by 0 except row 3, which is multiplied by 1. The result is row 3. So “one-hot vector followed by a linear layer with no bias” and “look up row ” are the same operation, and the second one skips all the multiplying by zero:

print(one_hot(s2i["sat"], 5) @ E)   # [-0.85  0.88  0.78]
print(E[s2i["sat"]])                # [-0.85  0.88  0.78]

A whole sentence is one indexing operation:

ids = [s2i[w] for w in sentence]    # [4, 0, 3, 2, 4, 1]
X = E[ids]
print(X.shape)                      # (6, 3)
print(np.allclose(X1 @ E, X))       # True
the  [[ 0.07  1.13  0.47]
cat   [ 0.3  -1.04  0.75]
sat   [-0.85  0.88  0.78]
on    [ 0.13 -0.32 -0.02]
the   [ 0.07  1.13  0.47]
mat   [ 0.94 -1.95 -1.3 ]]

In matrix terms, a sequence of tokens becomes an one-hot matrix, and multiplying it by the embedding table gives an matrix:

Here , and . Six tokens in, a matrix out: one row per token, in sentence order. Notice that both occurrences of “the” get the identical vector. Hold on to that; it matters at the end.

This also explains the parameter count. An embedding table for GPT-2 small has

numbers in it, which is about 31% of that model’s 124 million parameters.

7. Where the meaning comes from

So far the table is full of random numbers. The interesting part is that nobody ever fills it in. The embedding table is a weight matrix like any other, and it is trained by the same next-word objective as the rest of the model.

The intuition is an old one from linguistics: “You shall know a word by the company it keeps”.8 If “cat” and “dog” are followed by the same kinds of words, then a model that predicts the next word well is best served by giving them similar vectors. Bengio et al.9 built the first neural language model on exactly this idea, and word2vec10 later showed how rich these learned vectors can become.

Let’s watch it happen on our corpus with the smallest model that has an embedding in it.

A neural bigram model

Take the current word(i), look up its embedding(E(i)), apply one linear layer to get a score(z) for each vocabulary word, and turn the scores into probabilities() with a softmax:

The loss for one training pair (current word , true next word ) is the cross-entropy, which is small when the model gave the true next word a high probability:

It is the counting model from Section 1 again, but routed through a 2-dimensional embedding, so each word must be summarised in two numbers. I use so that the result can be plotted directly, with no dimensionality reduction.

The gradient only touches the rows that were used

Backpropagation gives three short results. Writing 𝟙 for the one-hot vector of the true next word:

𝟙𝟙

The last one is the lookup run backwards. It is a matrix that is zero everywhere except row . A training pair that starts with “the” updates the embedding of “the” and no other row.

That is why usage shapes the vectors. Each word’s row is pushed only by the contexts that word actually appeared in, so two words that appear in the same contexts get pushed the same way.

Training it

ids = np.array([stoi[t] for t in tokens])
X, Y = ids[:-1], ids[1:]            # 61 (current word, next word) pairs
N, d = len(X), 2

rng = np.random.default_rng(0)
E = rng.normal(0, 0.1, (V, d))      # embedding table, 20 x 2
W = rng.normal(0, 0.1, (d, V))      # output layer, 2 x 20
b = np.zeros(V)

lr = 0.5
for step in range(3001):
    # forward
    h = E[X]                                          # lookup, (61, 2)
    z = h @ W + b                                     # scores, (61, 20)
    z = z - z.max(axis=1, keepdims=True)              # for numerical stability
    p = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True)
    loss = -np.log(p[np.arange(N), Y]).mean()
    if step in (0, 100, 1000, 3000):
        print(step, f"{loss:.3f}")

    # backward
    dz = p.copy()
    dz[np.arange(N), Y] -= 1                          # p - onehot(y)
    dz /= N
    dW, db, dh = h.T @ dz, dz.sum(axis=0), dz @ W.T
    dE = np.zeros_like(E)
    np.add.at(dE, X, dh)                              # scatter each dh into its word's row

    # update
    E -= lr * dE
    W -= lr * dW
    b -= lr * db
Step Loss
0 2.995
100 1.755
1000 0.863
3000 0.835

Two reference points make those numbers readable:

  • Start, 2.995. A model that knows nothing spreads its probability evenly over 20 words, and . Right where we began.
  • Best possible, 0.830. No bigram model can do better than the count table from Section 1, because after “the” there really are ten different continuations in the data. Scoring the count table on the same pairs gives 0.830.

So the model ends within 0.005 of the best a bigram model can do, even though each word has been squeezed into two numbers. Its prediction after “the” matches the count table closely:

Next word Count table Neural model
cat 0.222 0.222
dog 0.167 0.167
king, queen, land 0.111 0.111
mat, rug, mouse, fish, bone 0.056 0.055

What the embeddings learned

Here are the vectors before and after training.

Word embeddings in two dimensions before training and after 3,000 steps

Before training the points are random noise near zero. Afterwards they have organised themselves, and the organisation follows usage:

  • king and queen land on the same point, . In this corpus both are followed by “ruled” or “wore” and nothing else, so nothing in the data pulls them apart.
  • cat and dog sit near each other. Both are followed by “sat”, “chased” and “ate”. They are not identical because “cat” also ends a sentence once (“the dog chased the cat .”) and “dog” never does.
  • mat, rug, mouse, fish, bone, land, crown collapse into one cluster. Each is always followed by a full stop.
  • ate, chased, ruled, on and the full stop share a point too. Every one of them is always followed by “the”.

Nobody told the model that kings and queens are related, or that cats and dogs are. That fell out of predicting the next word.

Measuring it: cosine similarity

The usual way to compare two embeddings is the cosine of the angle between them, which ignores length and looks only at direction:

It is 1 for the same direction, 0 for perpendicular, and for opposite. By hand for “cat” and “dog”:

def cos(u, v):
    return u @ v / (np.linalg.norm(u) * np.linalg.norm(v))

for u, v in [("king", "queen"), ("cat", "dog"), ("mat", "rug"), ("cat", "king")]:
    print(u, v, f"{cos(E[stoi[u]], E[stoi[v]]):.2f}")
Pair Cosine similarity
king, queen 1.00
mat, rug 1.00
cat, dog 0.82
cat, king −0.98

Compare that with one-hot vectors, where every one of those pairs scores exactly 0:

Cosine similarity between seven words under one-hot encoding and under the learned embeddings

The left panel is the one-hot world: a diagonal and nothing else. The right panel is what training produced.

About the toy example

Three caveats, so this example is not oversold:

  • It only clusters by the next word. A bigram model sees one word of context, so “similar” here means “followed by the same things”. That is why “on” lands with the verbs. A transformer’s embeddings are shaped by gradients coming back through the whole model and the whole context, so they capture far more.
  • Two dimensions is very tight. “cat” and “king” come out as near-opposites partly because there are only so many directions in a plane. Real models use hundreds or thousands of dimensions, which leaves room for many independent kinds of similarity at once.
  • 62 tokens is nothing. “king” and “queen” are identical here only because this corpus never uses them differently.

The mechanism, though, is exactly the one used in real models: a lookup table, trained by next-word prediction, where gradients flow only to the rows that were used.

8. Embeddings inside a real transformer

In PyTorch the table is one line. nn.Embedding is a matrix of trainable weights with indexing as its forward pass:

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)
emb = nn.Embedding(num_embeddings=V, embedding_dim=4)       # 20 x 4 table

token_ids = torch.tensor([stoi[w] for w in sentence])
print(token_ids)            # tensor([18,  4, 17, 13, 18, 11])

x = emb(token_ids)
print(x.shape)              # torch.Size([6, 4])

# same thing as one-hot times the weight matrix
onehot = F.one_hot(token_ids, num_classes=V).float()        # 6 x 20
print(torch.allclose(onehot @ emb.weight, x))               # True

Notice that the code never builds a one-hot matrix. nn.Embedding takes the token IDs and copies out the matching rows, the same E[ids] indexing we used in NumPy. The one-hot product is how to think about the operation, and the last line shows it gives the same answer, but building an matrix of mostly zeros just to multiply it would waste memory and time. The backward pass works the same way: gradients are added straight into the rows that were looked up.

The output has shape (sequence length, ). With a batch of sentences it becomes (batch, sequence length, ), and that is the tensor every later stage of the transformer works on. The width is called and stays the same through the whole stack.

Some sizes from real models:

Model Vocabulary Width Embedding parameters
This post 20 2 40
Transformer, base7 about 37,000 512 about 19 million
GPT-2 small11 50,257 768 38,597,376

Two details from the original paper are worth knowing now, even though they only fully make sense later in the series:

  • Scaling. The paper multiplies the embeddings by , which is , before adding position information.
  • Weight tying. The last step of the model turns a vector back into a score per vocabulary word, which needs a matrix. The paper reuses the embedding table for that, following Press & Wolf.12 The same matrix maps words to vectors on the way in and vectors to words on the way out. In our toy model that would mean setting .

9. What embeddings cannot do

Embeddings solve the sharing problem. They leave two things unsolved, and both are visible in the examples above.

They have no idea about order. Look up the embeddings for these two sentences:

dog bites man

man bites dog

You get the same three vectors both times, just in a different arrangement. An RNN would notice the arrangement, because it reads in order. A transformer looks at all tokens at once, and as we will see, its attention mechanism does not care which row is which. Without help, it would treat the two sentences as the same bag of words.

They have no idea about context. In Section 6 both occurrences of “the” got the identical vector. That is harmless for “the”, but consider:

I sat on the river bank.

I deposited cash at the bank.

One row in the table, one vector, two meanings. The embedding is a starting point for a word’s meaning, an average over every way the word is used. Working out which meaning applies here requires looking at the neighbouring words.

Those two gaps are the next two stages of the transformer:

  • Part 2, positional encoding, puts word order back into the vectors.
  • Part 3, self-attention, lets each word’s vector be updated by the words around it, so that “bank” next to “river” and “bank” next to “cash” stop being the same thing.

Recap

  • A language model predicts the next word. Counting tables cannot scale to long contexts and cannot share knowledge between similar words.
  • RNNs handle long context with a running summary, at the price of a bottleneck, fading gradients and no parallelism. Transformers replace the loop with direct, parallel connections between all tokens.
  • Token IDs are names, not quantities. One-hot vectors respect that but are huge and make every pair of words equally unrelated: dot product 0, distance .
  • An embedding table stores one dense vector per word. Multiplying a one-hot vector by is the same as selecting a row.
  • The table is trained by next-word prediction. Gradients reach only the rows that were used, so words used alike drift together. On a 62-token corpus, “king” and “queen” ended up at cosine similarity 1.00 and “cat” and “dog” at 0.82, with nobody telling the model they were related.
  • Embeddings alone know nothing about order or context. That is what the rest of the transformer is for.

Notes

  1. Elman, J. L. (1990). Finding structure in time. Cognitive Science, 14(2), 179–211. ↩

  2. Sutskever, I., Vinyals, O., & Le, Q. V. (2014). Sequence to sequence learning with neural networks. Advances in Neural Information Processing Systems 27 (NIPS 2014). ↩

  3. Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157–166. ↩

  4. Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. Proceedings of the 30th International Conference on Machine Learning (ICML). ↩

  5. Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780. ↩

  6. Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate. arXiv:1409.0473. ↩

  7. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems 30 (NIPS 2017). ↩ ↩2

  8. Firth, J. R. (1957). A synopsis of linguistic theory, 1930–1955. In Studies in Linguistic Analysis (pp. 1–32). Oxford: Blackwell. ↩

  9. Bengio, Y., Ducharme, R., Vincent, P., & Jauvin, C. (2003). A neural probabilistic language model. Journal of Machine Learning Research, 3, 1137–1155. ↩

  10. Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient estimation of word representations in vector space. arXiv:1301.3781. ↩

  11. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners. OpenAI. ↩

  12. Press, O., & Wolf, L. (2017). Using the output embedding to improve language models. Proceedings of EACL 2017. ↩

Citation

Please cite this work as:

Makonda, Barnabas, "Transformers, Part 1: Why They Exist, and How Words Become Vectors", Barnabas Makonda's blog, Nov 2026.

Or use the BibTeX citation:

bibtex
@misc{makonda2026transformers,
  author = {Barnabas Makonda},
  title = {Transformers, Part 1: Why They Exist, and How Words Become Vectors},
  howpublished = {Barnabas Makonda's blog},
  year = {2026},
  month = {nov},
  url = {https://blog.barnabasmakonda.workers.dev/posts/transformers-part-1-embeddings/},
}