Back to paper library
arXiv 2018Contrastive learningPaper notes

CPC

Today shapes tomorrow

Original paper

Representation Learning with Contrastive Predictive Coding

Paper authors

Aaron van den Oord · Yazhe Li · Oriol Vinyals

Publication
Publication venue not yet verified
First submitted to arXiv
arXiv:1807.03748
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{contrastivelearningcpc2018,
  title = {{Representation Learning with Contrastive Predictive Coding}},
  author = {Aaron van den Oord and Yazhe Li and Oriol Vinyals},
  year = {2018},
  eprint = {1807.03748},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1807.03748}
}
On this page

When dealing with complex, high-dimensional data, we often encounter a profound question:

Which features are truly "important"? Which ones are "insignificant"?

In supervised tasks, in order to minimize the loss function on the training set, the model will often, without our notice, fit some irrelevant features—such as noise, camera angle biases, recording device characteristics, or the habits of the annotators.

In the short term, the model's performance on the training set improves, and it may even perform well on the test set. However, when deployed in a real environment or faced with unseen data, the model may lose the "overfitted" features it previously relied on, significantly diminishing its ability to generalize.

Defining the Problem

At this time, generative models are a very popular unsupervised learning approach. The goal of these models is to learn the joint distribution of the data p(x)p(x) and generate new samples via a generative model p(x∣z)p(x \mid z).

At first glance, this seems fine, but consider this:

A generative objective that predicts pixels can devote substantial capacity to low-level details that are irrelevant to classification. This depends on the likelihood or reconstruction loss; generative learning does not universally require an exactly identical reconstruction.

For representation learning, that computation may not directly serve the downstream task.

The so-called "higher-order abstract" information in speech data might include the speaker’s gender, pitch variation, speech rate, and style. In image data, it might be object shapes, spatial relationships, or styles.

The authors argue that we should focus on: which features should be selected to reproduce the original form at the next moment (or later moments).

  • The key lies in "prediction" not "reconstruction."

As long as we can identify the key factors that determine future directions, we can obtain highly relevant information between the "latent representations of the past" and the "features of the future."

Instead of realistically "reproducing" the future, it is better to "extract" the higher-order semantics shared between the present and future.

Isn't this what people have been discussing for thousands of years?

Solving the Problem

Model Architecture

To solve the problem, the authors propose the Contrastive Predictive Coding (CPC) framework.

The overall architecture is shown in the figure above. We can look at it step by step:

  1. Encoder gencg_{\text{enc}}

    The first step is to transform the raw input sequence {xt}\{x_t\} (which could be feature vectors of each position in an image or every moment of a segmented audio signal) through a "non-linear encoder" gencg_{\text{enc}} to obtain a latent representation {zt}\{z_t\}:

    zt  =  genc(xt).z_t \;=\; g_{\text{enc}}(x_t).

    The purpose of this step is to compress the high-dimensional input into a more concise or abstract representation space, often achieved through convolutional networks (for images or sounds) or other neural network architectures.

  2. Autoregressive model garg_{\text{ar}}

    Next, an autoregressive model garg_{\text{ar}} (such as GRU, LSTM, or another form of RNN) is used to read the time sequence {z1,z2,…,zt}\{z_1, z_2, \ldots, z_t\} and generate a "context representation" ctc_t:

    ct  =  gar(z≤t)  =  gar(z1,z2,…,zt).c_t \;=\; g_{\text{ar}}(z_{\le t}) \;=\; g_{\text{ar}}(z_1, z_2, \ldots, z_t).

    ctc_t can be seen as the hidden state "the model uses to predict the future after time tt," summarizing the observed zz representations up to that point.

  3. Prediction for the Future: Estimating the "Density Ratio" Rather than Direct Generation

    As mentioned earlier, the goal of CPC is to predict future features xt+kx_{t+k} given the context ctc_t.

    However, CPC does not directly model p(xt+k∣ct)p(x_{t+k} \mid c_t) (generating the entire xx), but instead learns a density ratio:

    fk(xt+k,ct)    ∝    p(xt+k∣ct)p(xt+k).f_k(x_{t+k}, c_t) \;\;\propto\;\; \frac{p(x_{t+k} \mid c_t)}{p(x_{t+k})}.

    This ratio represents the likelihood of observing xt+kx_{t+k} given context ctc_t, relative to the likelihood of observing xt+kx_{t+k} without any context.

    The authors provide a simple implementation using a log-bilinear form:

    fk(xt+k,ct)  =  exp⁡(zt+kT Wk ct),f_k(x_{t+k}, c_t) \;=\; \exp\bigl( z_{t+k}^\mathsf{T} \, W_k \, c_t \bigr),

    where zt+kz_{t+k} is the representation of xt+kx_{t+k} after passing through the encoder, and WkW_k is a learnable linear transformation. Different WkW_k can be used for the future kk-th time step.


