Batch-Softmax Contrastive Loss for Pairwise Sentence Scoring Tasks (2022)

Abstract: The use of contrastive loss for representation learning has become prominent in computer vision, and it is now getting attention in Natural Language Processing (NLP).Here, we explore the idea of using a batch-softmax contrastive loss when fine-tuning large-scale pre-trained transformer models to learn better task-specific sentence embeddings for pairwise sentence scoring tasks. We introduce and study a number of variations in the calculation of the loss as well as in the overall training procedure; in particular, we find that a special data shuffling can be quite important. Our experimental results show sizable improvements on a number of datasets and pairwise sentence scoring tasks including classification, ranking, and regression. Finally, we offer detailed analysis and discussion, which should be useful for researchers aiming to explore the utility of contrastive loss in NLP.

## introduction recent years have seen a revolution in natural language processing (nlp) thanks to the advances in machine learning. a lot of attention has been paid to architectures, especially for deep learning, as well as to loss functions. notably, loss functions based on similar ideas were proposed in unrelated papers in different machine learning fields under different names. this can cause difficulties when solving new problems or when designing new experiments based on previous results. to a greater extent, this applies to "universal" loss functions, which can be applied in different machine learning areas and tasks such as computer vision (cv), recommendation systems, and nlp. an example of such loss function is the batch-softmax contrastive (bsc) loss, which we will discuss below. for many nlp tasks, it is important to obtain representations of sentences for semantic matching problems, since they can be used for further analysis, e.g., for finding the best answer to a question. sentence bert is a recent popular approach for this @xcite : it can be trained with different loss functions, and we show that the choice of a loss function is important. moreover, we show that it will not be optimal to take the "standard" batch-softmax contrastive loss, which is used for training simcse @xcite , a recent alternative to sentence bert, and we suggest ways to improve its efficiency. our contributions can be summarized as follows: the contrastive loss was proposed by @xcite as metric learning that contrasts euclidean distances between embeddings of samples from one class and between samples from different classes. @xcite suggested the triplet loss, which is based on a similar idea, but uses triplets (anchor, positive, negative), and aims for the difference between the distances for (anchor, positive) and for (anchor, negative) to be larger than a margin. n -pair loss was presented as a generalization of the contrastive and the triplet losses as a way to solve the problem of extensive construction of hard negative pairs and triplets @xcite . a batch of n pairs of examples from n different classes is sampled, and the first element in each pair is considered to be an anchor. thus, for each anchor, there are one positive and n ´1 negative pairs. the loss contrasts the distances simultaneously using the softmax function over dot-product similarities. the approach was used successfully in cv tasks. the same method of multiple negative ranking for training dot-product scoring models was applied to ranking natural language responses to emails @xcite , where the loss uses labeled pairs. a similar idea, called negative sharing, was used to reduce the computational cost when training recommender systems @xcite . @xcite presented an approach with n -pairs like logic, as a non-parametric softmax classifier, replacing the weights in the softmax with embeddings of samples from such classes. it was also proposed to use l2 normalization and temperature. @xcite used multiple negative ranking to train general sentence representations on data from reddit and snli. @xcite presented a quick-thoughts approach to learn sentence embeddings, which constructs batches of contiguous sets of sentences, and for each sentence, contrasts the next sentence in the text and all other candidates. a lot of subsequent work focused on maximizing mutual information (mi). @xcite presented a loss function based on noise-contrastive estimation, called infonce. it models the "similarity" function that estimates the mi between the target (future) and the context (present) signals, and maximizes the mi between temporally nearby signals. if this "similarity" function expresses the dot-product between embeddings, the infonce loss is equivalent to the n -pair loss up to some constants. it was also shown that infonce is equivalent to the mutual information neural estimator (mine) up to a constant @xcite , which maximizes a lower bound on mi. deep infomax (dim) @xcite improves mine, and can be modified to incorporate some autoregression as infonce. however, the effectiveness of loss functions such as dim and infonce might be primarily connected to mi, rather than to deep metric learning @xcite . the idea gained a lot of popularity in the field of computer vision with the advent of simclr (a simple framework for contrastive learning of visual representations), which introduced nt-xent (normalized temperature-scaled cross-entropy loss) @xcite . it uses self-supervised learning, where augmentations of the same image are used as positive examples and augmentations of different images are used as negative examples. thus, the task is as follows: for each example in a batch, find its paired positive augmentation. here, the n -pairs loss is modified with a temperature parameter and with an l2 normalization of embeddings to the unit hypersphere. the loss was further extended for supervised learning as supcon loss @xcite , which aggregates all positive examples (from the same class) in the softmax numerator. subsequently, similar kinds of loss functions were also introduced to the field of natural language processing (nlp). @xcite combined the supcon loss with the cross-entropy loss and obtained state-of-the-art results for several downstream nlp tasks using roberta. @xcite , fang and xie (2020) and @xcite used nt-xent to pre-train transformers, considering spans sampled from the same document, sentences augmented with back-translation as positive examples, and sequences corrupted with mlm. @xcite proposed to use nt-xent in a self-supervised setting to learn noise-invariant sequence representations, where sentences augmented with masking were considered as positive examples. finally, @xcite introduced the simclr loss to nlp under the name simcse (simple contrastive learning of sentence embeddings), where sentences processed by a neural network with dropout served as augmentations of the original sentences. here, we explore various ways to use a similar loss function for pairwise sentence scoring tasks. while the above-described loss functions have different names, they are all based on similar ideas. below, we will use the name batch-softmax contrastive (bsc) loss, which we believe reflects the main idea best. in our experiments below, we will use the "modern" variant of the loss: with temperature, normalization, and symmetrization components (described in more detail in section 3.1). these components were not used for nlp in combination before. , question-answer, for each q i , the bsc loss contrasts the scores between q i and a i (positive examples) vs. between q i and a j for all j ‰ i (negative examples) using softmax. here ‚ denotes the dot-product. we further introduce a number of novel and important modifications in the definition of the loss and in the training procedure, which make it more efficient, and we show that using the resulting loss yields better task-specific sentence embeddings for pairwise sentence scoring tasks. ## datasets nlp tasks that compare pairs of sentences can be roughly divided into three general categories: regression (predicting a similarity score), classification (e.g., similar vs. dissimilar), and ranking (search for the best matches). they differ only by the quality assessment functions, and thus they all can benefit from the above losses. note that it is important to calculate the sentence representations for ranking tasks in advance, as when independently calculating the embeddings of the individual elements in the pairs, the inference time of the model becomes linear instead of quadratic. therefore, we use sentence-bert (sbert), which is trained as a siamese bert model, and offers a way to obtain state-of-the-art sentence embeddings, which have been proven useful for a number of tasks @xcite . at inference time, we first use sbert to obtain independently a representation for the individual sentences, and then we calculate the cosine similarities between the corresponding embeddings as we construct pairs as part of the process of ranking. we use a variety of public english datasets and tasks for the evaluation. in particular, we have four ranking tasks (ranking answers to non-factoid questions, ranking questions by their similarity with respect to other questions, ranking comments by their similarity to a given question, ranking factchecked claims by their relevance with respect to an input claim), two binary classification tasks (paraphrases identification, and duplicate question identification), and one regression task (semantic sentence similarity). antique the dataset contains 2,626 non-factoid questions with answer choices @xcite , asked by users on yahoo! answers. there are a total of 34,011 question-answer pairs: 27,422 for training and 6,589 for validation. each answer is annotated with a relevance score with respect to the question on a scale from 1 to 4 (where 4 denotes the highest relevance), and the task is to rank the answers by their relevance. to model relevance as a cosine similarity, we normalize the scores to the r0, 1s interval. we use mean reciprocal rank (mrr) as the main evaluation measure. cqa-a this dataset was used in semeval-2017 task 3 on community question answering subtask a @xcite . the goal is to rank the first ten answers in a question thread on qatar living, so that good answers are ranked higher than bad ones. we used the clean part of the dataset, which consists of 14,110 and 2,440 labeled question-comments pairs for training and development, respectively. the evaluation measure is mean average precision (map). this dataset contains important metadata, e.g., the date and time of the comment, and sorting the comments by time yields a strong baseline; yet, we only use the text. to train the model with the triplet loss, we group the pairs by the first element (anchor). cqa-b this dataset was developed for semeval-2017 task 3, subtask b @xcite , whose goal was to rank ten potentially related questions by their similarity with respect to an input question. these questions were retrieved from the qatar living forum using google and the input question as a query. we use the clean part of the dataset, which consists of 19,990 training and 5,500 development labeled question-question pairs. the main evaluation measure here is map. there is additional information, e.g., the rank of the retrieved question in the google search results, which we do not use. ## experimental setup below, we describe our baselines and hyperparameter settings. ## results below, we describe the evaluation results. antique the results are shown in cqa-a the results for cqa subtask a are shown in cqa-b the evaluation results for cqa-b are shown in pfcc-s mrpc qqp the results for qqp are shown in stsb ## discussion we highlight the following observations: selecting a loss function is important. for instance, if the model optimizes pearson correlation, it achieves a score of 85.57 on the sts task. thus, it outperforms almost all considered approaches. moreover, the combination of such a loss with bsc allows the model to achieve an f1 score of 89.88 in the mrpc task (a classification task). finally, we would like to draw a parallel between our work and augmented sbert @xcite . when using the bsc loss, some negatives are implicitly added to the dataset. augmented sbert adds new examples too and retrieves them using bm25 or semantic search samplings. these methods are comparable to our fast shuffling by words (n-grams) and to example-based shuffling, respectively. moreover, the task-specific model is used to encode the data in both cases. however, we do not need to label such pairs with another model (cross-encoder) due to the bsc loss definition. ## conclusion and future work we explored the idea of using a batch-softmax contrastive loss for fine-tuning large-scale pre-trained transformers to learn better task-specific sentence embeddings for pairwise sentence scoring tasks. we introduced and studied a number of variations in the calculation of the loss as well as in the overall training procedure. our experimental results have shown sizable improvements on a number of datasets and pairwise sentence scoring tasks including ranking, classification, and regression. in future work, we want to explore new variations of the loss, and to gain better understanding of when to use which variation. we further plan experiments with a larger set of nlp tasks.