Embeddings
Neural networks are mathematical functions that require vector (or matrix or tensor) inputs. Last time, we saw how PCA (really SVD in disguise) reduces the dimension of data while maintaining its structure. Today, we’ll see techniques for converting more general data into representations called embeddings.
We’ll start by applying PCA to word counts, then use nonlinear encoders to preserve more complicated structure and contrastive learning to directly reward similarity.
Co-occurrence Embeddings
In order to process words, we’ll need to represent them as vectors. One simple representation gives every word its own dimension: put a one there and zeros everywhere else. This is a one-hot vector. It tells us which word we have, but every pair of distinct words is the same distance apart.
Our starting idea will be to learn something about a word from the company it keeps: For each word, count the words nearby, e.g., the two words on either side within the sentence. Repeat for every word to build a co-occurrence matrix where each row corresponds to a word, each column corresponds to a word, and each entry counts how often they appear together in the window.
Here’s an example from Dr. Seuss’s The Cat in the Hat:
Each row now describes the contexts in which a word appears, but with a large vocabulary, it could have thousands of entries.
This is where PCA comes in: Subtract each column’s mean to get the centered \(\mathbf X\), then use our linear encoder to compute \(\mathbf Z=E(\mathbf X)\). Each row \(\mathbf{x}_i\) now has a short embedding \(\mathbf{z}_i\). As we showed last time, \(\mathbf{z}_i\) and \(\mathbf{z}_j\) are close when \(\mathbf{x}_i\) and \(\mathbf{x}_j\) are. That is, the embeddings of two words are similar when their co-occurrences are.
The counts we choose matter. Very frequent words can dominate squared error, so we might first replace each count by \(\log(1+\text{count})\) and then center.
Once we have word embeddings, we can do fun word math:
These plots use GloVe word vectors, learned from co-occurrence counts. Each shows a three-dimensional PCA view of the words and nearby tokens. The arrows copy the same change from one word to another. Nearby tokens are chosen by cosine similarity in the original embedding space. The arithmetic is approximate.
A limitation of co-occurrence embeddings is that the same word can have different meanings: For “bank”, for example, the counts mix together river bank and bank loan, so both uses get the same embedding. Later, we’ll see how language models give a word different representations depending on its sentence.
Nonlinear Autoencoders
Let’s revisit PCA. Eckart–Young–Mirsky tells us that PCA gives the best linear reconstruction. But why stop at linear maps? There may be high-dimensional non-linear structure that we’d like to represent.
A manifold is a nonlinear analogue of a subspace. We can use fewer coordinates to identify where a point lies on it, but following its shape may require a nonlinear representation. For the rolled sheet below, each point has three coordinates, but we only need two to locate it on the sheet: how far along it lies and its height.
The embedding unfolds the sheet.
For real data, we need to learn an encoder and decoder that can follow the shape. An autoencoder uses neural networks for \(E\) and \(D\) and trains them together to minimize
\[ \min_{E,D}\ \|\mathbf X-D(E(\mathbf X))\|_F^2. \]
In contrast to the PCA encoder and decoder, each network can have several layers with nonlinear activations. The variables we’re optimizing are the weights of the two networks. We feed an example through \(E\) and then \(D\), compare the reconstruction with the input, and backpropagate through both networks. Once trained, we can run a new input through \(E\) to get its embedding. Gradient descent may not find the best weights, but nonlinear maps give us reconstructions that PCA cannot produce.
But a better reconstruction isn’t always a better representation for our task. Suppose we want to recognize an animal in a photograph. Most pixels might belong to the background, so the autoencoder could reduce its error by preserving the grass while losing a small feature that identifies the animal. To get the embeddings we want, we may need to change what we reward.
Contrastive Learning
The goal of contrastive learning is to make similar inputs have similar embeddings, where we directly control the definition of similarity. We call two inputs that we know are similar a positive pair and all other combinations of inputs negative pairs. Contrastive learning trains an encoder to find positive pairs.
Our encoder \(E\) can be a nonlinear neural network, just as in the autoencoder. This time, however, we train it to recognize matches. (We don’t need a decoder or a reconstruction of the input.)
Arrange \(n\geq2\) positive pairs in two batches \(\mathbf X\) and \(\mathbf X'\), so example \(i\) in one matches example \(i\) in the other. The prime marks the second batch. Apply the same encoder to each point and normalize its output to length one. Assuming the outputs are nonzero and including normalization in \(E\), we get
\[ \mathbf Z=E(\mathbf X),\qquad \mathbf Z'=E(\mathbf X'),\qquad \mathbf S=\mathbf Z(\mathbf Z')^\top. \]
Both embedding matrices have \(n\) rows and \(k\) columns. The \(n\times n\) matrix \(\mathbf S\) compares every embedding in the first batch with every embedding in the second. Its entry \(S_{ij}=\mathbf z_i^\top\mathbf z'_j\) is their cosine similarity, since the vectors have length one. The matrix multiplication computes these comparisons after the neural network has produced the embeddings.
Now look at row \(i\) of \(\mathbf S\). We have \(n\) scores, one for each candidate. This is a classification problem where our goal is to find candidate \(i\)! We can use the same softmax and cross-entropy we used in logistic regression.
Here’s an example with photos of my cats and their captions. The matrix shows the target labels, with a one for each correct match. For image–text pairs, we use separate encoders whose outputs share the same embedding space.
First, turn the scores into probabilities. Write \(p_{ij}\) for the probability assigned to candidate \(j\) when finding a match for example \(i\):
\[ p_{ij}=\frac{\exp(S_{ij}/\tau)}{\sum_{k=1}^n\exp(S_{ik}/\tau)}. \]
The numerator increases with candidate \(j\)’s similarity. The denominator adds up all the candidates’ contributions, so each row of probabilities sums to one.
The temperature \(\tau>0\) controls how strongly score differences affect these probabilities. A smaller temperature makes the distribution more concentrated on the highest scores. A larger temperature makes it more uniform.
The correct candidate is \(i\), so its probability is \(p_{ii}\). Cross-entropy takes the negative log of that probability, then we average over the batch:
\[ \ell_i=-\log p_{ii},\qquad \mathcal L=\frac1n\sum_{i=1}^n\ell_i. \]
To reduce the loss, the encoder must make the correct match stand out among the candidates. This is the contrastive cross-entropy objective used in methods such as SimCSE.
Let’s interpret what the gradient does. Substituting the softmax probability gives
\[ \ell_i=-\log p_{ii}=-\frac{S_{ii}}{\tau}+\log\left(\sum_{k=1}^n\exp(S_{ik}/\tau)\right). \]
Differentiating with respect to the matching score \(S_{ii}\) and a competing score \(S_{ij}\) gives
\[ \frac{\partial\ell_i}{\partial S_{ii}}=\frac{p_{ii}-1}{\tau}<0,\qquad \frac{\partial\ell_i}{\partial S_{ij}}=\frac{p_{ij}}{\tau}>0\quad(j\ne i). \]
Gradient descent therefore favors increasing the matching score and decreasing competing scores, with larger corrections for competitors assigned high probability. Backpropagation carries these gradients through the embeddings to update \(E\).
Why include the other candidates? If we only rewarded similarity within positive pairs, \(E\) could give every input the same unit vector. This is called collapse. Here, all the scores would be equal, giving \(p_{ij}=1/n\) and a loss of \(\log n\). The encoder would be no better at finding a match than a uniform guess.
The pairs still matter. Two sentences we treat as negatives may mean the same thing. The loss would then ask the encoder to distinguish examples we’d prefer to keep together. Therefore choosing the pairs is part of choosing what our embeddings should preserve.
Language Model Embeddings
How do large language models learn embeddings? For a GPT-style model, the main training task is to predict the next token. The embeddings are learned along with the rest of the model, without first building a co-occurrence matrix or running PCA.
First, split the text into tokens: words, parts of words, or punctuation. Each token gets an initial vector from a learned table. Transformer layers then combine it with information from the preceding tokens to predict what comes next. Cross-entropy rewards the token that actually appeared in the text, and backpropagation updates both the initial vectors and the transformer weights.
This pre-training gives us a way to distinguish the two uses of bank. The initial table supplies the same vector for that token, but the transformer layers can change its representation using the surrounding text available to them. These are contextual embeddings. What they learn to keep is shaped by the prediction task: information that helps predict the next token reduces the training loss.