Lesson 2 of 95 min
Word embeddings
A model's first layer gives every token a row of numbers, its vector, and training puts tokens used alike close together.
After this lesson you can read a word as a vector and find its neighbors.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Try the famous analogy
In the lesson’s Qwen model, the closest row to king − man + woman is still king. To get queen from this example, leave the three input tokens out of the search. Run these cells in order. Keep the leading space in each token.
import torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen3.5-0.8B-Base"
revision = "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68"
tok = AutoTokenizer.from_pretrained(name, revision=revision)
model = AutoModelForCausalLM.from_pretrained(name, revision=revision).eval()
E = model.get_input_embeddings().weight.detach()
rows = F.normalize(E[:len(tok)].float(), dim=-1)king, man, woman = [tok.encode(" " + word, add_special_tokens=False)[0]
for word in ("king", "man", "woman")]
vector = E[king].float() - E[man].float() + E[woman].float()
scores = rows @ F.normalize(vector, dim=0)
print(repr(tok.decode(scores.argmax().item())))
scores[[king, man, woman]] = -float("inf")
print(repr(tok.decode(scores.argmax().item())))' king' ' queen'
One bank, two uses
The same token appears in “the bank lent money” and “the bank of a river.” Its neighbors include different spellings and 银行, the Chinese word for a financial bank. The two sentences still start from the same row.
bank, = tok.encode(" bank", add_special_tokens=False)
scores = rows @ rows[bank]
scores[bank] = -float("inf")
print([tok.decode(i) for i in scores.topk(8).indices.tolist()])[' Bank', 'bank', ' banks', 'Bank', '银行', ' BANK', ' banking', '_bank']
Search the tokenizer’s rows
Qwen’s input table has room for 248,320 rows. This tokenizer uses 248,077 of them. The first cell sliced the table before searching so each result has a token you can decode.
print(E.shape)
print(len(tok))
print(E.shape[0] - len(tok))torch.Size([248320, 1024]) 248077 243
Check which weights the model shares
Qwen reads a row from the table at the start. At the end, it uses the same weights to score the next token. You may see this called “tied embeddings.”
output_weights = model.get_output_embeddings().weight
print(output_weights.data_ptr() == E.data_ptr())True
Look up a whole word
word2vec and GloVe trained standalone word vectors. A whole-word table can use a word as the key. Here we make a tiny word-keyed lookup from three Qwen rows to see how that interface feels. Each lookup gives you the full vector.
words = ["king", "man", "woman"]
word_rows = dict(zip(words, E[[king, man, woman]]))
print(word_rows["king"].shape)torch.Size([1024])
Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Distance and cosine similarity
Your search compares sentences by their vectors, from a model that gives every vector a length of 1. Which should it rank them by?
2 of 3
Nobody told the model that "Monday" is like "Tuesday", yet their rows sit close together. How did they get close?
3 of 3
A table gives each of 1,000 tokens a row of 384 numbers. Five token numbers pick out their rows. What does this print?
import torch
from torch import nn
table = nn.Embedding(1000, 384)
ids = torch.tensor([47, 512, 3, 3, 999])
print(table(ids).shape)The ideas in this lesson
- Embedding table
- A model's first layer: one row of numbers for every token, picked by the token's number; the row is the token's vector.
- Close means used alike
- Rows start random; training moves tokens that come up in the same places close together.
- One row, any sentence
- The table gives a token the same row in every sentence, whatever the words around it.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Word embeddings
Here's a question. To a model, every token is a number. But the number says nothing about the word. So how can a model tell that Monday is like Tuesday?
Keep your guess
Did someone tell it? Or did it work it out? Hold on to your guess.
A row for each token
So what does the model do with a token's number?
It looks it up in a table. That table is the model's first layer. It holds one long row of numbers for every token in the model's list.
"Antarctic" has its number, so it gets the row with that number. That row is the token's vector. You'll also hear it called an embedding. The first tables were made for whole words, so people say "word embeddings".
Now, every token gets a row.
Seven tokens.
Seven rows.
Why a row
Why not just use the number itself? Because it's only a place in the list. Look at three pieces that sit side by side in the list. They're nothing alike. And one number puts every token on one line. Each token has room for two neighbors, one on each side.
A long row has many directions. So one token can be near many others, each in its own way, all at once.
What sits near Antarctic
Which row do you think is nearest to "Antarctic"?
Cosine similarity says how much two rows point the same way, measured on the whole row. The nearest is "Antarctica".
Then "Arctic", the other pole. Then two Chinese words: one means "Antarctic", the other "polar regions". The same word with an "a" on the end.
The other pole. The same word in Chinese. And the cold places it belongs to.
A picture of the rows
A row that long can't be drawn. So take twenty-six tokens, from four groups.
Flatten each row down to three numbers: the three directions where they differ most. About half of how they differ is kept... and the groups show up. Days. Numbers. Colors. Cold things.
Learned from use
So who put the days together?
Nobody told the model. Try this one. "See you on Blursday morning." What's Blursday?... A day. You can tell from the words around it.
Every row starts as random numbers. Then training reads a huge amount of text. Again and again, the model guesses the next token, and after every guess, the rows move a little.
Monday and Tuesday come up in the same places, after the same words.
Close means used alike
So their rows are moved the same way, and they end up close. Close means used alike. That's why the days sit together. You know what a day is. The model only knows where the word comes up.
One row, any sentence
Now a word with two meanings: "seal".
"A seal swims under the ice."
"Please seal the box."
For the seal under the ice, will the model start from an animal's row?... No. Look at its nearest rows. "Sealing". "Sealed". And a Chinese word that means "sealed shut". Closing things.
One row per token, no matter the sentence. The seal under the ice gets that row too.
Making each token's vector fit its sentence is the job of attention, later in this course.
In code
Now in real code. The table is one line: the model's input embeddings.
What's its shape?
One row for every token, and each row is long. The sentence's numbers pick out its seven rows. Cosine similarity against every row finds the rows nearest to "Antarctic". First "Antarctic" itself, then "Antarctica", then "Arctic".
And a model of your own starts with PyTorch's Embedding layer: a row for every token, as wide as you choose. The rows are random, until training moves them.
Three ideas
So every token has a row in the table: its vector. The rows are learned, so tokens used alike sit close. And a token gets the same row in every sentence.
A row for each token
Each token gets a row of numbers, learned from how it's used. Now try it on this lesson's page, and take the quiz. Find another word with its Chinese twin close by.
You use this lesson in Lab 1: Score any text, token by token, after Language modeling.
Facts last checked on .
