Contrastive Learning with Hard Negative Samples
Joshua Robinson, Ching-Yao Chuang, Suvrit Sra, Stefanie Jegelka
Introduction
Owing to their empirical success, contrastive learning methods (Chopra et al., 2005; Hadsell et al., 2006) have become one of the most popular self-supervised approaches for learning representations (Oord et al., 2018; Tian et al., 2019; Chen et al., 2020a). In computer vision, unsupervised contrastive learning methods have even outperformed supervised pre-training for object detection and segmentation tasks (Misra & Maaten, 2020; He et al., 2020).
Contrastive learning relies on two key ingredients: notions of similar (positive) and dissimilar (negative) pairs of data points. The training objective, typically noise-contrastive estimation (Gutmann & Hyvärinen, 2010), guides the learned representation to map positive pairs to nearby locations, and negative pairs farther apart; other objectives have also been considered (Chen et al., 2020a). The success of the associated methods depends on the design of informative of the positive and negative pairs, which cannot exploit true similarity information since there is no supervision.
Much research effort has addressed sampling strategies for positive pairs, and has been a key driver of recent progress in multi-view and contrastive learning (Blum & Mitchell, 1998; Xu et al., 2013; Bachman et al., 2019; Chen et al., 2020a; Tian et al., 2020). For image data, positive sampling strategies often apply transformations that preserve semantic content, e.g., jittering, random cropping, separating color channels, etc. (Chen et al., 2020a; c; Tian et al., 2019). Such transformations have also been effective in learning control policies from raw pixel data (Srinivas et al., 2020). Positive sampling techniques have also been proposed for sentence, audio, and video data (Logeswaran & Lee, 2018; Oord et al., 2018; Purushwalkam & Gupta, 2020; Sermanet et al., 2018).
Surprisingly, the choice of negative pairs has drawn much less attention in contrastive learning. Often, given an “anchor” point , a “negative” is simply sampled uniformly from the training data, independent of how informative it may be for the learned representation. In supervised and metric learning settings, “hard” (true negative) examples can help guide a learning method to correct its mistakes more quickly (Schroff et al., 2015; Song et al., 2016). For representation learning, informative negative examples are intuitively those pairs that are mapped nearby but should be far apart. This idea is successfully applied in metric learning, where true pairs of dissimilar points are available, as opposed to unsupervised contrastive learning.
With this motivation, we address the challenge of selecting informative negatives for contrastive representation learning. In response, we propose a solution that builds a tunable sampling distribution that prefers negative pairs whose representations are currently very similar. This solution faces two challenges: (1) we do not have access to any true similarity or dissimilarity information; (2) we need an efficient sampling strategy for this tunable distribution. We overcome (1) by building on ideas from positive-unlabeled learning (Elkan & Noto, 2008; Du Plessis et al., 2014), and (2) by designing an efficient, easy to implement importance sampling technique that incurs no computational overhead.
Our theoretical analysis shows that, as a function of the tuning parameter, the optimal representations for our new method place similar inputs in tight clusters, whilst spacing the clusters as far apart as possible. Empirically, our hard negative sampling strategy improves the downstream task performance for image, graph and text data, supporting that indeed, our negative examples are more informative.
Contributions. In summary, we make the following contributions:
We propose a simple distribution over hard negative pairs for contrastive representation learning, and derive a practical importance sampling strategy with zero computational overhead that takes into account the lack of true dissimilarity information;
We theoretically analyze the hard negatives objective and optimal representations, showing that they capture desirable generalization properties;
We empirically observe that the proposed sampling method improves the downstream task performance on image, graph and text data.
Before moving onto the problem formulation and our results, we summarize related work below.
Contrastive Representation Learning. Various frameworks for contrastive learning of visual representations have been proposed, including SimCLR (Chen et al., 2020a; b), which uses augmented views of other items in a minibatch as negative samples, and MoCo (He et al., 2020; Chen et al., 2020c), which uses a momentum updated memory bank of old negative representations to enable the use of very large batches of negative samples. Most contrastive methods are unsupervised, however there exist some that use label information (Sylvain et al., 2020; Khosla et al., 2020). Many works study the role of positive pairs, and, e.g., propose to apply large perturbations for images Chen et al. (2020a; c), or argue to minimize the mutual information within positive pairs, apart from relevant information for the ultimate prediction task (Tian et al., 2020). Beyond visual data, contrastive methods have been developed for sentence embeddings (Logeswaran & Lee, 2018), sequential data (Oord et al., 2018; Hénaff et al., 2020), graph (Sun et al., 2020; Hassani & Khasahmadi, 2020; Li et al., 2019) and node representation learning (Velickovic et al., 2019), and learning representations from raw images for off-policy control (Srinivas et al., 2020). The role of negative pairs hase been much less studied. Chuang et al. (2020) propose a method for “debiasing”, i.e., correcting for the fact that not all negative pairs may be true negatives. It does so by taking the viewpoint of Positive-Unlabeled learning, and exploits a decomposition of the true negative distribution. Kalantidis et al. (2020) consider applying Mixup (Zhang et al., 2018) to generate hard negatives in latent space, and Jin et al. (2018) exploit the specific temporal structure of video to generate negatives for object detection.
Negative Mining in Deep Metric Learning. As opposed to the contrastive representation learning literature, selection strategies for negative samples have been thoroughly studied in (deep) metric learning (Schroff et al., 2015; Song et al., 2016; Harwood et al., 2017; Wu et al., 2017; Ge, 2018; Suh et al., 2019). Most of these works observe that it is helpful to use negative samples that are difficult for the current embedding to discriminate. Schroff et al. (2015) qualify this, observing that some examples are simply too hard, and propose selecting “semi-hard” negative samples. The well known importance of negative samples in metric learning, where (partial) true dissimilarity information is available, raises the question of negative samples in contrastive learning, the subject of this paper.
Contrastive Learning Setup
Following the setup of Arora et al. (2019), we assume an underlying set of discrete latent classes that represent semantic content, so that similar pairs have the same latent class. Denoting the distribution over latent classes by for , we define the joint distribution whose marginal we refer to simply as , and assume . For simplicity, we assume is uniform, and let be the probability of another class. Since the class-prior is unknown in practice, it must either be treated as a hyperparameter, or estimated (Christoffel et al., 2016; Jain et al., 2016).
For each data point , the noise-contrastive estimation (NCE) objective (Gutmann & Hyvärinen, 2010) for learning the representation uses a positive example with the same label as , and negative examples with (supposedly) different labels, , sampled from :
The weighting parameter is introduced for the purpose of analysis. When is finite we take , yielding the usual form of the contrastive objective. The negative sample distribution is frequently chosen to be the marginal distribution , or, in practice, an empirical approximation of it (Tian et al., 2019; Chen et al., 2020a; c; He et al., 2020; Chen et al., 2020c; Oord et al., 2018; Hénaff et al., 2020). In this paper we ask: is there a better way to choose ?
Hard Negative Sampling
In this section we describe our approach for hard negative sampling. We begin by asking what makes a good negative sample? To answer this question we adopt the following two guiding principles:
should only sample “true negatives” whose labels differ from that of the anchor .
The most useful negative samples are ones that the embedding currently believes to be similar to the anchor.
In short, negative samples that have different label from the anchor, but that are embedded nearby are likely to be most useful and provide significant gradient information during training. In metric learning there is access to true negative pairs, automatically fulfilling the first principle.
In unsupervised contrastive learning there is no supervision, so upholding Principle 1 is impossible to do exactly. In this paper we propose a method that upholds Principle 1 approximately, and simultaneously combines this idea with the key additional conceptual ingredient of “hardness” (encapsulated in Principle 2). The level of “hardness” in our method can be smoothly adjusted, allowing the user to select the hardness that best trades-off between an improved learning signal from hard negatives, and the harm due to the correction of false negatives being only approximate. This important since the hardest points are those closest to the anchor, and are expected to have a high propensity to have the same label. Therefore the damage from the approximation not removing all false negatives becomes larger for harder samples, creating the trade-off. As a special case our our method, when the hardness level is tuned fully down, we obtain the method proposed in (Chuang et al., 2020) that only upholds Principle 1 (approximately) but not Principle 2. Finally, beyond Principles 1 and 2, we wish to design an efficient sampling method that does not add additional computational overhead during training.
Our first goal is to design a distribution on that is allowed to depend on the embedding and the anchor . From we sample a batch of negatives according to the principles noted above. We propose sampling negatives from the distribution defined as
for . Note that and both depend on , but we suppress the dependance from the notation. The exponential term in is an unnormalized von Mises–Fisher distribution with mean direction and “concentration parameter” (Mardia & Jupp, 2000). There are two key components to , corresponding to each principle: 1) conditioning on the event which guarantees that correspond to different latent classes (Principle ); 2) the concentration parameter term controls the degree by which up-weights points that have large inner product (similarity) to the anchor (Principle ). Since lies on the surface of a hypersphere of radius , we have so preferring points with large inner product is equivalent to preferring points with small squared Euclidean distance.
Although we have designed to have all of the desired components, it is not clear how to sample efficiently from it. To work towards a practical method, note that we can rewrite this distribution by adopting a PU-learning viewpoint (Elkan & Noto, 2008; Du Plessis et al., 2014; Chuang et al., 2020). That is, by conditioning on the event we can split as
where . Rearranging equation 2 yields a formula q_{\beta}^{-}(x^{-})=\bigl{(}q_{\beta}(x^{-})-\tau^{+}q^{+}_{\beta}(x^{-})\bigr{)}/\tau^{-} for the negative sampling distribution in terms of two distributions that are tractable since we have samples from and can approximate samples from using a set of semantics-preserving transformations, as is typical in contrastive learning methods.
It is possible to generate samples from and (approximately from) using rejection sampling. However, rejection sampling involves an algorithmic complication since the procedure for sampling batches must be modified. To avoid this, we instead take an importance sampling approach. To obtain this, first note that fixing the number and taking the limit in the objective (1) yields,
The original objective (1) can be viewed as a finite negative sample approximation to (note implicitly depends on ) . Inserting and using the rearrangement of equation (2) we obtain the following hardness-biased objective:
It is important to emphasize the simplicity of the implementation of our proposed approach. Since we propose to reweight the objective instead of modifying the sampling procedure, only two extra lines of code are needed to implement our approach, with no additional computational overhead. PyTorch-style pseudocode for the objective is given in Fig. 13 in Appendix D.
Analysis of Hard Negative Sampling
Intuitively, the concentration parameter in our proposed negative sample distribution controls the level of “hardness” of the negative samples. As discussed earlier, the debiasing method of Chuang et al. (2020) can be recovered as a special case: taking to obtain the distribution . This case amounts to correcting for the fact that some samples in a negative batch sampled from will have the same label as the anchor. But what interpretation does large admit? Specifically, what does the distribution converge to in the limit , if anything? We show that in the limit approximates an inner solution to the following zero-sum two player game.
where is the set of distributions with support that is disjoint from points with the same class as (without loss of generality we assume is non-empty). Since depends on and it can be thought of as a family of distributions. The formal statement is as follows.
To develop a better intuitive understanding of the worst case negative distribution objective , we note that the supremum can be characterized analytically. Indeed,
2 Optimal Embeddings on the Hypersphere for Worst-Case Negative Samples
What desirable properties does an optimal contrastive embedding (global minimizer of ) possess that make the representation generalizable? To study this question, we first analyze the distribution of an optimal embedding on the hypersphere when negatives are sampled from the adversarial worst-case distribution. We consider a different limiting viewpoint of objective (1) as the number of negative samples . Following the formulation of Wang & Isola (2020) we take in (1), and subtract . This changes neither the set of minimizers, nor the geometry of the loss surface. Taking the number of negative samples yields the limiting objective,
This understanding of global minimizers of can further developed into a better understanding of generalization on downstream tasks. The next result shows that representations that achieve small excess risk on the objective still separate clusters well in the sense that a simple 1-nearest neighbor classifier achieves low classification error.
Empirical Results
Next, we evaluate our hard negative sampling method empirically, and apply it as a modification to state-of-the-art contrastive methods on image, graph, and text data. For all experiments is treated as a hyper-parameter (see ablations in Fig. 2 for more understanding of how to pick ). Values for and must also be determined. We fix for all experiments, since taking would increase the number of inputs for the forward-backward pass. Lemma 11 in the appendix gives a theoretical justification for the choice of . Choosing the class-prior can be done in two ways: estimating it from data (Christoffel et al., 2016; Jain et al., 2016), or treating it as a hyper-parameter. The first option requires the possession of labeled data before contrastive training.
We begin by testing the hard sampling method on vision tasks using the STL10, CIFAR100 and CIFAR10 data. We use SimCLR (Chen et al., 2020a) as the baseline method, and all models are trained for epochs. The results in Fig. 2 show consistent improvement over SimCLR () and the particular case of our method with proposed in (Chuang et al., 2020) (called debiasing) on STL10 and CIFAR100. For negative examples per data point we observe absolute improvements of and over SimCLR on CIFAR100 and STL10 respectively, and absolute improvements over the best debiased baseline of and . On tinyImageNet (Tab. 1) we observe an absolute improvement of over SimCLR, while on CIFAR10 there is a slight improvement for smaller , which disappears at larger . See Appendix C.1 results using MoCo-v2 for large negative batch size, and Appendix D.1 for full setup details.
2 Graph Representations
Second, we consider hard negative sampling in the context of learning graph representations. We use the state-of-the-art InfoGraph method introduced by Sun et al. (2020) as the baseline, which is suitable for downstream graph-level classification. The objective is of a slightly different form from the NCE loss. Because of this we use a generalization of the formulation presented in Section 3 (See Appendix B for details). In doing so, we illustrate that it is easy to adapt our hard sampling method to other contrastive frameworks.
Fig. 3 shows the results of fine-tuning an SVM (Boser et al., 1992; Cortes & Vapnik, 1995) on the fixed, learned embedding for a range of different values of . Hard sampling does as well as InfoGraph in all cases, and better in 6 out of 8 cases. For ENZYMES and REDDIT, hard negative samples improve the accuracy by and , respectively, for DD and PTC by , and for IMDB-B and MUTAG by at least . Usually, multiple different choices of were competitive with the InfoGraph baseline: 17 out of the 24 values of tried (across all 8 datasets) achieve accuracy as high or better than InfoGraph ().
3 Sentence Representations
Third, we test hard negative sampling on learning representations of sentences using the quick-thoughts (QT) vectors framework introduced by Logeswaran & Lee (2018), which uses adjacent sentences (before/after) as positive samples. Embeddings are trained using the unlabeled BookCorpus dataset (Kiros et al., 2015), and evaluated following the protocol of Logeswaran & Lee (2018) on six downstream tasks. The results are reported in Table 2. Hard sampling outperforms or equals the QT baseline in 5 out of 6 cases, the debiased baseline (Chuang et al., 2020) in 4 out of 6, and both in 3 out of 6 cases. Setting led to numerical issues in optimization for hard sampling.
A Closer Look at Hard Sampling
By setting to large values, one can focus on only the hardest samples in a training batch. But is this desirable? Fig. 4 (left, middle) shows that for vision problems, taking larger does not necessarily lead to better representations. In contrast, when one uses true positive pairs during training (green curve, uses label information for positive but not negative pairs), the downstream performance monotonically increases with until convergence (Fig. 4 , middle). Interestingly, this is achieved without using label information for the negative pairs. This observation suggests an explanation for why bigger hurts performance in practice. Debiasing (conditioning on the event ) using the true corrects for sampling with the same label as . However, since in practice we approximate using a set of data transformations, we can only partially correct. This is harmful for large since this regime strongly prefers for which is close to , many of whom will have the same label as if not corrected for. We note also that by annealing (gradually decreasing to throughout training; see Appendix D.1 for details) it is possible to be more robust to the choice of initial , with marginal impact on downstream accuracy compared to the best fixed value of .
2 Does Avoiding False Negatives Improve Hard Sampling?
Our proposed hard negative sampling method conditions on the event in order to avoid false negatives (termed “debiasing” (Chuang et al., 2020)). But does this help? To test this, we train four embeddings: hard sampling with and without debiasing, and uniform sampling () with and without debiasing. The results in Fig. 4 (right) show that hard sampling with debiasing obtains the highest linear readout accuracy on STL10, only using hard sampling or only debiasing yields (in this case) similar accuracy. All improve over the SimCLR baseline.
Fig. 5 compares the histograms of cosine similarities of positive and negative pairs for the four learned representations. The representation trained with hard negatives and debiasing assigns much lower similarity score to a pair of negative samples than other methods. On the other hand, the SimCLR baseline assigns higher cosine similarity scores to pairs of positive samples. However, to discriminate positive and negative pairs, a key property is the amount of overlap of positive and negative histograms. Our hard sampling method achieves less overlap than SimCLR, by better trading off higher dissimilarity of negative pairs with less similarity of positive pairs. Similar tradeoffs are observed for the debiased objective, and hard sampling without debiasing.
3 How do Hard Negatives Affect Optimization?
Fig. 11 (in Appendix C due to space constraints) shows the performance on STL10 and CIFAR100 of SimCLR versus using hard negatives throughout training. We use weighted -nearest neighbors with as the classifier and evaluate each model once every five epochs. Hard sampling with leads to much faster training: on STL10 hard sampling takes only 60 epochs to reach the same performance as SimCLR does in 400 epochs. On CIFAR100 hard sampling takes only 125 epochs to reach the same performance as SimCLR does in 400 epochs. We speculate that the speedup is, in part, due to hard negatives providing non-negligible gradient information during training.
Conclusion
We argue for the value of hard negatives in unsupervised contrastive representation learning, and introduce a simple hard negative sampling method. Our work connects two major lines of work: contrastive learning, and negative mining in metric learning. Doing so requires overcoming an apparent roadblock: negative mining in metric learning uses pairwise similarity information as a core component, while contrastive learning is unsupervised. Our method enjoys several nice aspects: having desirable theoretical properties, a very simple implementation that requires modifying only a couple of lines of code, not changing anything about the data sampling pipeline, introducing zero extra computational overhead, and handling false negatives in a principled way.
References
Appendix A Analysis of Hard Sampling
We begin by proving Proposition 3. Recall that the proposition stated the following.
Consider the following essential supremum,
The second inequality holds since . We may rewrite
The difference between these two terms can be bounded as follows,
where for the second inequality we have used the fact that lies on the hypersphere of radius to restrict the domain of the logarithm to values greater than . Because of this the logarithm is Lipschitz with parameter . Using again the fact that lies on the hypersphere we know that and hence have the following inequality,
From now on we denote for brevity, and consider a fixed . From the definition of it is clear that . That is, since for some (non-constant) , it is absolutely continuous with respect to . So almost surely for , and we may therefore drop the absolute value signs from our expectation. Define the following event where is refers to a “good” event. Define its complement where is for “bad”. For a fixed and consider,
where is the partition function of . We may bound this expression by,
A.2 Optimal Embeddings on the Hypersphere for Worst-Case Negative Samples
In order to study properties of global optima of the contrastive objective using the adversarial worst case hard sampling distribution recall that we have the following limiting objective,
We may separate the logarithm of a quotient into the sum of two terms plus a constant,
Taking supremum to obtain we find that the second expression simplifies to,
Using Eqn. (9), this can be re-expressed as,
The forthcoming theorem exactly characterizes the global optima of
Any minimizer of has the property that almost surely. So, in order to prove the first claim, it suffices to show that there exist functions for which almost surely. This is because, at that point, we have shown that and intersect, and therefore any solution of must lie in this intersection.
To this end, suppose that but that with non-zero probability. We shall show that we can construct a new embedding such that almost surely, and . Due to Eqn. (10) this last condition is equivalent to showing,
Fix a , and let . The maximum is guaranteed to be attained, as we explain now. Indeed we know the maximum is attained at some point in the closure . Since is compact and connected, any point is such that since must belong to for some other . Such an cannot be a solution unless all points in also achieve , in which case we can simply take to be a point in the interior of .
Now, define for any such that and otherwise. Let us first aim to show that Eqn. (12) holds for this . Let us begin to expand the left hand side of Eqn. (12),
Since by construction the range of is a subset of the range of , we know that . Combining this with the fact that whenever we see,
Using these two lower bounds we may conclude that Eqn. (13) can be lower bounded by,
A.3 Downstream Generalization
To begin, using the definition of we know that for any ,
.
Using this fact we are able to get control over the tail probability as follows,
where this inequality holds for for any .
Since this holds for any ,
Elementary calculus shows that the minimum is attained at . Plugging this in yields the final bound,
Consider the same setting as introduced in Theorem 5. In particular define
and are random due to the randomness of . We can split up the following expectation by conditioning on the event and its complement,
Using and the notational re-writing of the objective introduced before Theorem 11, we observe the following fact, whose proof we give in a separate lemma after the conclusion of this proof.
Fact (see lemma 10):
From which we can say that for any ,
Consider the same setting as introduced in Theorem 5. Define also,
where the inequality follows since is a subset of the closure of . Taking expectations over ,
So since , we have found that
Subtracting and multiplying by yields the result.
Appendix B Graph Representation Learning
We describe in detail the hard sampling method for graphs whose results are reported in Section 5.2. Before getting that point, in the interests of completeness we cover some required background details on the InfoGraph method of Sun et al. (2020). For further information see the original paper (Sun et al., 2020).
which is typically taken to be a simple permutation invariant function such as the sum or mean. The InfoGraph method aims to maximize the mutual information between the graph level embedding and patch-level embeddings using the following objective,
where denotes the softplus function. The finial objective is the joint maximization over and ,
B.2 Hard Negative Sampling for Learning Graph Representations
In order to derive a simple modification of the NCE hard sampling technique that is appropriate for use with InfoGraph, we first provide a mildly generalized view of hard sampling. Recall that the NCE contrastive objective can be decomposed into two constituent pieces,
where is in fact a family of distributions over that is indexed by the possible values of the anchor . performs the role of “aligning” positive pairs (embedding near to one-another), while repels negative pairs. The hard sampling framework aims to solve,
View this view, we can easily adapt to the InfoGraph framework, taking
Appendix C Additional Experiments
The vision experiments in the main body of the paper are all based off the SimCLR framework (Chen et al., 2020a). They use a relatively small batch size (up to ). In order to test whether our hard negatives sampling method can help when the negative batch size is very large, we also run experiments using MoCo-v2 with standard negative memory bank size (He et al., 2020; Chen et al., 2020c). We adopt the official MoCo-v2 code https://github.com/facebookresearch/moco. Embeddings are trained for epochs, with batch size . Figure 6 summarizes the results. We find that hard negative sampling can still improve the generalization of embeddings trained on CIFAR10: MoCo-v2 attains linear readout accuracy of 88.08%, and MoCo-v2 with hard negatives (, ) attains 88.47%.
C.2 Ablations
To study the affect of varying the concentration parameter on the learned embeddings Figure 9 plots cosine similarity histograms of pairs of similar and dissimilar points. The results show that for moving from through to causes both the positive and negative similarities to gradually skew left. In terms of downstream classification, an important property is the relative difference in similarity between positive and negative pairs. In this case find the best balance (since it achieves the highest downstream accuracy). When is taken very large (), we see a change in conditions. Both positive and negative pairs are assigned higher similarities in general. Visually it seems that the positive and negative histograms for overlap a lot more than for smaller values, which helps explain why the linear readout accuracy is lower for .
Figure 12 gives real examples of hard vs. uniformly sampled negatives. Given an anchor (a monkey) and trained embedding (trained on STL10 using standard SimCLR for epochs), we sample a batch of images. The top row shows the ten negatives that have the largest inner product , while the bottom row is a random sample from from the same batch. Negatives with the largest inner product with the anchor correspond to the items in the batch are the most important terms in the objective since they are given the highest weighting by . Figure 12 shows that “real” hard negatives are conceptually similar to the idea as proposed in Figure 1: hard negatives are semantically similar to the anchor, possessing various similarities, including color (browns and greens), texture (fur), and objects (animals vs machinery).
Appendix D Experimental Details
Figure 13 shows PyTorch-style pseudocode for the standard objective, the debiased objective, and the hard sampling objective. The proposed hard-sample loss is very simple to implement, requiring only two extra lines of code compared to the standard objective.
We implement SimCLR in PyTorch. We use a ResNet-50 (He et al., 2016) as the backbone with embedding dimension (the representation used for linear readout), and projection head into the lower -dimensional space (the embedding used in the contrastive objective). We use the Adam optimizer (Kingma & Ba, 2015) with learning rate and weight decay . Code available at https://github.com/joshr17/HCL. Since we adopt the SimCLR framework, the number of negative samples . Since we always take the batch size to be a power of 2 () the negative batch sizes are respectively. Unless otherwise stated, all models are trained for epochs.
We also found the annealing in the opposite direction (“down”) achieved similar performance.
Bias-variance of empirical estimates in hard-negative objective:
Recall the final hard negative samples objective we derive is,
Consider the random variable where and . Then \text{Var}(X)\leq\mathcal{O}\big{(}\mathcal{L}_{\text{align}}(f)\big{)}.
where the first inequality follows since lies on the sphere of radius , the second inequality by Cauchy–Schwarz, the third again since lies on the sphere of radius , and the fourth since is absolutely continuous with respect to with bounded ratio.
D.2 Graph Representations
All datasets we benchmark on can be downloaded at www.graphlearning.io from the TUDataset repository of graph classification problems (Morris et al., 2020). Information on basic statistics of the datasets is included in Tables 3 and 4. For fair comparison to the original InfoGraph method, we adopt the official code, which can be found at https://github.com/fanyun-sun/InfoGraph. We modify only the gan_losses.py script, adding in our proposed hard sampling via reweighting. For simplicity we trained all models using the same set of hyperparameters: we used the GIN architecture (Xu et al., 2019) with layers and embedding dimension . Each model is trained for epochs with batch size using the Adam optimizer (Kingma & Ba, 2015). with learning rate , and weight decay of . Each embedding is evaluated using the average accuracy 10-fold cross-validation using an SVM as the classifier (in line with the approach taken by Morris et al. (2020)). Each experiment is repeated from scratch 10 times, and the distribution of results from these 10 runs is plotted in Figure 3.
Since the graph embeddings are not constrained to lie on a hypersphere, for a batch we clip all the inner products to live in the interval $$ while computing the reweighting, as illustrated in Figure 14. We found this to be important for stabilizing optimization.
D.3 Sentence Representations
We adopt the official quick-thoughts vectors experimental settings, which can be found at https://github.com/lajanugen/S2V. We keep all hyperparameters at the default values and change only the s2v-model.py script. Since the official BookCorpus dataset Kiros et al. (2015) is not available, we use an unofficial version obtained using the following repository: https://github.com/soskek/bookcorpus. Since the sentence embeddings are also not constrained to lie on a hypersphere, we use the same clipping trick as for the graph embeddings, illustrated in Figure 14.
After training on the BookCorpus dataset, we evaluate the embeddings on six different classification tasks: paraphrase identification (MSRP) (Dolan et al., 2004), question type classification (TREC) (Voorhees & Harman, 2002), opinion polarity (MPQA) (Wiebe et al., 2005), subjectivity classification (SUBJ) (Pang & Lee, 2004), product reviews (CR) (Hu & Liu, 2004), and sentiment of movie reviews (MR) (Pang & Lee, 2005).
Kalantidis et al. (2020) also consider ways to sample negatives, and propose a mixing strategy for hard negatives, called MoCHi. The main points of difference are: 1) MoCHi considers the benefit of hard negatives, but does not consider the possibility of false negatives (Principle 1), which we found to be valuable. 2) MoCHi introduces three extra hyperparameters, while our method introduces only two (, ). If we discard Principle 1 (i.e. ) then only requires tuning. 3) our method introduces zero computational overhead by utilizing within-batch reweighting, whereas MoCHi involves a small amount of extra computation.