Here, directly generating high-dimensional data (e.g., images or speech) requires complex models; however, the goal is simply to use "information related to the context." In other words, the model doesn't need to reproduce all the background noise, only to perform contrastive recognition or differentiation of the captured abstract features.

In practice, the learned representations ztz_t or ctc_t from this framework can be used for downstream tasks.

If more "historical context" is needed (e.g., for speech recognition, which requires capturing longer speech segments), use ctc_t. If the task can be handled immediately (e.g., some localized recognition), ztz_t may suffice. Pooling across the entire image or sequence can also be used to obtain an overall representation.

InfoNCE

Next, let's look at the loss function used by the authors: InfoNCE.

Explaining InfoNCE directly might catch you off guard, so let’s begin with the simple cross-entropy.

In binary classification, the predicted positive-class probability should approach 1 for positive examples and 0 for negative examples. This can be written as the "cross-entropy loss":

CE=−[ ylog⁡(y^)  +  (1−y)log⁡(1−y^)]\mathrm{CE} = - \Bigl[\, y \log(\hat{y}) \;+\; (1-y)\log(1-\hat{y}) \Bigr]
  • If y=1y=1 (positive class), the loss becomes −log⁡(y^)-\log(\hat{y}).
  • If y=0y=0 (negative class), the loss becomes −log⁡(1−y^)-\log(1-\hat{y}).

Cross-entropy here plays the role of "forcing the model to output the correct probabilities." If we treat the "positive sample" as class 1 and the "negative sample" as class 0, we can train using cross-entropy.

For KK classes, each input xx corresponds to one of the classes kk.

The model outputs a score {s1(x),…,sK(x)}\{s_1(x), \dots, s_K(x)\} for each class, and we convert this into probabilities y^k\hat{y}_k using softmax:

y^k=exp⁡(sk(x))∑j=1Kexp⁡(sj(x)).\hat{y}_k = \frac{\exp(s_k(x))}{\sum_{j=1}^K \exp(s_j(x))}.

If the true label is "class ii", the entire cross-entropy loss becomes

CE  =  − log⁡(y^i)  =  − log⁡(exp⁡(si(x))∑j=1Kexp⁡(sj(x))).\mathrm{CE} \;=\; -\, \log \Bigl(\hat{y}_i\Bigr) \;=\; -\, \log \biggl( \frac{\exp(s_i(x))}{\sum_{j=1}^K \exp(s_j(x))} \biggr).

In other words, we want to maximize exp⁡(si(x))\exp(s_i(x)) while relatively lowering the other exp⁡(sj(x))\exp(s_j(x)) (j≠ij \neq i) to ensure the "correct class" has the highest probability.

In contrastive learning, we often encounter the situation:

In a batch of samples, only one corresponds to your condition/context, and the others are either "mismatched" or pure "noise."

For example, out of NN samples, only 1 sample is positive, and the remaining N−1N-1 are negative. We want to use the same cross-entropy to "select which one is the positive sample."

At this point, we can use multiclass classification with K=NK = N: each candidate position is one choice.

  • The "positive sample" occupies one position,
  • The remaining N−1N-1 positions hold negative samples.

In practice, we don't treat each negative sample as a distinct semantic class; we treat "which sample is the positive one" as a one-of-many problem.

