Intriguing Properties of Contrastive Losses
Ting Chen, Calvin Luo, Lala Li
Introduction
Contrastive learning has achieved great successes recently for learning visual representations without supervision. As shown in , contrastive learning can learn representations that rival supervised learning, and significantly improve the state-of-the-art in semi-supervised learning on ImageNet. One successful use case of contrastive loss for self-supervised learning is to make augmented views of the same example agree . A widely used contrastive loss to encourage agreement is based on cross entropy . Given an augmented view of an example, the contrastive prediction task aims to classify a set of candidates into the positive example (i.e. the other augmented view of the same example) and negative ones via the cross entropy loss.
In this work, to understand the effectiveness and limitation of existing contrastive learning methods, we study three intriguing aspects. First, we propose a generalization of the standard contrastive loss, and systematically study their performance differences. Second, we study if the instance-based contrastive learning, for which the contrastive loss operates on global representation of an input image, can learn well on images with multiple objects present, and whether or not it leads to meaningful local features. Finally, we systematically study the feature suppression phenomenon in contrastive learning. The suppression effect occurs among competing features shared across augmented views. For example, with random cropping as the augmentation, “color distribution” and “object class” are often competing features as they are likely shared between two augmented views. The suppression effect among competing features can significantly degenerate the representation quality, or even completely disable the learning of certain features, as shown in our experiments. Existing methods critically rely on hand-crafted data augmentation to favor certain sets of competing features than others.
Our main findings and contributions are summarized below.
We propose a generalized contrastive loss, and show that differences between contrastive losses are small with a deep projection head.
We show that the instance-based objective widely used in existing contrastive learning methods can learn on images with multiple objects, and also learn meaningful local features despite operating on global image representation.
We construct three datasets with explicit and controllable competing features to systematically study the feature suppression effect in contrastive learning.
We show that a few bits of easy-to-learn shared features can suppress, and even fully prevent, the learning of other sets of competing features. In scenarios where there are multiple objects in an image, the dominant object would suppress the learning of smaller objects. This poses open challenges to existing contrastive learning.
Generalized contrastive loss and differences among its instantiations
The common contrastive loss used in most recent work is based on cross entropy . Following the notation in , the contrastive loss can be defined between two augmented views of the same example for a mini-batch of size of , and can be written as the following.
In this work, we generalize the standard contrastive loss to the following form.
Both terms are defined on hidden representations. encourages representations of augmented views to be consistent, while encourages representations (or a random subset of them) to match a prior distribution (of high entropy). It is not difficult to see that the standard contrastive loss in Eq. 1 is a special case as it can be re-written as follows (scaled by a constant ).
Connection with mutual information.
The connection between the standard contrastive loss and mutual information has been shown before , where the contrastive loss (a.k.a. InfoNCE loss ) is shown to be a lower bound of the mutual information. To connect the generalized contrastive loss to mutual information, we start by the definition of mutual information between two latent variables , which is . Comparing this factorization of mutual information with generalized contrastive loss, it is not difficult to see that: 1) the alignment term is directly related to which aims to reduce uncertainty of the other views given one view of the example; and 2) the distribution matching term can be considered as a proxy to for maximizing the entropy in the representation. It is perhaps worth noting that different from mutual information, the generalized contrastive loss (Eq. 2) allows a tunable weight () between the alignment and distribution matching term. The weighting scalar is (inversely) related to the temperature (details in Appendix A.2).
Comparing different instantiations of generalized contrastive loss.
Here we ask: Is it essential to use a uniform hypersphere prior for the effectiveness of contrastive loss? How much differences does it make when different generalized contrastive losses are used? To answer this question, we conduct experiments following SimCLR settings , and use the linear evaluation protocol. Detailed experimental setup can be found in appendix A.1.
Figure 1 shows linear evaluation results of models trained with different losses under different training epochs. On CIFAR-10, we see little differences in terms of linear evaluation for variants of the generalized contrastive losses, especially when trained longer than 200 epochs. As for ImageNet, there are some discrepancies between different losses, but they disappear when a deeper 3-layer non-linear projection head is used.
Furthermore, we find that deep projection head not only reduces the differences among different generalized contrastive losses, but has a similar effect for batch size. With proper learning rate scaling across batch sizes (e.g. square root scaling with LARS optimizer ), the impact of batch size on representation quality is small. Table 2 demonstrate this phenomenon for the standard contrastive loss, and more results on other losses can be found in Appendix A.3.
Instance-based objective can learn on images with multiple objects and learn good local features
Most existing contrastive learning methods define their objectives at the instance level where each image is encoded into a single vector representation (e.g. representations of two random crops of the same image instance are treated as a positive pair). In other words, the objective operates on a global representation of its input rather than on some local regions (of its input). We pose two questions regarding instance-based global objective: 1) when there is only a single (dominant) object in the image, the objective seems reasonable as it encourages the model to learn features relevant to object class, but when there are multiple objects present in the image, can instance-based objective still learn well? 2) Since the instance-based objective uses a global summary of its input, can it still learn good local features (e.g. parts of an object, or multiple objects in the same scheme)? To answer these questions, we use SimCLR as representative for the instance-based objective.
Commonly used self-supervised learning datasets, such as MNIST, CIFAR-10, ImageNet, are object centered, i.e. the image is mainly occupied by a single (dominant) object. To experiment with multiple objects in a controllable setting, we propose a new dataset setting by composing multiple digits as follows.
MultiDigits dataset. We place MNIST digits ( size) on a shared canvas ( size). We vary the number of digits placed on the canvas. One factor that could interfere with learning of multiple digits is overlapping digits, therefore we use two placement strategies: random vs in-grid (Figure 2). Random placement of digits incurs no constraint on where digits can be placed on the canvas, whereas in-grid placement puts each digit in one of the grid cells the canvas is divided into, and no two digits can fall in the same cell. In-grid placement ensures no overlapping of digits.
We first pretrain a ResNet-18 with SimCLR or supervised learning with the same augmentation policy (random cropping and resize) on MultiDigits dataset. To access the representation quality, we then train linear classifiers for images with a single digit of size on the canvas. Similarly during evaluation, we place only one digit of size on the canvas.
As shown in Table 3, representations learned using supervised loss maintains its quality when up to 8 digits are placed in the image. After that the representation becomes worse as the canvas gets more crowded. Notably, representations learned using SimCLR display a similar phenomenon. Regardless of placement strategy, top-1 accuracy stays at the same level up to 8 digits, demonstrating that SimCLR can learn from images with multiple objects. In addition, the increased performance gap between the two placement strategies with increased number of digits shows that object overlapping makes it harder for contrastive losses to learn from multiple objects.
2 SimCLR learns local features that exhibit hierarchical properties
To understand the local features learned by SimCLR, we apply K-means on intermediate features of the pretrained ResNet with SimCLR, and see how local regions of an image are grouped together. For good representations, we expect that regions of similar objects or object parts should be grouped together.
Specifically, we take a pretrained Resnet-50 on ImageNet, and run inference on images (from ImageNet validation set and COCO ) of size 448448. We run K-means with various numbers of clusters on the l2-normalized hidden features from middle layers of the network (e.g. block group 2,3,4 of the ResNet). We also compare SimCLR learned features with supervised learned features, as well as the raw pixel (RGB) features extracted from each patch.
Figure 3(a) shows that as the number of clusters increases, the learned representations tend to group image regions based on parts of the object (i.e. facial components of the dog). This phenomenon appears in both SimCLR and supervised learned features, but not with raw pixel features, indicating meaningful local features learned by SimCLR and supervised learning. In Figure 3(b), we compare ResNet intermediate features at different layers, and it suggests that earlier layers contain more edge-related features, while later layers contain more object/part features.
Figure 4 show region grouping results on two COCO images of SimCLR and supervised learning (trained on ImageNet). Again, region grouping by local features tend to overlap with object class, indicating good local features learned.
Feature suppression limits the potential of contrastive learning
Contrastive learning requires good design of data augmentation to work well. As shown in , without color augmentation that randomly shift color distribution (while maintaining information regarding object class), the quality of learned representations are significantly worse. In other words, the presence of “color distribution” features suppresses their competing feature of “object class”, and is addressed by color augmentation. However, there may be scenarios where the known augmentations cannot fully address this feature suppression effect, and it can thus limit the potential of contrastive learning. Here we quantitatively study the feature suppression phenomenon by constructing datasets with explicit and controllable competing features, and see how well contrastive learning method could learn.
To construct datasets with controllable competing features, we leverage two strategies: channel addition that adds different feature information in a shared canvas, and channel concatenation that expand the RGB channels to include additional features. With these strategies, we construct three datasets below.
DigitOnImageNet dataset. We overlay MNIST digits on ImageNet images via channel addition/summation (Figure 5(a)). For each ImageNet image, we assign an unique MNIST digit and replicate it in nine fixed locations before the standard SimCLR augmentations are applied to create augmented views. Therefore the original ImageNet images and added MNIST digits are competing features. Although it is difficult to quantify information in MNIST digits, we can manually control the number of unique MNIST digits used. Ideally, we want the model to learn both set of features so that it could perform well for both MNIST digit and ImageNet object recognition.
MultiDigits dataset (varying the size of one digit). This dataset is modified from MultiDigits introduced above. Here we only consider two digits and varying the size of one digit (Figure 5(b)). The canvas size is , and we place two digits on it in this work. We fix the size of one of the digits to be while varying the other from to . Digits of different sizes can be considered as competing features. Ideally, we want the model to learn features for digits of all sizes appeared during training.
RandBit dataset. We concatenate a real image with an image of a random integer in their channel dimension (Figure 5(c)). The random integer is randomly sampled from range of where is a parameter to control. It is replicated across spatial dimension (i.e. all pixel location shares the same value), and it is also represented as binary bits/channels instead of an integer or floating number to make it easily learnable. Furthermore, unlike RGB channels, these additional channels of random bits will not be altered by augmentation, so they are identical for both augmented views of the same image. The RGB channels and the added channels of random bits are competing features, and this construction allows us to control the amount of information in the added competing feature, which is bits. Also, we know that the mutual information between two views given this construction is at least .
2 Easy-to-learn features (MNIST digit) suppress the learning of other features (ImageNet object class)
On DigitOnImageNet datasets, we vary the number of unique MNIST digits used in the training set, and all MNIST digits are used in the validation/test set. As a baseline, we train supervised ResNet-50 on the created datasets with ImageNet labels, and the number of unique MNIST digits has little impact on the top-1 ImageNet classification accuracy (Figure 6(a)).
We then train SimCLR on the datasets with different temperatures. As shown in Figure 6(b), when we increase the number of unique MNIST digits, the linear evaluation performance of the learned features for MNIST classes increases accordingly, while the accuracy for ImageNet classes decreases dramatically. The trade-off between digit recognition ability and object recognition ability shows that simple features suppress the learning of difficult features, when both are shared between two augmented views. Different batch sizes and projection head depths have negligible influence to the outcome we observe here. Therefore, it is difficult to learn both of the competing features using existing contrastive losses (e.g. SimCLR).
3 The presence of dominant object suppresses the learning of features of smaller objects
On the MultiDigits dataset, as mentioned, we fix one digit to be size of while varying the other from to , on a canvas of . We first pretrain a ResNet-18 with SimCLR or supervised learning with the same augmentation policy (random cropping and resize) and batch size of 1024. To access the representation quality, we then train linear classifiers for each of the digit sizes that appeared during pretraining. For training of the linear classifier, we only place a single digit at a time on the canvas of the same size as during pretraining.
The results are summarized in Table 4. For supervised learning, the learned representations for the smaller digit do not change much as the other digit increases its size, and the model perform well for both small and large digits (accuracy ). However, for SimCLR, the learned representations of the smaller digit degenerate significantly when the size of the other digit increases, almost to the level of a random untrained network. The dominant object can be learned very well (accuracy ) while suppressing the learning of the smaller object. Although tuning temperature has some effects on reducing the feature suppression, the trend stays unchanged.
In the RandBit datasets, we add additional channels (identical across pixels) of random bits to MNIST and ImageNet. As mentioned above, SimCLR augmentation is only applied to RGB channels so extra added channels will be shared among two view.
Figure 7 shows the linear evaluation accuracy of models trained on MNIST (with additional random bits added). We observe that the linear evaluation accuracy quickly drops with a few bits of competing feature added. This detrimental effect on the representation quality persists on bigger datasets like CIFAR-10 and ImageNet as well, and cannot be avoided by using different contrastive losses, batch sizes, or memory mechanism based on momentum contrast (details in Appendix B.1). We believe the fact that just a few bits of easy-to-learn features can completely disable the good representation learning is related to the saturation of the distribution matching loss. As shown in Appendix B.2, the linear increase in bits requires an exponential increase in batch size, which is not sustainable as the required batch size can quickly go beyond the size of the dataset size. In practice, we rely on using data augmentation to remove those uninformative easy-to-learn features so that contrastive learning can learn useful representations. Interestingly, the extra bits do not affect a generative model, variational autoencoder , nearly as much, despite other settings such as model size are held the same, prompting a potential direction of addressing the issue.
Related Work
Our work studies the contrastive loss based on cross entropy loss . This loss is widely used in recent successful contrastive learning methods . In terms of the contrastive loss, our work is perhaps most related to , which shows that formulating contrastive loss as alignment and uniformity in the hypersphere gives similar performance as the standard contrastive loss. We further generalize this factorization, and show other distribution matching losses can be used, and they could achieve similar results. Other than standard contrastive loss that directly utilize negative examples, BYOL demonstrates another way to maintain representation distribution/entropy without directly relying on distribution matching, and SWAV shows clustering-based method equipped with proper data augmentations could also achieve similar performance. We conduct preliminary experiments of BYOL on RandBit and found that it also suffers from feature suppression as generalized contrastive loss. It is expected that SWAV would exhibit similar behaviors on RandBit as those random bits could fuel representations for perfect clustering.
The connection between contrastive loss and mutual information has been studied before . We show that for the generalized contrastive loss, it can also be related to mutual information. Despite the connection between contrastive loss and mutual information, it has been pointed out that mutual information estimation may suffer from certain limitations . Moreover, show that higher mutual information learned by the network does not warrant better representation quality. In our work, we find adding mutual information bits between two views which are irrelevant to downstream tasks can be harmful for the quality of learned representations. Data augmentation plays an important role at favoring certain bits of mutual information than others.
There is a growing number of recent work on the topic of understanding contrastive learning, both theoretically and empirically . However, little work has been done to study the phenomenon of feature suppression. To our knowledge, we are the first one to quantitatively and systematically study this problem. We believe this is still a very open question and could benefit from more future investigation. Finally, the feature suppression effect in unsupervised contrastive learning that we study in this work may also exist in standard supervised learning (“contrastive loss” between examples and class labels), as suggested by , though the specific form would be different.
Conclusion
In this work, we study three intriguing properties of contrastive losses. In particular, our results highlight that feature suppression is still an open challenge in contrastive learning. While there is a plethora of work on improving contrastive learning, few of them directly aim to address feature suppression. This limitation of contrastive learning becomes a bottleneck for scenarios where existing augmentation cannot fully address the feature suppression phenomenon, and learning would saturate at a level of dissatisfaction.
We would also like to point out some limitations of our study. Firstly, we focus mostly on contrastive learning with explicit negatives (e.g. SimCLR and MoCo). We believe other methods based on clustering and/or without negative pairs would exhibit similar phenomenon but we leave that as future work. Secondly, many of our proposed image datasets are not fully realistic despite being composed from some (challenging) natural image datasets such as ImageNet. We admit it is very hard to explore competing features or multiple objects in a controllable fashion on realistic large scale image datasets.
Acknowledgements
We specially thank Geoffrey Hinton for many inspiring discussions and helpful advice. We would also like to thank David Fleet, Simon Kornblith, Mohammad Norouzi, Kevin Swersky and Katherine Hermann for insightful discussions. In addition, we are thankful to William Chan and Sara Sabour for ideas on implementation of sorting on TPUs. We also thank anonymous reviewers for their constructive feedback.
References
Appendix A More on generalized contrastive loss
A.2 Temperature τ𝜏\tau is (within a range) inversely correlated to weighting λ𝜆\lambda of distribution loss
To see how well the learned distribution matches the prior distribution (e.g. Gaussian), we randomly project the (high-dimensional) representation vectors into 1-D space and plot the histogram distribution. For prior distribution of Gaussian or uniform in hypersphere, these random projections in 1-D space should be Gaussian like.
Figure A.1 shows random orthogonal projection of representation from CIFAR-10 test set. We see that both weighting ( in Eq. 2) and the temperature scaling ( in Eq. 1) have the effect of controlling distribution matching term, but they have an inverse correlation. In other words, using a higher temperature has similar effect as setting a larger weighting of distribution matching term.
Decoupled NT-Xent loss.
It is worth noting that temperature in the rewritten NT-Xent loss (Eq. 3) appears in two places, one as the scaling of the distribution loss term, and the other as the width of Gaussian kernel. They do not necessarily need to be the same, so we could decouple them as follows.
The decoupling allows us to study the effects of them separately. So we tune and separately for the decoupled NT-xent loss. Figure A.2 shows the linear evaluation of ResNet-18 trained in 200 epochs. We see that the temperature and the weighting are inversely correlated for most range. In practice one could simply fix one and tune the other.
A.3 Linear evaluation of generalized contrastive losses on CIFAR-10 and ImageNet
Table A.1, A.2 and A.3 show linear evaluation performance of ResNet-50 trained with different losses (numerical results of Figure 1). Similar to , a square root learning rate is used. In addition, results of different batch sizes are also compared, and we find the differences are small with reasonable sizes (e.g. 128 for CIFAR-10 and 1024 for ImageNet).
Appendix B More on feature suppression
Figure B.1 shows linear evaluation on CIFAR-10 with different random bits added trained with a wider range of batch sizes. It is worth noting that the bits (in the x-axis) are calculated based on the total size of uniform integer distribution. However, this is an overestimation of actual bits as due to collision in generated integers. We observe that the linear evaluation accuracy decreases quickly with a few bits of the extra channel competing feature added. And this detrimental effect on the representation quality cannot be avoided by different contrastive loss functions, batch sizes, or memory mechanism in momentum contrast . Although a smaller temperature () or larger weighting () slightly mitigate the degeneration effect, its baseline performance when no extra bits are added is also worse. With less than 15 bits of competing features added, the representation quality degenerates to the level where RGB channels are completely ignored.
Similar results are shown for ImageNet as shown in Figure B.2.
Figure B.3 shows that distribution loss saturates quickly with a few bits of entropy in the dataset (same or less bits in representations), and both temperature and batch sizes have effects on the saturation behavior. It also shows that linear increase of bits in representation requires exponentially increase of batch size, which is not sustainable as the required batch size can quickly go beyond the size of the dataset (e.g., 30 bits would require more than 1 billion batch size, which is larger than most of the existing datasets). This is one of the main reasons why data augmentation is critical for contrastive learning - that the network can learn a few bits that give rise to useful representations.