Neural-net foundations11 / 15

Lesson 11 · The primitives toolbox

Embeddings and autoencoders

The problem

The pizza shop sells 8 toppings: pepperoni, sausage, ham, pineapple, mushroom, onion, olive and pepper. A network that reads orders needs each topping as numbers. The usual first step is one-hot encoding: 8 numbers, all 0 except a 1 in the topping's own position.

One-hot vectors keep the toppings apart, but they say nothing else. Every pair of one-hot vectors is the same distance apart, so pepperoni is as far from sausage as from pineapple. A network has to learn every fact about every topping separately.

This lesson has two ideas. The first gives each topping a short vector that the network learns, so similar toppings get similar vectors. The second squeezes a whole input through a few numbers and back, to find a compact code for it without any labels.

Embeddings: a learned vector for each category

Give each topping 2 numbers instead of 8, and let training choose them. The 8 × 2 table of numbers, one row per topping, is an embedding. Its rows start random. Gradient descent moves them, like any other weights.

What should the vectors learn? Here, which toppings get ordered together.

The shop has 500 orders. Pepperoni is on 224 of them and sausage on 113. If people picked toppings at random, both would be on about 500×224500×113500≈51500 \times \frac{224}{500} \times \frac{113}{500} \approx 51 orders.

In fact, they share 90. So pepperoni and sausage count as "ordered together". Of the 28 pairs of toppings, 10 are ordered together more often than chance.

The model scores a pair by how close the two toppings' vectors are:

logit(i,j)=b−∥ei−ej∥2\text{logit}(i, j) = b - \lVert \mathbf{e}_i - \mathbf{e}_j \rVert^2

In words: ei\mathbf{e}_i is topping ii's row of the table, and bb is a learned number. Close vectors give a high logit, so "ordered together". Far vectors give a low one. The loss is binary cross-entropy on the 28 pairs, the loss of logistic regression.

Predict first

Nobody tells the model which toppings are meats and which are vegetables. After training, where do the four vegetables (mushroom, onion, olive, pepper) end up?

Step 0 · 18 of 28 pairs right

−3−2−10123−3−2−10123pepperonisausagehampineapplemushroomonionolivepepper

Loss 1.909. The model calls 18 of the 28 pairs correctly.

Faint lines join the 10 pairs ordered together more often than chance.

Each dot is one topping's 2-D vector. They start random; training pulls pairs that are ordered together (joined by faint lines) close, and pushes other pairs apart. AdamW, learning rate 0.01, all 28 pairs in each step.

Things to notice:

  • At step 0, the dots are scattered at random, and the model gets about two thirds of the pairs right by luck.
  • By step 200, the vegetables have gathered in one spot and the meats in another, and the model gets 27 of the 28 pairs right. Pineapple sits next to ham.
  • By the end, every pair ordered together is closer than every pair that isn't. Pepperoni and sausage almost sit on top of each other.

The model found these groups because it had only 2 numbers per topping. To score all 28 pairs well with so few numbers, toppings that behave alike must share a vector. With real data, embeddings have tens or hundreds of numbers each, and they capture much more than two groups.

An embedding is a lookup

How does a network use the table? Multiply a topping's one-hot vector by the table, with the matrix product. Every row is multiplied by 0 except the topping's own row, which is multiplied by 1. So the product is that row.

One-hot vector for “mushroom”

0
0
0
0
1
0
0
0
row1st2nd× one-hot
pepperoni−1.51.3× 0
sausage−1.51.3× 0
ham−2.10.4× 0
pineapple−2.9−0.6× 0
mushroom0.6−0.6× 1
onion0.8−0.5× 0
olive0.8−0.6× 0
pepper0.8−0.6× 0

= (0.6, −0.6), the “mushroom” row

Every row is multiplied by 0 except one, so the product is that row. An embedding layer skips the multiplication and reads the row.

A one-hot vector times the embedding table. Pick a topping: the product is its row of the table. The numbers are the trained vectors from the figure above, rounded.

So an embedding layer is a linear layer with no bias, fed one-hot inputs. Since the answer is always one row, the layer skips the multiplication and reads the row directly. That's much faster when there are 50,000 words instead of 8 toppings.

Once you have the vectors, you can compare them with cosine similarity or distance, add them up, or feed them to any network. Words get the same treatment. The word vectors in the last lesson were picked by hand; in a real language model, each word's vector is an embedding, learned this way.

DigressionRecommendations with embeddingsOne vector per customer, one per pizza, and a dot product to score them. · 2 min

Embeddings are the basis of many recommender systems, the models that suggest what to watch or buy.

Give every customer a vector and every pizza a vector, both learned. Score a customer–pizza pair with the dot product of their vectors. Train the vectors so that pizzas a customer ordered score high and the others score low.

After training, customers with similar tastes have similar vectors, and so do pizzas that the same people like. To recommend, take a customer's vector and find the pizzas with the highest scores. A new customer with few orders still gets sensible suggestions, because their vector lands near customers like them.

