Towards Compositional Generalization in Code Search

Hojae Han, Seung-won Hwang, Shuai Lu, Nan Duan, Seungtaek Choi

Abstract

Current code search models often struggle when they encounter familiar programming structures in unfamiliar combinations—a challenge known as compositional generalization. This paper introduces CTBERT (Code Template BERT), which learns to represent code by automatically mining and training on "templates"—frequently occurring structural building blocks derived from Abstract Syntax Trees (ASTs). By treating code as a composition of these structural idioms, CTBERT significantly outperforms existing models on adversarial benchmarks that test for true structural understanding.

The Challenge: Compositional Generalization

In code search, the goal is to find the most relevant code snippet for a given natural language query. While state-of-the-art models like CodeBERT excel at pattern matching, they often fail when faced with novel compositions of known elements. The authors categorize these failures into two types:

  1. Lexical Generalization: The model fails when variable names change, even if the underlying logic is identical.
  2. Structural Generalization: The model fails when familiar structural elements (e.g., loops, conditionals, try-except blocks) are combined in ways not seen during training.
Lexical vs. Structural Generalization in code search.

Existing models typically treat code as flat text or rely on Data Flow Graphs (DFG). While DFGs track variable dependencies, they often overlook the local structural context that defines how code logic is composed.

Methods: CTBERT and Template Mining

The authors propose CTBERT, which incorporates structural idioms directly into the model's representation. The approach follows three main steps:

1. Template Mining

Instead of manual definition, templates are automatically mined from ASTs. By calculating the conditional probability of child nodes given their parents, the system identifies frequently co-occurring subtrees. These "structural idioms" (e.g., a standard if-else or a specific try-except pattern) are then filtered by size and frequency.

2. Injecting Structure via Masked Attention

CTBERT augments the standard BERT input with a sequence of these mined templates. To ensure the model learns the relationship between tokens and their structural roles, Masked Attention is used: a code token can only attend to the template it belongs to, preventing the model from relying on global shortcuts.

Comparison of code representations: Sequence, AST, DFG, and the proposed Template.

3. Template Alignment Pre-training

A new loss function, Template Alignment ($\mathcal{L}_T$), is introduced. The model must predict which template a specific code token belongs to, forcing it to internalize the structural boundaries of the code.

Evaluation and Results

The model was evaluated on the CodeSearchNet (CSN) dataset and AdvTest, a specialized benchmark where variable and function names are normalized to test true logical understanding.

  • Superior Generalization: On AdvTest, CTBERT achieved an MRR (Mean Reciprocal Rank) of 0.3997, outperforming GraphCodeBERT (0.352) and SynCoBERT (0.381).
  • Complementary Representations: CTBERT's performance improved further when combined with DFG objectives, suggesting that structural templates and data flow provide orthogonal, beneficial information.
  • Robustness Gains: CTBERT showed a +1.72% gain in lexical generalization and a +2.00% gain in structural generalization over baselines.

Key Insights

  • AST Subtrees vs. Text: Mining AST subtrees is more effective than using frequent lines of code because it captures syntax rather than surface-level text.
  • Local Logic: While DFGs are good for long-range dependencies, templates act as "connective tissue" that provides essential local logic context.
  • Alignment is Crucial: The specific alignment task—predicting token-to-template membership—is the primary driver for performance gains on adversarial tests.

Limitations and Future Work

Despite its success, CTBERT has a high pre-training cost (requiring roughly 14 hours on 8 NVIDIA Tesla V100 GPUs). The template mining process also relies on heuristic hyperparameters. Future work could explore end-to-end learning of these structural building blocks and extending the approach to languages beyond Python.

Summary updated

BibTeX
@inproceedings{han2022towards,
  author = {Hojae Han and Seung-won Hwang and Shuai Lu and Nan Duan and Seungtaek Choi},
  title = {{Towards Compositional Generalization in Code Search}},
  booktitle = {Conference on Empirical Methods in Natural Language Processing},
  year = {2022},
  doi = {10.18653/v1/2022.emnlp-main.737},
}
Figure