Embedding Layers
A word, a user id, a product code, a postcode: many inputs are symbols from a large set with no natural numeric value. One-hot encoding turns symbol of into a vector of zeros with a 1 at position , which is correct but wasteful: with 50,000 words every input is a 50,000-dimensional vector that is almost all zeros, and the first layer's weight matrix has 50,000 rows. An embedding layer stores one learned vector of numbers per symbol, typically between 2 and a few thousand (over 10,000 in the largest language models), and looks it up by index. Training moves the vectors so that symbols that behave alike end up close together. Embedding layers are the input of every language model (Building a Transformer Block), the core of recommenders, and the best way to feed high-cardinality categorical columns into a tabular MLP.
The algebra (a lookup is a matrix product, cosine similarity, how embeddings are learned in word2vec and in transformers) is in Embeddings, and embeddings as a feature-engineering tool in Learned Embeddings. This lesson is about the layer: what nn.Embedding computes forward and backward, padding and bags, a small embedding learned from an original toy corpus, and entity embeddings for a categorical column.
A lookup is a matrix product
The layer holds a table , one row per symbol. For symbol with one-hot vector ,
so an embedding layer is exactly a linear layer without bias applied to one-hot inputs, implemented as an index instead of a multiplication. The backward pass follows from the same identity: for a batch of indices with one-hot matrix and upstream gradient ,
Row of the gradient is the sum of the upstream gradients of all positions that looked up symbol , and every row that was not used has a zero gradient. A batch of 64 sentences touches a few hundred of 50,000 rows; the framework scatter-adds into those rows instead of forming .
The mechanics in NumPy
import numpy as np
rng = np.random.default_rng(0)
k, d = 6, 3 # 6 categories (vocabulary), 3-dimensional vectors
E = rng.normal(0, 1, (k, d)).round(2) # the embedding table: one row per category
ids = np.array([4, 1, 4, 0]) # a batch of 4 category ids (4 appears twice)
lookup = E[ids] # what nn.Embedding does
one_hot = np.eye(k)[ids] # (4, 6)
print("lookup == one_hot @ E:", np.allclose(lookup, one_hot @ E))
print("rows looked up:\n", lookup)
# backward: dL/dE = one_hot.T @ dL/dlookup, i.e. scatter-add the incoming gradients into the used rows
g = np.ones((4, d)) * np.array([[1.0], [2.0], [3.0], [4.0]]) # pretend gradient for each looked-up row
dE = one_hot.T @ g
dE_scatter = np.zeros_like(E)
np.add.at(dE_scatter, ids, g) # the cheap way: no one-hot matrix
print("dE rows:", dE[:, 0].tolist(), " same as scatter-add:", np.allclose(dE, dE_scatter))
print("rows with a nonzero gradient:", np.flatnonzero(np.abs(dE).sum(1)).tolist())
# EmbeddingBag(mode="mean"): one vector per variable-length bag, e.g. the tags of a product
bags = [[0, 2], [5], [1, 3, 4]]
print("bag means:", [np.round(E[b].mean(0), 3).tolist() for b in bags])
# padding: row 0 reserved for padding stays zero and gets no gradient
E_pad = E.copy(); E_pad[0] = 0
seqs = np.array([[3, 5, 0, 0], [2, 1, 4, 0]]) # two sequences padded with id 0
mask = seqs != 0
mean_vec = (E_pad[seqs] * mask[..., None]).sum(1) / mask.sum(1, keepdims=True)
print("masked mean of padded sequences:", np.round(mean_vec, 3).tolist())
# parameter count: one-hot input into a hidden layer of H units vs an embedding of size d first
for k_big in (10, 1_000, 100_000):
H, d_emb = 256, 16
print(f"k = {k_big:6d}: one-hot -> Linear(k, {H}) {k_big * H:10,d} weights;"
f" Embedding(k, {d_emb}) -> Linear({d_emb}, {H}) {k_big * d_emb + d_emb * H:9,d}")lookup == one_hot @ E: True
rows looked up:
[[-2.33 -0.22 -1.25]
[ 0.1 -0.54 0.36]
[-2.33 -0.22 -1.25]
[ 0.13 -0.13 0.64]]
dE rows: [4.0, 2.0, 0.0, 0.0, 4.0, 0.0] same as scatter-add: True
rows with a nonzero gradient: [0, 1, 4]
bag means: [[0.715, 0.41, -0.03], [-0.73, -0.54, -0.32], [-1.167, -0.46, -0.283]]
masked mean of padded sequences: [[-1.0, -0.58, -0.14], [-0.31, 0.063, -0.53]]
k = 10: one-hot -> Linear(k, 256) 2,560 weights; Embedding(k, 16) -> Linear(16, 256) 4,256
k = 1000: one-hot -> Linear(k, 256) 256,000 weights; Embedding(k, 16) -> Linear(16, 256) 20,096
k = 100000: one-hot -> Linear(k, 256) 25,600,000 weights; Embedding(k, 16) -> Linear(16, 256) 1,604,096
The lookup equals the one-hot product, and symbol 4, used twice, appears twice. Its gradient row is (positions 0 and 2), row 1 gets 2 and row 0 gets 4 from the last position; rows 2, 3 and 5 get exactly zero. np.add.at is the scatter-add a framework uses; the plain fancy-index assignment dE[ids] += g would be wrong here, because it writes the repeated index 4 only once.
Two variants of the lookup:
- Bags. A product with several tags, a user with several past purchases: the input is a variable-length set of symbols. An EmbeddingBag returns one vector per bag, the mean (or sum, or max) of its rows, without materialising the individual vectors.
- Padding. Batched sequences have different lengths and are padded with a reserved index, here 0. Its row is zero and must not influence results: average with a mask (the masked mean above divides by 2 and 3, the true lengths, not by 4).
The parameter count is the real argument for embeddings. Feeding one-hot columns straight into a hidden layer of 256 units needs weights; an embedding of size 16 first needs . For 10 categories the one-hot version is smaller (2,560 against 4,256), for 1,000 it is 13 times larger, and for 100,000 symbols it is 25.6 million weights against 1.6 million. The embedding also forces all symbols through a shared 16-dimensional space, which is what makes similar symbols share what they learn.
Learning embeddings from co-occurrence
Where does the geometry come from? From the training objective. The classic example is skip-gram (word2vec): predict which words appear near a given word. The corpus here is original and synthetic: 1500 short sentences generated from 9 templates in which 4 animals, 4 fruits, 4 vehicles and 4 places can fill the slots. Words of a group appear in the same contexts, but no group label is given to the model. Each (centre word, context word) pair within a window of 2 is a positive example, scored by the dot product ; 5 random "negative" words per pair are pushed apart (negative sampling). Training is plain SGD in NumPy, and the update touches only the rows used in each batch, as derived above.
import numpy as np
rng = np.random.default_rng(0)
groups = {"animal": ["cat", "dog", "horse", "rabbit"], "fruit": ["apple", "pear", "plum", "cherry"],
"vehicle": ["car", "truck", "bus", "van"], "place": ["garden", "park", "market", "school"]}
templates = [
"the {animal} sleeps near the {place}", "a hungry {animal} chased the {animal}",
"my {animal} likes to run and play", "she sliced a ripe {fruit} for lunch",
"the {fruit} tree grew in the {place}", "fresh {fruit} juice tastes sweet",
"we drove the {vehicle} to the {place}", "the old {vehicle} needs new tyres",
"a red {vehicle} was parked outside",
]
def sentence():
t = templates[rng.integers(len(templates))]
while "{" in t:
g = t[t.index("{") + 1:t.index("}")]
t = t.replace("{" + g + "}", groups[g][rng.integers(4)], 1)
return t.split()
corpus = [sentence() for _ in range(1500)]
vocab = sorted({w for s in corpus for w in s})
idx = {w: i for i, w in enumerate(vocab)}
print("sentences:", len(corpus), " vocabulary:", len(vocab), " example:", " ".join(corpus[0]))
pairs = np.array([(idx[s[i]], idx[s[j]]) for s in corpus for i in range(len(s))
for j in range(max(0, i - 2), min(len(s), i + 3)) if j != i]) # window of 2
counts = np.bincount(pairs[:, 1], minlength=len(vocab)) ** 0.75
noise = counts / counts.sum() # negative samples drawn like word2vec
V, D, K, lr = len(vocab), 12, 5, 0.05
W_in = rng.normal(0, 0.1, (V, D)) # the embeddings we keep
W_out = np.zeros((V, D)) # context vectors
sig = lambda z: 1 / (1 + np.exp(-z))
for epoch in range(3):
pairs = pairs[rng.permutation(len(pairs))]
for s in range(0, len(pairs), 256):
c, o = pairs[s:s + 256, 0], pairs[s:s + 256, 1]
neg = rng.choice(V, size=(len(c), K), p=noise)
v = W_in[c] # (B, D)
g_pos = sig((v * W_out[o]).sum(1)) - 1 # d/dscore of -log sig(v.u_o)
g_neg = sig(np.einsum("bd,bkd->bk", v, W_out[neg])) # d/dscore of -log sig(-v.u_n)
grad_v = g_pos[:, None] * W_out[o] + np.einsum("bk,bkd->bd", g_neg, W_out[neg])
np.add.at(W_out, o, -lr * g_pos[:, None] * v)
np.add.at(W_out, neg, -lr * g_neg[..., None] * v[:, None, :])
np.add.at(W_in, c, -lr * grad_v) # sparse update: only the used rows
E = W_in / np.linalg.norm(W_in, axis=1, keepdims=True)
sim = E @ E.T
for w in ("cat", "apple", "truck", "park"):
near = [vocab[j] for j in np.argsort(-sim[idx[w]]) if j != idx[w]][:3]
print(f"nearest to {w:6s}: {near}")
within, across = [], []
names = list(groups)
for a in names:
for b in names:
block = sim[np.ix_([idx[w] for w in groups[a]], [idx[w] for w in groups[b]])]
if a == b:
within.append(block[~np.eye(4, dtype=bool)].mean())
else:
across.append(block.mean())
print(f"mean cosine similarity: within a group {np.mean(within):.3f}, across groups {np.mean(across):.3f}")sentences: 1500 vocabulary: 50 example: the old bus needs new tyres
nearest to cat : ['horse', 'dog', 'rabbit']
nearest to apple : ['pear', 'cherry', 'plum']
nearest to truck : ['car', 'bus', 'van']
nearest to park : ['school', 'garden', 'market']
mean cosine similarity: within a group 0.954, across groups 0.405
After 3 passes over the pairs the 12-dimensional vectors have organised themselves: the three nearest neighbours of cat are the other three animals, those of apple the other fruits, of truck the vehicles and of park the places. The mean cosine similarity between words of the same group is 0.954, against 0.405 between groups. Nothing in the code knows about groups: words that can replace each other in the same sentences receive similar gradients, so their rows move the same way. Real word embeddings are learned the same way from billions of sentences, and transformer token embeddings are learned end to end by the language-modelling loss.
The layer in PyTorch
nn.Embedding(num_embeddings, embedding_dim, padding_idx=None) holds the table as weight, initialised from . Recorded with PyTorch 2.14.1 on CPU:
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0)
emb = nn.Embedding(num_embeddings=6, embedding_dim=3, padding_idx=0)
print("weight std (init N(0, 1)):", round(emb.weight.std().item(), 3), " padding row:", emb.weight[0].tolist())
ids = torch.tensor([[4, 1, 0], [4, 2, 5]]) # batch of 2 sequences, 0 = padding
out = emb(ids)
print("output shape:", tuple(out.shape),
" equals one_hot @ W:", torch.allclose(out, F.one_hot(ids, 6).float() @ emb.weight))
out.sum().backward()
print("gradient row sums:", emb.weight.grad.sum(1).tolist(), "(row 4 used twice, row 0 is padding)")
bag = nn.EmbeddingBag(6, 3, mode="mean")
with torch.no_grad():
bag.weight.copy_(emb.weight)
flat = torch.tensor([1, 3, 5, 2]) # two bags: [1, 3, 5] and [2]
offsets = torch.tensor([0, 3])
print("EmbeddingBag mean == mean of rows:",
torch.allclose(bag(flat, offsets)[0], emb.weight[[1, 3, 5]].mean(0)))weight std (init N(0, 1)): 0.878 padding row: [0.0, 0.0, 0.0]
output shape: (2, 3, 3) equals one_hot @ W: True
gradient row sums: [0.0, 3.0, 3.0, 0.0, 6.0, 3.0] (row 4 used twice, row 0 is padding)
EmbeddingBag mean == mean of rows: True
The output has shape (batch, sequence, ) and equals one_hot(ids) @ weight. After a backward pass with an upstream gradient of 1 everywhere, each used row has gradient sum per use, row 4 has 6 for its two uses, and the padding row 0 has 0 even though it was looked up: padding_idx initialises that row to zeros and never gives it a gradient. nn.EmbeddingBag takes a flat index tensor plus offsets marking where each bag starts, and its mean equals the mean of the rows.
Details worth knowing:
- The initialisation is large next to other layers. Transformers usually re-initialise with standard deviation about 0.02 or scale the output by (Weight Initialisation in Practice).
sparse=Truemakes the gradient a sparse tensor with only the used rows, which saves memory for huge tables; it needs an optimiser that accepts sparse gradients (torch.optim.SparseAdam, SGD). With a dense optimiser such as Adam, unused rows still get updated by their momentum.- Language models often tie the input embedding and the output projection: the logits are , so the same table both reads and writes tokens (GPT-2 does this), saving parameters.
- Indices must be integers (
torch.longorint) in ; an out-of-range id raises an index error on CPU and a less readable device-side assert on a GPU.
Entity embeddings for a categorical column
In a table, an embedding replaces one-hot encoding of a categorical column with many levels (shop, product, postcode). The synthetic example: 4000 rows with a shop column of 40 shops and a numeric price. The target depends on the price and on a hidden region of each shop (4 regions, 10 shops each, with effects ), plus noise with variance 0.25. The model never sees the region: it gets a 2-dimensional embedding of the shop concatenated with the price, fed to a small MLP, trained with AdamW (weight decay 0.1) on 3000 rows and evaluated on 1000.
import torch
from torch import nn
# A table with a categorical column "shop" (40 shops) and a numeric column "price".
# Hidden truth: every shop belongs to one of 4 regions, and the region shifts the target.
g = torch.Generator().manual_seed(0)
n_shops, n = 40, 4000
region = torch.arange(n_shops) % 4 # never shown to the model
region_effect = torch.tensor([-2.0, -0.5, 0.5, 2.0])
shop = torch.randint(0, n_shops, (n,), generator=g)
price = torch.randn(n, generator=g)
y = region_effect[region[shop]] + 1.5 * price + 0.5 * torch.randn(n, generator=g)
tr, va = slice(0, 3000), slice(3000, None)
class EntityModel(nn.Module):
def __init__(self, dim):
super().__init__()
self.shop = nn.Embedding(n_shops, dim)
self.mlp = nn.Sequential(nn.Linear(dim + 1, 32), nn.ReLU(), nn.Linear(32, 1))
def forward(self, shop, price):
return self.mlp(torch.cat([self.shop(shop), price[:, None]], dim=1)).squeeze(1)
torch.manual_seed(0)
model = EntityModel(dim=2)
opt = torch.optim.AdamW(model.parameters(), lr=0.01, weight_decay=0.1)
for epoch in range(30):
for idx in torch.randperm(3000, generator=g).split(100):
loss = nn.functional.mse_loss(model(shop[tr][idx], price[tr][idx]), y[tr][idx])
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
val_mse = nn.functional.mse_loss(model(shop[va], price[va]), y[va]).item()
print(f"validation MSE {val_mse:.3f} (noise variance 0.25 is the floor)")
print("parameters: embedding", model.shop.weight.numel(), " MLP", sum(p.numel() for p in model.mlp.parameters()))
E = model.shop.weight.detach() # the learned shop vectors, (40, 2)
dist = torch.cdist(E, E) + torch.eye(n_shops) * 1e9 # exclude each shop itself
nearest = dist.topk(3, largest=False).indices # 3 nearest shops in embedding space
share = (region[nearest] == region[:, None]).float().mean().item()
print(f"share of each shop's 3 nearest shops that are in its region: {share:.3f} (chance {9 / 39:.3f})")validation MSE 0.265 (noise variance 0.25 is the floor)
parameters: embedding 80 MLP 161
share of each shop's 3 nearest shops that are in its region: 0.825 (chance 0.231)
The validation MSE, 0.265, is close to the noise floor of 0.25, so the model has learned what matters about each shop with only 80 embedding parameters. The embedding space shows how: for each shop, 82.5 % of its 3 nearest shops (by distance between the learned vectors) are in the same hidden region, against 23.1 % by chance. Shops that affect the target the same way got similar vectors, and a new model could reuse them, for example to cluster shops or as features for a gradient-boosted model. The weight decay matters: without it the unused directions of the space keep their random initial spread and the neighbourhoods are less clean.
Choosing the dimension: a few for a column with tens of levels, tens to hundreds for thousands of levels; a heuristic such as is a starting point to tune on validation data. Reserve an extra index for unseen or rare categories (all levels with fewer than a handful of rows mapped to one "other" row), so the model can handle new values at prediction time.
Pitfalls
- Forgetting the unknown index. A category that first appears in production has no row; map it to a reserved "unknown" index trained on rare levels.
- Padding without a mask.
padding_idxkeeps the padding row at zero, but a plain mean over the sequence still divides by the padded length; use a mask orEmbeddingBag. - Dense optimiser state for huge tables. Adam keeps two extra numbers per parameter; for a 10-million-row table that triples the memory. Use sparse gradients with
SparseAdam, or a smaller table (hashing, see binary, frequency and hashing encodings). - Reading meaning into raw coordinates. The axes of an embedding have no fixed meaning; only relative positions (distances, cosine similarity) do, and only for directions the loss cared about.
- Leakage through ids. A user id embedding can memorise the label of every training user; validate on users not seen in training if the model must generalise to new ones.
Practice
- A vocabulary of 32,000 tokens with , input and output embeddings tied. How many parameters do the embeddings cost, and how many would untied ones cost?
Answer
Tied: , about 16.4 million. Untied: twice that, about 32.8 million (plus the output bias if there is one).
- Why does
dE[ids] += ggive the wrong gradient in NumPy whenidscontains repeats, and what is the fix?
Answer
Fancy-index assignment evaluates dE[ids] + g and then writes each result to its index; for a repeated index the later write overwrites the earlier one, so only one contribution survives. np.add.at(dE, ids, g) accumulates all of them (PyTorch's index_add_ does the same).
- Write a PyTorch model for a table with a categorical column of 1000 levels and 5 numeric columns, using an 8-dimensional entity embedding.
Answer
class TabularNet(nn.Module):
def __init__(self, n_levels=1000, dim=8, n_num=5):
super().__init__()
self.cat = nn.Embedding(n_levels + 1, dim) # +1: index n_levels = unknown
self.mlp = nn.Sequential(nn.Linear(dim + n_num, 64), nn.ReLU(), nn.Linear(64, 1))
def forward(self, cat_ids, x_num): # x_num already standardised
return self.mlp(torch.cat([self.cat(cat_ids), x_num], dim=1))Test yourself
What does nn.Embedding(k, d)(i) compute?
- A hash of
- Row of a learned table, equal to the one-hot vector of times the table
- A random vector every call
- The one-hot vector of
Which rows of the embedding table receive a nonzero gradient in a training step?
- All rows
- Only the rows of symbols that appeared in the batch (and not the padding row)
- Only row 0
- Only the most frequent symbols
For a categorical column with 100,000 levels feeding a hidden layer of 256 units, how do the weights compare between one-hot and a 16-dimensional embedding?
- Equal
- 25.6 million against about 1.6 million
- 1.6 million against 25.6 million
- The embedding needs more
In the skip-gram example, why do cat and dog end up with similar vectors?
- Their spellings are similar
- They appear in the same contexts, so their rows receive similar gradients
- The code assigns them to the same group
- They are the most frequent words
What does padding_idx=0 do in nn.Embedding?
- Removes index 0 from the vocabulary
- Initialises row 0 to zeros and never updates it
- Pads every sequence to the same length
- Masks the attention