InfoNCE uses multiclass cross-entropy to perform the "positive vs. negative" contrast.

In the paper, the loss for InfoNCE is defined over a candidate set as follows:

LN=− EX[log⁡fk(xpos,c)∑xj∈Xfk(xj,c)]L_N = -\, \mathbb{E}_{X} \Biggl[ \log \frac{ f_k(x_{\text{pos}}, c) } { \sum_{x_j \in X} f_k(x_j, c) } \Biggr]

Where:

  • X={x1,x2,...,xN}X = \{x_1, x_2, ..., x_N\} includes 1 positive sample xposx_{\text{pos}} (which truly matches the context cc), and N−1N-1 negative samples.
  • fk(x,c)f_k(x, c) is a positive score, analogous to exp⁡(si(x))\exp(s_i(x)) above.
  • The candidate set XX need not be a training batch. For the mutual-information bound below, the positive is drawn conditionally on cc and the negatives independently from the marginal distribution p(x)p(x).

In this one-of-many problem, the NN candidates occupy NN positions, and the model must find the position of the positive sample.

The name InfoNCE comes from the fact that the authors further prove:

  • Minimizing this contrastive cross-entropy (LNL_N)
  • Raises the lower bound of the mutual information between the context cc and the target sample xposx_{\text{pos}}.

In other words, when we use this contrastive method to differentiate between "positive vs. negative samples," the model is forced to learn the "shared information between the context and the positive sample."

  • Mathematically, it can be proven that: I(x,c)≥log⁡(N)−LNI(x, c) \ge \log(N) - L_N.
  • Under the paper's sampling assumptions, a larger NN can make this bound tighter; its actual value still depends on LNL_N.

Discussion

The authors applied the CPC method to four different domains:

  1. Speech
  2. Images
  3. Natural Language
  4. Reinforcement Learning

The authors explored how much distinguishable information the model learned through "linear classification" or qualitative evaluations. In reinforcement learning, they incorporated the CPC auxiliary loss function into the agent model to observe improvements in convergence speed.

However, due to space constraints, we will only look at the results of CPC in the speech and image domains. For the other domains, readers are encouraged to refer to the original paper.

Speech Recognition

In the speech domain, the authors used a 100-hour subset from the publicly available LibriSpeech dataset. Although the dataset primarily provides raw speech and transcribed text, the authors used the Kaldi toolkit and its pretrained model on LibriSpeech to generate corresponding "phoneme sequence" labels.

The authors have uploaded the aligned phone labels and their training/test split to Google Drive for easy reproduction of the experiments. The dataset contains 251 different speakers.

The model architecture, as described earlier, uses a 5-layer convolutional network as the encoder, with each layer's stride and filter size being [5,4,2,2,2][5, 4, 2, 2, 2] and [10,8,4,4,4][10, 8, 4, 4, 4], respectively. Each layer has 512 hidden units, and the ReLU activation function is used.

In the autoregressive model, the authors used a GRU with a hidden layer dimension of 256. During training, the Adam optimizer was used with a learning rate of 2×10−42 \times 10^{-4}, and the training was conducted on 8 GPUs.

The figure below shows, for 1 to 20 future steps, the average fraction of comparisons in which the positive sample scores above the negative samples:

Overall, predicting further into the future (e.g., t+20t+20) becomes more challenging, and the fraction of positive scores above negative scores falls. This is a result for the contrastive prediction task, not downstream phone-classification accuracy.

To better understand the representations learned by CPC, after training, the authors extracted the GRU outputs (i.e., ctc_t, 256 dimensions) and used this vector as a feature to perform linear classification for multiclass recognition across the entire dataset.

The results are shown in the table below:

The terms in the table represent:

  • Random initialization: Features from a randomly initialized encoder, evaluated with a trained classifier.
  • MFCC: Traditional speech features (Mel-frequency cepstral coefficients) used to train the same linear classifier.
  • Supervised: End-to-end training using labeled data (the same convolutional + GRU architecture), used as a supervised reference, not a theoretical upper bound.

