NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

An Exploratory Study on Code Attention in BERT

Rishab Sharma, Fuxiang Chen, Fatemeh H. Fard, David Lo · DOI

Abstract

Pre-trained Language Models (PLMs) like BERT have become foundational tools in software engineering for tasks such as bug detection and code summarization. However, these models are often applied using Natural Language Processing (NLP) conventions that may not align with the structural realities of source code. This study investigates BERT's attention mechanisms when trained on Java, revealing that the standard [CLS] token—a staple of NLP—is significantly less effective than identifier-based representations. By shifting focus to identifiers and separators, the researchers demonstrate performance gains in code clone detection of up to 605% in the model's lower layers.

Introduction

The software engineering community has rapidly adopted models like BERT and RoBERTa, largely under the assumption that they process code similarly to natural language. In standard NLP, the [CLS] token is treated as the "master summary" of a sequence. However, code possesses a rigid, hierarchical, and syntactic structure that distinguishes it from English. This paper explores whether BERT actually attends to the most relevant features of code or if current "best practices" are hindering model performance.

Methodology

The authors conducted an exploratory study using a BERT-Base model pre-trained from scratch on the Java subset of the CodeSearchNet benchmark (approximately 165k records). The model utilized standard Masked Language Modeling (MLM) and Next Sentence Prediction (NSP) objectives to ensure a fair comparison with NLP-centric studies.

The investigation was divided into three phases:

  1. Attention Mapping: Analyzing attention scores across 12 layers and 144 heads to identify which tokens (e.g., [CLS], identifiers, operators) the model prioritizes.
  2. Syntactic Probing: Testing the model's ability to predict the syntactic type of masked tokens to determine its grasp of Java grammar.
  3. Downstream Evaluation: Comparing the performance of the standard [CLS] token against a weighted average of identifier embeddings for a code clone detection task using the Big-Clone-Bench dataset.

Key Insights

The Devaluation of the [CLS] Token

In natural language processing, the [CLS] token typically receives high attention scores as it aggregates sentence context. In code, however, BERT's attention on [CLS] drops to between 0 and 0.1, compared to scores as high as 0.6 in NLP tasks. This suggests that the standard method of using [CLS] as a global code representation is suboptimal.

The Primacy of Identifiers and Separators

BERT naturally gravitates toward identifiers (variable and function names) and separators (brackets and semicolons). These tokens serve as the primary anchors for the model's understanding of logic. Interestingly, the model's attention is notably "nearsighted," with approximately 30% of attention focused on immediate left or right neighbors, indicating a reliance on local context over long-range dependencies.

Implicit Syntactic Awareness

Despite no explicit training on Java syntax, BERT becomes highly proficient at identifying syntactic categories. The model achieved an F1-score of over 90% in predicting whether a token was an identifier, modifier, or operator, proving that MLM is sufficient for the model to learn the underlying grammar of a programming language.

Results and Impact

The most significant finding emerged from replacing the standard [CLS] embedding with identifier-based embeddings for Code Clone Detection:

  • Lower Layer Breakthroughs: In the first layer, using identifier embeddings improved the F1-score by 605% over the [CLS] baseline.
  • Upper Layer Consistency: Even in the final layers, identifier-based representations provided a 4% performance boost.
  • Model Generalizability: When this logic was applied to the state-of-the-art CodeBERT model, the F1-score for clone detection improved by 21–24%.
  • Training Success: The scratch-trained model achieved 87.44% accuracy on MLM, confirming it successfully learned the nuances of Java.

Conclusion and Future Work

This study demonstrates that identifiers are the most critical components for BERT's understanding of source code. The findings suggest that the software engineering community should move away from NLP-centric defaults like the [CLS] token.

Future research may focus on:

  • Language Diversity: Expanding the study beyond Java to non-curly-brace languages like Python or Haskell.
  • Task Variety: Evaluating identifier-based embeddings for code summarization and vulnerability detection.
  • Efficiency: Developing smaller, specialized models that prioritize key tokens (identifiers) to reduce computational overhead without sacrificing accuracy.

Summary updated

BibTeX
@inproceedings{sharma2022exploratory,
  author = {Rishab Sharma and Fuxiang Chen and Fatemeh H. Fard and David Lo},
  title = {{An Exploratory Study on Code Attention in BERT}},
  booktitle = {ICPC},
  year = {2022},
  url = {https://openreview.net/forum?id=pJH5tOLE0F},
}
Figure