This is the same idea as the topping figure, with two tables instead of one. Recommender systems may get a lesson of their own later in the book.

Autoencoders: squeeze and rebuild

Now a different job. Each of the shop's 150 customers has a taste profile of 6 numbers. Each number is the share of their orders in one topping group: meat, veg, cheese, spicy, fruit or fish. Can 2 numbers describe a customer well enough to rebuild all 6?

PCA answers this with a straight-line method: it finds the flat 2-D plane that stays closest to the data. A network can do the same job, and it can also bend.

Build a network in two halves:

  • The encoder takes the 6 numbers and outputs 2.
  • The decoder takes those 2 numbers and outputs 6.

Train the whole thing to output its own input, with mean squared error between the output and the input. This network is an autoencoder.

Copying the input would be easy if the network were wide all the way through. The trick is the narrow middle. The 2-number layer is a bottleneck: everything the decoder knows about a customer must pass through those 2 numbers. To rebuild 6 numbers from 2, the encoder has to keep what matters most and drop the rest.

There are no labels anywhere. The input is its own target, so this is unsupervised learning, and the 2 numbers are a form of dimensionality reduction.

Predict first

An autoencoder has only linear layers (no activation functions) and uses squared-error loss. It squeezes 2-D points down to 1 number and back. What does it learn?

Step 0 · of 2000

PCA's 2 numbers

−0.6−0.4−0.200.20.40.6−0.4−0.200.20.4code 1code 2

Autoencoder's code (linear)

−0.100.10.20.3−0.3−0.2−0.100.1code 1code 2
meat loverveggieadventurous

Share of the spread lost when rebuilding 6 numbers from 2

PCA12.1%
Autoencoder>100%
Left: each customer's two PCA coordinates. Right: the autoencoder's 2-number code, as it trains. Marker shape and colour show the customer's type, which the model never sees. The bars show how much of the data's spread is lost by rebuilding 6 numbers from 2. Plain Adam (no weight decay), learning rate 0.01, all 150 customers in each step.

Things to notice:

  • Linear layers. The error falls to PCA's 12.1% and stops there. The code picture is PCA's picture turned, stretched or flipped: the same plane, described with different axes.
  • ReLU layers. With 8 ReLU units on each side, the error goes below PCA's, to about 9% after 2,000 steps. A bent surface can follow the data more closely than a flat plane.
  • The three types of customer (meat lovers, veggies and adventurous eaters) form three groups in both pictures. The model was never told the types. It found them because they're the biggest pattern in the data.

The space of codes is the latent space ("latent" means hidden). Points close together in it are customers with similar tastes. You can use the codes as features for another model, plot them to explore the data, or flag customers whose profile rebuilds badly as unusual.

The gain here is small, because this data sits almost flat already. On images or sound, where the data lies on a strongly curved surface, nonlinear autoencoders beat PCA by much more.

DigressionFrom autoencoders to generating new pizzas: VAEsDecode a random point of the latent space, and you get a brand-new input. · 2 min

The decoder turns any 2 numbers into a taste profile. So pick a new point in the latent space and decode it. Do you get a believable new customer?

With a plain autoencoder, often not. Training only shapes the latent space near the codes of real customers. The gaps between them can decode to nonsense.

A variational autoencoder (VAE), introduced by Kingma and Welling in 2013, fixes this. Its encoder outputs a small cloud of possible codes for each input instead of one point. Its loss also pushes the clouds to fill a simple shape around 0, with no gaps. Then any point you pick decodes to something sensible, and the decoder becomes a generator of new data.

That's covered in VAEs, in the Autoencoders course.

In PyTorch

nn.Embedding holds the table. You give it integer ids, not one-hot vectors, and it returns one row per id.

nn.Embedding is a lookup
def lookup_demo() -> dict[str, torch.Tensor]:
    """nn.Embedding is a lookup table: integer ids in, one row of the weight matrix out per id."""
    torch.manual_seed(0)
    emb = nn.Embedding(num_embeddings=8, embedding_dim=2)  # weight: (8, 2), random N(0, 1) to start
    ids = torch.tensor([4, 0, 4])  # mushroom, pepperoni, mushroom: shape (3,)
    vectors = emb(ids)  # (3, 2): rows 4, 0 and 4 of emb.weight
    one_hot = F.one_hot(ids, num_classes=8).float()  # (3, 8)
    return {"lookup": vectors, "one_hot_times_matrix": one_hot @ emb.weight, "weight": emb.weight}

Read the shapes:

  • nn.Embedding(num_embeddings=8, embedding_dim=2) has a weight of shape (8, 2): one row per topping. It starts as random numbers from a standard normal.
  • ids has shape (3,) and holds integers. The output has shape (3, 2): one vector per id.
  • Any shape of ids works. A batch of sentences with shape (32, 20) gives (32, 20, d).
  • one_hot @ emb.weight gives exactly the same numbers. The test file checks it.

The topping model is a small nn.Module with an embedding and one extra learned number:

Score a pair by how close its vectors are
class PairModel(nn.Module):
    """One 2-D vector per topping. A pair's logit is b − (squared distance between their vectors)."""

    def __init__(self, n_toppings: int = 8, dim: int = 2) -> None:
        super().__init__()
        self.emb = nn.Embedding(n_toppings, dim)
        self.bias = nn.Parameter(torch.zeros(1))

    def forward(self, pairs: torch.Tensor) -> torch.Tensor:  # pairs: (n, 2) integer ids
        e = self.emb(pairs)  # (n, 2, dim): both toppings' vectors
        dist2 = ((e[:, 0] - e[:, 1]) ** 2).sum(dim=-1)  # (n,)
        return self.bias - dist2  # (n,) logits: close → "ordered together"

self.emb(pairs) looks up both toppings of every pair at once: ids of shape (28, 2) give vectors of shape (28, 2, 2). Training uses AdamW and F.binary_cross_entropy_with_logits on all 28 pairs at each step.

The autoencoder is two smaller networks, kept as two attributes so you can call model.encoder alone to get the codes:

An autoencoder: encoder and decoder
class Autoencoder(nn.Module):
    """encoder: 6 → 2 numbers (the code); decoder: 2 → 6 (the reconstruction)."""

    def __init__(self, n_in: int = 6, code: int = 2, hidden: int | None = 8) -> None:
        super().__init__()
        if hidden is None:  # linear: no hidden layers, no activation
            self.encoder = nn.Linear(n_in, code)
            self.decoder = nn.Linear(code, n_in)
        else:
            self.encoder = nn.Sequential(nn.Linear(n_in, hidden), nn.ReLU(), nn.Linear(hidden, code))
            self.decoder = nn.Sequential(nn.Linear(code, hidden), nn.ReLU(), nn.Linear(hidden, n_in))

    def forward(self, x: torch.Tensor) -> torch.Tensor:  # x: (batch, 6)
        return self.decoder(self.encoder(x))  # (batch, 6), trained to equal x

It trains with the same five steps as the Lesson 4 template. Three things change: the target is the input itself, the loss is F.mse_loss, and the optimiser is plain Adam. Adam has no weight decay, so the comparison with PCA stays exact. There's no accuracy to report.

Train it to rebuild its input
def train_autoencoder(hidden: int | None = 8, epochs: int = 2000, lr: float = 0.01, seed: int = 0) -> tuple[Autoencoder, list[float]]:
    """The Lesson 4 loop with three changes: the target is the input itself, the loss is F.mse_loss,
    and the optimiser is plain Adam (no weight decay, so the linear case matches PCA exactly)."""
    seed_everything(seed)
    device = get_device()
    x = taste_profiles()
    loader = DataLoader(TensorDataset(x), batch_size=len(x))  # all 150 customers in one batch
    model = Autoencoder(hidden=hidden).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    losses = []
    for _ in range(epochs):
        model.train()
        for (batch,) in loader:
            batch = batch.to(device)
            optimizer.zero_grad()
            loss = F.mse_loss(model(batch), batch)  # how far the copy is from the input
            loss.backward()
            optimizer.step()
        losses.append(loss.item())
    return model, losses

Running the file prints the error as a share of the data's spread. PCA loses 12.1%, the linear autoencoder 12.1%, and the ReLU autoencoder 7.9%. (The PyTorch run starts from different random weights than the figure, so its ReLU number differs a little.)

Common misconceptions

"An embedding is a fixed code, like one-hot." One-hot is fixed. An embedding's numbers are weights, learned from the task, so similar categories end up close.

"The embedding layer multiplies by a one-hot vector." It gives the same answer as that product, but it reads the row directly. That's why it takes integer ids.

"An autoencoder is useful because its output copies the input." The copy is only the training task. The useful part is the code in the bottleneck, which has to be small.

"A deeper autoencoder always beats PCA." Only if it has nonlinear activations. With linear layers, it finds the same plane as PCA, no matter how many layers it has.

"Nearby points in the latent space are always meaningful." Only near the codes of real inputs. Plain autoencoders can leave gaps that decode to nonsense. VAEs are built to close them.

Recap

  • An embedding gives each category a learned vector, stored as one row of a table. Categories that behave alike get similar vectors.
  • Looking up a row equals multiplying a one-hot vector by the table, so an embedding layer is a linear layer that skips the multiplication.
  • An autoencoder squeezes its input through a narrow bottleneck and rebuilds it. The code in the bottleneck is a compact description, learned without labels.
  • With linear layers and squared error, an autoencoder finds PCA's plane. Nonlinear layers let it rebuild the data better.
  • The space of codes is the latent space: nearby codes mean similar inputs.
  • PyTorch names used: nn.Embedding, F.one_hot, F.binary_cross_entropy_with_logits, F.mse_loss, torch.linalg.svd.
  • The Autoencoders course goes deeper into autoencoders and VAEs; the Language and sequences course learns word embeddings.