Rethinking Negative Pairs in Code Search

Haochen Li, Xin Zhou, Anh Tuan Luu, Chunyan Miao

Abstract

Contrastive learning has become the cornerstone of modern code search, yet standard implementations often rely on the InfoNCE loss, which treats all negative samples as equally irrelevant. This approach ignores the semantic nuances of code, where some "negative" samples may be functional duplicates or closely related to the query. This paper introduces Soft-InfoNCE, a modified loss function that weights negative pairs based on their estimated similarity to the query. By incorporating importance sampling and theoretical grounding in KL-divergence regularization, Soft-InfoNCE achieves a consistent 1-2% performance improvement across state-of-the-art models and multiple programming languages.

Introduction

Code search—the task of retrieving relevant code snippets based on natural language queries—is essential for developer productivity. Current state-of-the-art models utilize contrastive learning to map queries and code into a shared embedding space. The objective is to minimize the distance between a query and its corresponding code (positive pair) while maximizing the distance from all other code snippets in the batch (negative pairs).

While the standard InfoNCE loss is effective, it suffers from a critical oversight: it assumes a binary relationship where every non-matching snippet is equally "wrong." This paper argues that this uniform treatment of negative samples limits the model's ability to learn fine-grained semantic relationships and handle the inherent noise in large-scale codebases.

The Problem: Uniform Pushing and False Negatives

The authors identify two primary flaws in the standard InfoNCE approach:

  1. False Negatives: Large-scale datasets like CodeSearchNet often contain functional duplicates. A snippet labeled as a "negative" in a training batch might actually perform the exact same task as the positive sample. Forcing the model to push these samples away creates contradictory signals that hinder convergence.
  2. Uniform Pushing: In standard contrastive learning, a snippet for "bubble sort" is pushed away from a "quick sort" query with the same intensity as a snippet for "file system I/O." Because "bubble sort" is semantically closer to the query than "file I/O," treating them identically prevents the model from learning the structural and functional hierarchies of code.

Proposed Method: Soft-InfoNCE

To address these issues, the authors propose Soft-InfoNCE. This method introduces a weight term ($w_{ij}$) into the denominator of the loss function, allowing the model to adjust the "pushing" force for each negative sample based on its relevance to the query.

Weight Estimation Strategies

Since human-labeled relevance for every negative pair is unavailable, the authors explored three automated methods to estimate $w_{ij}$:

  • BM25: A traditional information retrieval metric that weights samples based on keyword overlap.
  • SimCSE: An unsupervised sentence similarity model applied to the natural language descriptions of the code.
  • Trained Model: Utilizing a model previously trained with standard InfoNCE to provide an initial estimate of semantic similarity.

Theoretical Justification

Beyond empirical intuition, the paper provides a rigorous mathematical framework for Soft-InfoNCE. The authors demonstrate that this weighted loss acts as a KL-divergence regularizer, encouraging the model's predicted similarity distribution to align with a prior similarity distribution. Furthermore, they show that by using importance sampling, Soft-InfoNCE provides a more precise, unbiased estimate of Mutual Information between the query and the code.

Experimental Evaluation

The researchers evaluated Soft-InfoNCE using the CodeSearchNet (CSN) benchmark, covering six programming languages: Python, Java, JavaScript, PHP, Ruby, and Go. They integrated the loss function into three leading transformer-based architectures:

  • CodeBERT
  • GraphCodeBERT
  • UniXCoder

Key Results

  • Performance Gains: Soft-InfoNCE delivered a consistent improvement of 1% to 2% in Mean Reciprocal Rank (MRR) across all models and languages compared to the vanilla InfoNCE baseline.
  • Robustness: While the "Trained Model" approach often yielded the highest accuracy for specific architectures, the SimCSE-based weighting proved to be the most robust and generalizable across different models.
  • Efficiency: The computational overhead for calculating weights was found to be negligible. For instance, training time per batch only increased from 0.75s to 0.81s when using SimCSE weighting.
  • Comparison with Alternatives: Soft-InfoNCE outperformed other common loss variants, such as Binary Cross Entropy (BCE) and standard Weighted InfoNCE, validating the authors' theoretical approach to importance sampling.

Discussion and Future Work

The study highlights that the "anisotropy" problem—where transformer embeddings tend to cluster in a narrow cone—can be mitigated by more precise management of negative sample distributions. By acknowledging that not all negatives are equal, Soft-InfoNCE allows models to develop a more nuanced understanding of code semantics.

However, the authors note that weight estimation is still an evolving area. Future research may focus on more sophisticated, real-time estimation methods. Additionally, the reliance on binary benchmarks (where a result is either "correct" or "incorrect") suggests a need for new evaluation datasets that incorporate graded relevance labels to better measure the refined ranking capabilities of models trained with Soft-InfoNCE.

Conclusion

Soft-InfoNCE represents a significant step forward in contrastive learning for code search. By replacing the "uniform pushing" of negative samples with a weighted, importance-sampling approach, the method resolves the issues of false negatives and semantic blurring. The result is a more robust, theoretically grounded, and higher-performing retrieval system that can be easily integrated into existing model architectures.

Summary updated

BibTeX
@inproceedings{li2023rethinking,
  author = {Haochen Li and Xin Zhou and Anh Tuan Luu and Chunyan Miao},
  title = {{Rethinking Negative Pairs in Code Search}},
  booktitle = {Conference on Empirical Methods in Natural Language Processing},
  year = {2023},
  doi = {10.18653/v1/2023.emnlp-main.786},
}
Figure