For phone classification, CPC reaches 64.6%, above MFCC's 39.7% but below the fully supervised model's 74.6%. Speaker classification reaches 97.4%, close to the supervised model's 98.5%. If the phone-classification probe has one hidden layer, its accuracy rises from 64.6% to 72.5%; that is a different setting from the linear probe in the table.

Ablation Experiments

To validate whether the design of CPC truly helps, the authors conducted two types of ablation experiments:

  1. Changing the prediction time steps: Predicting 2, 4, 8, 12, and 16 future steps gives phone-classification accuracies of 28.5%, 57.6%, 63.6%, 64.6%, and 63.8%, respectively. Predicting multiple steps helps in this setting, though more steps are not always better.
  2. Different negative sample strategies:
    • "Mixed speakers" vs. "Same speaker": Whether to include slices from different speakers in the negative samples.
    • Whether to exclude the current sequence itself as a source of negative samples (excl. in the table).
    • Drawing negative samples only from the current sequence vs. from other sequences in the batch.

These strategies change the phone-classification results: same-speaker negatives give 65.5%, compared with 64.6% for mixed-speaker negatives; excluding the current sequence gives 64.6% and 57.3%, respectively. Drawing only from the current sequence gives 65.2%. The table does not support saying that one sampling strategy is always best.

Speaker Identification Visualization

The authors used t-SNE to project CPC speech representations from 10 of the 251 speakers onto a 2D plane.

In this qualitative example, the representations of those 10 speakers are mostly separated. The 97.4% speaker-classification accuracy in Table 1 gives more direct quantitative evidence.

Image Recognition

In the image domain experiments, the authors used the ILSVRC ImageNet dataset, which is a common benchmark for evaluating various unsupervised visual models.

The authors followed the approach from past literature:

The encoder was an initially untrained ResNet v2-101 without Batch Normalization. After unsupervised training, a linear classifier was trained using ImageNet labels for evaluation.

Training first randomly cropped a 256×256 image from a 300×300 image. A 7×7 grid was then extracted from that crop, with each patch measuring 64×64 and overlapping its neighbors by 32 pixels.

Training also used horizontal flipping (50% chance) and conversion to grayscale. Each 64×64 patch was randomly cropped to 60×60 and then padded back to 64×64.

The representations extracted by ResNet v2-101 came from the third residual module, followed by spatial average pooling to obtain a 1024-dimensional vector, forming a 7×7×1024 tensor. The next step used a PixelCNN-like architecture to perform "autoregressive" predictions on the 7×7 grid: from top to bottom, each row tried to predict the features up to 5 rows ahead, with contrastive loss applied to each patch in the target row.

The experimental results are shown in the table below:

The metrics are top-1 and top-5 classification accuracy on ImageNet. CPC reaches 48.7% top-1, 9.1 percentage points above the previous best 39.6% within the table's ResNet-v2 group. Its 73.6% top-5 is 4.3 percentage points above the 69.3% four-task combination listed as the previous best.

  • The table groups AlexNet and ResNet-v2 top-1 results separately; they should not be read as comparisons using the same backbone.
  • The CPC linear classifier spatially average-pools the 7×7×1024 representation first. The cited prior method uses a different feature size and classifier setup.

These ImageNet linear evaluations show higher accuracy for CPC under the reported settings; the backbone and probe differences still matter when comparing methods.

Visualization of Image Features

Finally, the authors show image patches that strongly activate the same neuron, one neuron per row. Eyes, wheels, sky, and other similar appearances recur within rows. This is a qualitative view of feature preferences; the classification results in the table remain the evidence for accuracy.

Conclusion

CPC offers a flexible and efficient approach in the field of unsupervised learning, combining autoregressive models with noise contrastive loss to automatically extract more abstract and generalizable representations from high-dimensional inputs.

In the past, we often had to tailor specific feature extraction methods for different data modalities or application scenarios. However, CPC shows that representation learning can be performed with a similar mechanism across tasks in speech, image, and text, and this universality opens up more possibilities for future research and applications.