Code Prediction by Feeding Trees to Transformers

Seohyun Kim, Jinman Zhao, Yuchi Tian, Satish Chandra

TL;DR

This paper demonstrates that code autocomplete systems perform significantly better when Transformers are made "syntax-aware" by feeding them Abstract Syntax Trees (ASTs) instead of just raw text. By linearizing code structure through tree traversals and paths, the authors' flagship model, TravTrans, outperforms previous state-of-the-art systems by 14% to 18% in prediction accuracy.

What Problem Does This Paper Address?

Modern software development relies heavily on autocomplete to save time and discover APIs. However, for autocomplete to be truly useful, the correct suggestion needs to be at the very top of the list.

The challenge lies in the nature of code. Unlike natural language, code has a rigid, hierarchical structure defined by a grammar (the Abstract Syntax Tree or AST). Traditional models often treat code as a simple sequence of words (like a sentence), which ignores these deep structural relationships. While some specialized models have tried to incorporate ASTs using Recurrent Neural Networks (RNNs) or decision trees, they often struggle with long-range dependencies or the sheer complexity of large codebases.

Methods

The authors build upon the Transformer architecture (specifically a GPT-2 style model), which is renowned for handling long-range dependencies through its self-attention mechanism. They propose and compare several ways to "feed" the tree structure into the Transformer:

  1. SeqTrans (Baseline): Treats code as a linear sequence of source tokens, similar to how GPT models process natural language.
  2. PathTrans: For every leaf node (the actual values in code), it provides the "root-path"—the sequence of nodes from that leaf up to the root of the tree. These paths are compressed using an LSTM and added to the leaf's embedding.
  3. TravTrans (Flagship): Instead of raw source code, it feeds the Transformer a sequence of AST nodes in Depth-First Search (DFS) order. This forces the model to see the "type" of a node (e.g., AttributeLoad) immediately before its "value" (e.g., atoi).
  4. TravTrans+: An experimental version that modifies the Transformer's attention mechanism with a relational matrix $R$, explicitly telling the model how many "up" and "down" moves in the tree separate any two nodes.

Datasets

The models were trained and evaluated on two primary datasets:

  • py150: A standard benchmark consisting of 150,000 Python 2 files from GitHub, parsed into ASTs.
  • Internal Facebook Corpus: 5,000 Python files from a private repository to test how well the models generalize to different coding styles and disjoint projects.

Key Insights and Ideas

  • Structure is a Force Multiplier: Simply moving from an RNN to a Transformer (SeqRNN to SeqTrans) provided a massive boost, but adding tree structure (TravTrans) provided the winning edge.
  • The "Parent" is Key: Using saliency maps (a technique to see what the model is "looking at"), the authors found that the model focuses heavily on the parent node in the AST. Knowing that the next node must be an "Attribute" drastically narrows down the search space compared to just looking at the previous word.
  • DFS Linearization Works: Transformers are naturally built for sequences. By linearizing the tree via DFS, the authors found a "sweet spot" where the model can use its standard machinery to learn hierarchical rules.
  • Generalization: The models maintained their performance lead even on the internal Facebook dataset, suggesting they are learning fundamental patterns of the Python language rather than just memorizing GitHub-specific quirks.

Key Results

The primary metric used was Mean Reciprocal Rank (MRR), which measures how close the correct suggestion is to the top of the list.

  • Superior Accuracy: TravTrans achieved an MRR of 58.0% on the py150 dataset, significantly higher than previous SOTA models like Deep3 (43.9%) and Code2Seq (43.7%).
  • RNN vs. Transformer: The Transformer-based SeqTrans (50.1% MRR) easily beat the RNN-based SeqRNN (36.6% MRR), proving the Transformer's architecture is inherently better suited for code.
  • Efficiency: Despite the added complexity of tree processing, the inference time for TravTrans remained competitive (50 mins to evaluate the entire test set), making it viable for real-world IDE integration.

Limitations and Future Work

  • Out-of-Vocabulary (OOV) Issues: The model struggles with "rare" tokens (like specific variable names) that weren't in the training set. Between 21% and 35% of prediction locations contained OOV tokens, which the current model cannot predict correctly.
  • Python-Only: The study focused exclusively on Python. While the authors expect the trends to hold for other languages like JavaScript, it hasn't been proven here.
  • Single Token Prediction: The model currently predicts one token at a time. Future work could explore "multi-token" prediction to autocomplete entire expressions or blocks of code.
  • Traversal Order: The authors used pre-order traversal; they suggest that "in-order" traversal might be more effective for top-down code generation in the future.

Summary updated

BibTeX
@inproceedings{kim2021code,
  author = {Seohyun Kim and Jinman Zhao and Yuchi Tian and Satish Chandra},
  title = {{Code Prediction by Feeding Trees to Transformers}},
  booktitle = {ICSE},
  year = {2021},
  url = {https://openreview.net/forum?id=rAM-D4BEDRK},
}
Figure