Autoencoders, embeddings and representation learning
Encoders compress, decoders reconstruct; meaning lives in between
"Encoder", "decoder", "latent", "embedding" — these four words run through the rest of the path: seq2seq models (6.6 Seq2seq, encoder–decoder and beam search), the transformer's two stacks (7.1 Attention Is All You Need: the big picture), BERT and GPT as encoder-only and decoder-only (7.5 Encoder-only: BERT and friends (and sentence embeddings), 7.6 Decoder-only: GPT and autoregressive generation), VAEs and the latent space of Stable Diffusion (8.8 Generative models I: VAEs and GANs, 8.9 Generative models II: Diffusion and flow matching), and the embedding vectors that power every retrieval system (9.2 Embeddings deep dive). The autoencoder is the simplest model that contains all of them, and it is the cleanest place to learn what a representation is and why cosine similarity on learned vectors works.
You'll be able to
- Define encoder, decoder, bottleneck and latent space and write the autoencoder objective
- Explain why a linear autoencoder recovers the PCA subspace and what nonlinearity adds
- Describe denoising, sparse and masked autoencoders and the manifold hypothesis
- Explain nn.Embedding as a learned lookup table and why similarity in embedding space is meaningful
- Use the words encoder and decoder correctly across autoencoders, seq2seq and transformers
Key ideas
- An autoencoder minimizes ‖x − g(f(x))‖² through a bottleneck k < d; the code z is a learned representation obtained without labels.
- A linear autoencoder with squared loss learns the top-k principal subspace (PCA); nonlinear encoders/decoders learn curved manifolds.
- The manifold hypothesis: real data lies near a low-dimensional manifold; latent coordinates parameterize it, which is why interpolation and generation work.
Show 4 more key ideas
- Denoising autoencoders estimate the direction back to the data manifold (the score) — the core of diffusion models; masked autoencoders (MAE, BERT) are denoising over patches/tokens.
- nn.Embedding is a V×d lookup table trained by backprop; one-hot × matrix = row selection.
- Embedding similarity is meaningful because training objectives score with dot products, pushing similarly-used items together; the geometry is task-dependent.
- Encoders map inputs to representations, decoders produce outputs from them; the exact meaning differs across autoencoders, seq2seq, transformers and VAEs.
Suggested path through this lesson
Encoder, bottleneck, decoder
An autoencoder learns to copy its input through a constriction. An encoder maps the input to a latent code , and a decoder maps the code back to a reconstruction . Training minimizes the reconstruction error,
or a binary cross-entropy per pixel when inputs are in (4.3 Loss functions catalog). If the model could learn the identity and nothing interesting would happen; the undercomplete case forces the code to keep only what matters for reconstruction. Everything the network cannot afford to store — noise, redundancy, pixel-level detail predictable from context — is discarded. The code is therefore a representation: a compressed description in coordinates the model chose itself. No labels were needed, which makes autoencoders the prototype of self-supervised learning (5.8 Self-supervised and contrastive learning).
Linear autoencoders are PCA
Make both maps linear, , , with squared loss. The optimal reconstruction is the projection onto the subspace spanned by the top- principal components of the data (3.12 Dimensionality reduction: PCA, t-SNE and UMAP) — the Eckart–Young theorem of 1.3 Eigen-things, SVD and low rank in disguise. (Gradient descent recovers the subspace, not necessarily the individual ordered components, because any invertible change of basis inside the subspace gives the same loss.) So an autoencoder with a nonlinear encoder and decoder is nonlinear PCA: it can bend the subspace into a curved surface, which is what real data needs.
Worked example. An MNIST autoencoder has parameters and compresses each image . With linear layers its reconstruction error matches PCA with 32 components; with a ReLU hidden layer of 128 units on each side it reconstructs noticeably sharper digits at the same code size — the manifold of handwritten digits is curved.
The manifold hypothesis
Random pixel arrays never look like digits; real digits occupy a thin, curved sheet inside whose intrinsic dimension is perhaps a few dozen (stroke thickness, slant, loop size…). The manifold hypothesis says natural data concentrates near such low-dimensional manifolds, and the latent space is a coordinate chart for it: moving along moves along the manifold, so interpolating between two codes produces plausible intermediates rather than a pixel blend. This picture explains why generative models work at all (8.8 Generative models I: VAEs and GANs, 8.9 Generative models II: Diffusion and flow matching) and why adversarial examples exist (small steps off the manifold, 5.9 Interpretability, robustness and adversarial examples).
Variants that learn better representations
- Denoising autoencoders corrupt the input, or with random masking, and train . The model must learn the structure of the data to undo corruption, so the code cannot be a trivial copy even without a bottleneck. The optimal denoiser points from the corrupted input back toward the data manifold — it estimates the score , which is exactly what a diffusion model learns at every noise level (8.9 Generative models II: Diffusion and flow matching).
- Sparse autoencoders add an penalty on the code (or a KL penalty toward a target activation rate) so that only a few latent units fire for any input. Over-complete sparse codes () are the tool interpretability researchers use to pull human-readable features out of LLM activations (8.11 Interpretability: what is happening inside).
- Masked autoencoders hide a large fraction of input patches or tokens and reconstruct them: MAE masks 75% of image patches (5.8 Self-supervised and contrastive learning), and BERT's masked language modeling is a denoising autoencoder over text (7.5 Encoder-only: BERT and friends (and sentence embeddings)).
- Variational autoencoders replace the point code with a distribution and add a KL term pulling it toward a prior, which turns the autoencoder into a generative model with a smooth, sample-able latent space (8.8 Generative models I: VAEs and GANs).
- Contractive autoencoders penalize the encoder's Jacobian so small input changes give small code changes — robustness by construction.
Embeddings: a learned lookup table
Discrete objects — words, tokens, users, products — have no natural coordinates. An embedding layer gives them some: nn.Embedding(V, d) is a matrix , and the embedding of item is its row . Equivalently, it is a linear layer applied to a one-hot vector, , implemented as a lookup because multiplying by one-hots would be wasteful (1.2 Matrices as transformations). The rows are ordinary parameters trained by backprop through whatever task sits on top: next-token prediction (6.3 Word embeddings, 7.6 Decoder-only: GPT and autoregressive generation), click prediction, or a contrastive objective (4.3 Loss functions catalog).
Why does geometry in this space mean anything? Because every objective that uses embeddings scores them with dot products (1.1 Vectors, dot products and norms): a word's embedding is pushed toward the contexts it appears in (word2vec), a query embedding toward its relevant documents (retrieval), an image embedding toward its caption (CLIP). Items that are used similarly are pushed to similar places, so cosine similarity between embeddings measures functional similarity under the training task — not some innate semantics. Change the task and the geometry changes; that is why a retrieval model's embeddings outperform a language model's hidden states for search (9.2 Embeddings deep dive). Embeddings are the universal interface of modern ML: everything is turned into a vector, and vectors are compared.
Representation learning as a goal
A good representation makes the downstream task easy — ideally linear. The standard measurement is a linear probe: freeze the encoder, train logistic regression on its features, and read the accuracy (5.8 Self-supervised and contrastive learning). Transfer learning (5.4 Transfer learning and training CNNs in practice) reuses representations learned on a big dataset for a small one; pretraining (7.6 Decoder-only: GPT and autoregressive generation, 8.1 The LLM lifecycle and model landscape) is representation learning at the scale of the internet, and fine-tuning adjusts the representation for a task (8.2 Fine-tuning and PEFT). The hidden layers of every network in this phase were already learning representations; autoencoders just make the idea explicit by giving the representation a name and a dimension.
The vocabulary you will carry forward
| model | encoder | latent / representation | decoder |
|---|---|---|---|
| autoencoder | input → code | a fixed-size vector | code → reconstruction |
| seq2seq (6.6 Seq2seq, encoder–decoder and beam search) | source sentence → states | the final state (or all states) | generates target tokens one at a time |
| transformer (7.1 Attention Is All You Need: the big picture) | the encoder stack: tokens → contextual vectors | one vector per token | the decoder stack: generates tokens, attending to the encoder output |
| BERT (7.5 Encoder-only: BERT and friends (and sentence embeddings)) | encoder only | contextual token vectors, pooled for sentences | none (a task head instead) |
| GPT (7.6 Decoder-only: GPT and autoregressive generation) | — | the residual stream | decoder only: autoregressive generation |
| VAE / latent diffusion (8.8 Generative models I: VAEs and GANs, 8.9 Generative models II: Diffusion and flow matching) | image → latent distribution | a compressed spatial latent | latent → image |
The same two words mean slightly different things in each row — an encoder always maps inputs to representations, a decoder always produces outputs from representations, but whether the decoder reconstructs, translates or generates depends on the model. When someone says "encoder-only" or "decoder-only" in 7.7 Encoder–decoder: T5, BART and choosing an architecture, this table is what they mean.
In code
class AE(nn.Module):
def __init__(self, d=784, h=128, k=32):
super().__init__()
self.enc = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, k))
self.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))
def forward(self, x):
z = self.enc(x)
return self.dec(z), z
x_hat, z = ae(x.view(x.size(0), -1))
loss = torch.nn.functional.mse_loss(x_hat, x.view(x.size(0), -1))
Where this shows up later
- PCA as the linear special case — 3.12 Dimensionality reduction: PCA, t-SNE and UMAP; InfoNCE and contrastive representation learning — 4.3 Loss functions catalog, 5.8 Self-supervised and contrastive learning; linear probes and transfer — 5.4 Transfer learning and training CNNs in practice.
- Word embeddings trained by prediction — 6.3 Word embeddings; the encoder–decoder split in seq2seq and transformers — 6.6 Seq2seq, encoder–decoder and beam search, 7.1 Attention Is All You Need: the big picture, 7.7 Encoder–decoder: T5, BART and choosing an architecture; BERT as a masked (denoising) autoencoder — 7.5 Encoder-only: BERT and friends (and sentence embeddings).
- VAEs, latent diffusion's VAE compressor and the denoiser-as-score connection — 8.8 Generative models I: VAEs and GANs, 8.9 Generative models II: Diffusion and flow matching; sparse autoencoders for interpretability — 8.11 Interpretability: what is happening inside; embedding models and vector search — 9.2 Embeddings deep dive, 9.3 Vector search and indexes.
Common pitfalls (4)
- Expecting a plain autoencoder's latent space to be smooth and sample-able — it is not; that is what the VAE's KL term buys.
- Using an over-complete autoencoder with no noise or sparsity: it learns the identity.
- Assuming a language model's hidden states are good retrieval embeddings; embeddings are only as good as the objective that shaped them.
- Reading the encoder/decoder labels in transformers as 'compressor/decompressor' — the decoder generates, it does not reconstruct.
Recap: all 7 key points
- An autoencoder minimizes ‖x − g(f(x))‖² through a bottleneck k < d; the code z is a learned representation obtained without labels.
- A linear autoencoder with squared loss learns the top-k principal subspace (PCA); nonlinear encoders/decoders learn curved manifolds.
- The manifold hypothesis: real data lies near a low-dimensional manifold; latent coordinates parameterize it, which is why interpolation and generation work.
- Denoising autoencoders estimate the direction back to the data manifold (the score) — the core of diffusion models; masked autoencoders (MAE, BERT) are denoising over patches/tokens.
- nn.Embedding is a V×d lookup table trained by backprop; one-hot × matrix = row selection.
- Embedding similarity is meaningful because training objectives score with dot products, pushing similarly-used items together; the geometry is task-dependent.
- Encoders map inputs to representations, decoders produce outputs from them; the exact meaning differs across autoencoders, seq2seq, transformers and VAEs.
Watch
Starts from the plain autoencoder and its latent-space problems before introducing the VAE — watch the first third now, the rest in [[8.8]].
Read
Try it live
Interactive demo
runs in your browserExercises
- Linear autoencoder vs PCA
Train a linear autoencoder on MNIST with MSE and compare its reconstruction error with scikit-learn PCA using 16 components. Then check that the span of the decoder's columns equals the span of the top-16 principal components (project one onto the other). Expected: equal reconstruction error up to optimization noise; subspaces coincide even though individual vectors differ.
- Nonlinear and denoising autoencoders
Train the
AEabove () on MNIST, then a denoising version that receives inputs with 30% of pixels zeroed. Visualize reconstructions, latent interpolations between two digits, and a 2-D t-SNE of the codes coloured by digit (3.12 Dimensionality reduction: PCA, t-SNE and UMAP). Expected: the denoiser reconstructs clean digits from corrupted ones; codes cluster by digit even though no labels were used. - Linear probe
Freeze the trained encoder and fit logistic regression on the 32-dimensional codes. Compare with logistic regression on raw pixels and on 32 PCA components. Expected: the nonlinear autoencoder's codes give the highest probe accuracy, PCA next, raw pixels close behind — representations make the task more linear.
- Embeddings from scratch
Build an
nn.Embedding(1000, 16)and train it on a toy co-occurrence task (predict whether two random 'items' appear together, with a hidden rule such as 'same remainder mod 10'). Afterwards compute cosine similarities between embeddings. Expected: items that the rule groups together have high cosine similarity — the geometry is created by the objective.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →