TL;DR
An embedding layer is a table of learned numbers. It has one row for each category, such as each word in a vocabulary, and a lookup returns the row for the category it is given. The row is a short list of numbers, so the model works with a compact vector instead of a long one-hot vector. The table is trained together with the rest of the network, so categories that behave alike end up with rows that are alike.
Builds on: One-Hot Encoding, Matrix Multiplication · Leads to: Word Embedding, Language Model, Recommender System
Where it's used
The first layer of language models. A Language Model reads text as a sequence of tokens, each one a word or a piece of a word from a fixed list. The first layer maps each token to its embedding row. Transformer-based text models start this way, and the embedding table can be a large share of all the weights in a small model.
Recommender systems. A video service with millions of titles can give each title a row in an embedding table, and each user a row in a second table. The model then scores a user against a title with a dot product of their two rows. This is the idea behind the Matrix Factorization family of recommenders, now trained with the same tools as neural networks.
Categorical features in tabular models. A bank's model may have a column for the merchant category, with a few hundred values. Instead of a few hundred one-hot columns, the model can learn a row of, say, 8 numbers per category. Similar merchants can then share similar rows, something a one-hot column cannot express.
How it works
Take a tiny example. There are three colours, red, green and blue, and we want each one as a vector with two numbers. The embedding table is a grid of learned numbers with three rows and two columns.
-
Start with a table of numbers. Suppose training has produced these rows: red is , green is , blue is . Check: there are three rows, one per colour, and two numbers in each row.
-
Get the index of the input. The input is the colour green. Its index in the colour list is 2. Check: the index is the position of the category in the list, starting from 1.
-
Look up the row. Go to row 2 of the table and read it off. The result is . Check: the lookup copies one row and does no arithmetic.
-
Pass the vector on. The vector is the input to the next layer of the network. Check: the next layer sees two numbers, not three, and not a one-hot vector.
-
Update the row during training. Suppose the gradient of the loss with respect to the green row is , and the learning rate is . A step goes against the gradient, so it subtracts the scaled gradient. The new green row is . Check: only row 2 changed. Red and blue rows are untouched.
The learning is the important part. The numbers in the table are not chosen by hand. They start random and move, step by step, toward whatever makes the loss smaller. Colours that the task treats alike are pushed toward similar rows.
flowchart LR
A["Category: green"] --> B["Index 2"]
B --> C["Row 2 of the table"]
C --> D["Vector (2.0, 0.0)"]
D --> E["Rest of the network"]
The math
Let there be categories and let the embedding dimension be . An embedding layer is a matrix whose -th row is a vector of learned numbers for category . Its input is a category index or, equivalently, a one-hot vector with entries. Its output is the row .
Step 1 in symbols: the table
The table has rows and columns for the colours:
Row 1 is red, row 2 is green and row 3 is blue. The entries are the learned parameters, so this table has numbers to store.
Step 3 in symbols: the lookup is a product
The one-hot vector for green is . Multiplying a row vector by the table gives
So the lookup and the product give the same vector. A library computes the lookup directly, because multiplying by a one-hot vector wastes work on zeros, but the two are the same map. This is the reason an embedding layer is often described as "one-hot encoding followed by a linear layer with no bias."
Step 5 in symbols: the update
Let be the learning rate and let be the gradient of the loss with respect to the row that was used. Gradient descent changes only that row:
Here , and , so . Every other row has gradient zero for this input, so it stays the same. Gradient descent is covered in Gradient Descent, and the way the gradient reaches the table is described in Backpropagation.
Size of the table
The number of parameters is . For a vocabulary of words and dimensions, the table holds numbers. That is large. A dense layer that takes one-hot input has the same count, but the lookup avoids the multiplication by zeros, so the cost of one lookup does not depend on .
Worked examples
Use the table from "How it works", with rows red , green , blue .
- Input: blue. Its index is 3.
- Read row 3 of : .
- Output: .
- Interpretation: the layer returned the stored vector for blue. Nothing was computed except the copy.
Use the same table to embed the sentence "red blue green red". Each word is one token.
- Indices: red is 1, blue is 3, green is 2, red is 1. The sequence is .
- Look up each index: row 1 is , row 3 is , row 2 is , row 1 is .
- Stack the four rows into a matrix. This is the input the next layer receives.
- Take the average of the four vectors. The first coordinates add to , and the second coordinates add to .
- Divide each sum by 4: the average is .
- Interpretation: the sentence is now one vector. The repeated word "red" contributes the same row both times, and the average is a fixed-size summary of the sentence.
This example is made up to show the mechanism. Suppose a streaming service has learned two-number embeddings. A user has the row . Three titles have rows: an action film , a romance , and a documentary .
- The score for a title is the dot product of the user's row and the title's row.
- Action: .
- Romance: .
- Documentary: .
- The ranking is action (2.0), then romance (1.0), then documentary (-1.5).
- Interpretation: the user's row points most in the direction of the action row, so the model recommends the action film first. In a real system the rows would have dozens or hundreds of learned numbers, and training would set them, not a person.
Try it: a vocabulary has four words with rows , , , . Look up words 4 and 2, and add the two vectors. Answer: .
Common mistakes and tradeoffs
It is tempting to think an embedding is a fixed code, like one-hot encoding with fewer digits. In fact the rows are learned from the task, because they are updated by gradient descent along with every other weight. Two words that the task never separates will drift toward similar rows, and that is the point.
It is tempting to think the rows are readable, so that one coordinate means "royalty" or "colour". In fact, the coordinates of a learned table are usually not individually meaningful. What carries meaning is the geometry: which rows are close, for example by cosine similarity, and which directions separate them.
It is tempting to think a bigger embedding dimension is always better. In fact, sets the parameter count and the memory cost, and too small a cannot separate many categories. Larger tables also need more training data, because each row sees only the examples that use its category. The right size depends on how many categories there are and how much data the model sees.
It is tempting to think the embedding layer is a separate step that can be ignored after training. In fact, it is the part of the model that turns raw categories into numbers, so changing the category list means the table must change too. A new word that is not in the table has no row.
Use an embedding layer when the input is a category with many values, and when similar categories should share structure. Do not use one when there are only a handful of categories and a one-hot column is simpler to read. Alternatives include fixed encodings such as One-Hot Encoding, and pretrained vectors from a separate training run, which can be frozen or fine-tuned as in Word Embedding. Inside a Transformer, the embedding layer's output is what the attention layers, such as Multi-Head Attention, first read.
History
Early neural language models in the early 2000s already learned a vector for each word as part of training. Yoshua Bengio and colleagues described this in 2003, with a network that predicted the next word and learned the word vectors as a side effect. Training was slow, because the models were large and the datasets were small by today's standards.
The idea became widely used around 2013. Tomas Mikolov and colleagues published fast methods for learning word vectors from large text collections, and the work showed that the learned vectors captured useful relations between words. Neural network toolkits then made this table a standard building block that any model can include.
Recap
- A category index selects one row from a learned table of rows and columns.
- The lookup is the same as multiplying the one-hot vector by the table, but it is computed as a copy.
- The table is trained by gradient descent, so only the rows that were used receive an update.
- The output vector feeds the next layer, and it is the input of most language models and many recommenders.
Read next: Word Embedding for embeddings of words learned from text, Language Model for the model that uses them first, and Recommender System for the other main use. The table is also the input stage of a Feedforward Neural Network.
Check yourself
QuestionAn embedding table has categories and dimensions. How many learned numbers does it hold?Show answer
It holds numbers. Each of the 10 rows has 4 entries, so the count is 40.
QuestionThe table row for category 3 is and the table has five rows. What vector does the lookup return for category 3, and what does a one-hot multiplication return?Show answer
Both return . The lookup copies row 3. The product with the one-hot vector picks out the third row, because every other term is multiplied by zero, so the result is the same row.
QuestionA row is , the gradient for that row is , and the learning rate is . What is the updated row?Show answer
The update is . Only the row that was used changes.
QuestionWhy might a model that uses a learned embedding layer treat two rare words more sensibly than a one-hot column would?Show answer
A one-hot column treats every pair of different categories as equally far apart. A learned table moves rows during training, so two words that appear in similar contexts can end up with similar rows, even if one of them is rare, because the gradient from the common neighbours pushes both toward a shared region. The model can therefore generalise from the frequent word to the rare one, which a one-hot encoding cannot do.
QuestionA product team has a column with 2,000 product categories and wants an embedding of width 16. How many parameters does the table have, and is the lookup cost affected by the 2,000?Show answer
The table has parameters. The lookup for one input copies one row, so its cost does not grow with the 2,000 categories, although the table still has to be stored in memory.