BERT2Code: Can Pretrained Language Models be Leveraged for Code Search?

Abdullah Al Ishtiaq, Masum Hasan, Md. Mahim Anjum Haque, Kazi Sajeed Mehrab, Tanveer Muttaqueen, Tahmid Hasan, Anindya Iqbal, Rifat ShahriyararXiv 2021

Abstract

Millions of repetitive code snippets are submitted to code repositories every day. To search from these large codebases using simple natural language queries would allow programmers to ideate, prototype, and develop easier and faster. Although the existing methods have shown good performance in searching codes when the natural language description contains keywords from the code, they are still far behind in searching codes based on the semantic meaning of the natural language query and semantic structure of the code. In recent years, both natural language and programming language research communities have created techniques to embed them in vector spaces. In this work, we leverage the efficacy of these embedding models using a simple, lightweight 2-layer neural network in the task of semantic code search. We show that our model learns the inherent relationship between the embedding spaces and further probes into the scope of improvement by empirically analyzing the embedding methods. In this analysis, we show that the quality of the code embedding model is the bottleneck for our model's performance, and discuss future directions of study in this area.

1. Introduction

Finding the right code snippet in a massive repository is a daily struggle for developers. Traditional search engines often rely on keyword matching—if your query contains the word "sort" and the code has a function named sort(), you're in luck. However, if the query describes the intent (e.g., "organize a list by value") without using specific keywords, traditional methods often fail.

This is the challenge of Semantic Code Search: understanding the underlying meaning of both the natural language (NL) query and the source code. While high-quality embedding models exist for both text and code, they live in different "vector spaces." This paper investigates whether a simple transformation can bridge these two worlds to enable effective searching.

2. Methodology

The authors propose BERT2Code, a framework that treats code search as a translation problem between vector spaces. The process involves three main components:

  1. Embedding Generation:
    • NL Side: Sentence-BERT (SBERT) is used to transform natural language queries into 1024-dimensional vectors, capturing sentence-level semantics.
  2. Code Side: The study experiments with two models: Code2Vec (representing code via Abstract Syntax Tree paths) and CodeBERT (a transformer-based model).
  3. The Transformation Bridge: Instead of a massive end-to-end model, a lightweight 2-layer feed-forward neural network is employed. This network is trained to take an SBERT vector as input and predict the corresponding code vector.
  4. Training and Retrieval: The model uses a max-margin approach with Euclidean distance to minimize the gap between predicted and actual code vectors. For retrieval, the FAISS library enables fast nearest-neighbor searches in the code vector space.
BERT2Code Architecture: Mapping natural language embeddings to code embeddings using a simple neural network.

3. Experimental Setup

The model was evaluated using two primary datasets:

  • CodeSearchNet Challenge: Specifically the Java subset, containing approximately 543,000 code-description pairs.
  • DeepCom: A dataset of over 505,000 pairs used for manual analysis of embedding quality to identify performance bottlenecks.

4. Results

Performance was measured using Mean Reciprocal Rank (MRR), indicating the average rank of the correct result. BERT2Code significantly outperformed the random baseline, demonstrating that the mapping network successfully learns the relationship between the two embedding spaces.

Method MRR (%)
BERT2Code (with Code2Vec) 15.478%
BERT2Code (with CodeBERT) 9.986%
Random Model 0.74%

Interestingly, Code2Vec embeddings yielded better search results than the more modern CodeBERT architecture in this specific task.

5. Discussion: The Embedding Bottleneck

A key insight of this work is identifying where the search process fails. Through a manual study, the authors had humans rate the similarity of query pairs and code pairs, then compared these ratings to vector distances.

Correlation analysis showing that code embeddings correlate significantly less with human judgment than natural language embeddings.

As shown in the table above, NL embeddings (SBERT) correlated strongly with human judgment ($r = -0.772$). However, code embeddings (Code2Vec) showed a much weaker correlation ($r = -0.444$). This suggests that while we can effectively represent the "meaning" of English sentences mathematically, current models for representing the "meaning" of code are still lacking. The bottleneck for better search is not the search algorithm or the mapping network, but the underlying quality of code embeddings.

6. Conclusion

BERT2Code demonstrates that a simple neural bridge can connect disparate language and code embedding spaces for semantic search. However, the study highlights that current code embeddings often over-rely on syntax rather than deep logic and fail to generalize across different tasks. Future research should focus on building more generalizable code embedding models to achieve human-like performance in semantic retrieval.

Summary updated

BibTeX
@misc{ishtiaq2021bert,
  author = {Abdullah Al Ishtiaq and Masum Hasan and Md. Mahim Anjum Haque and Kazi Sajeed Mehrab and Tanveer Muttaqueen and Tahmid Hasan and Anindya Iqbal and Rifat Shahriyar},
  title = {{BERT2Code: Can Pretrained Language Models be Leveraged for Code Search?}},
  year = {2021},
  eprint = {2104.08017},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2104.08017},
}
Figure