Implant Global and Local Hierarchy Information to Sequence based Code Representation Models

Kechi Zhang, Zhuo Li, Zhi Jin, Ge Li

Abstract

Traditional code representation models often struggle to balance the efficiency of sequence-based Transformers with the structural awareness of graph-based models. We introduce the Hierarchy Transformer (HiT), a novel architecture that embeds both global block-level structure and local token-level roles directly into the attention mechanism. By utilizing Concrete Syntax Trees (CST) to extract root-to-leaf hierarchical paths, HiT provides a comprehensive semantic context for each token. Experimental results across eight datasets demonstrate that HiT significantly outperforms state-of-the-art structural models and even large-scale pre-trained models like CodeBERT on complex logic tasks, while maintaining computational efficiency.

1. Introduction

The field of AI for Code has long been divided between two primary paradigms: sequence-based models and structural models. Sequence-based models, such as standard Transformers, excel at capturing long-range dependencies and the "naturalness" of code but often fail to recognize the rigid hierarchical structures—such as nested loops and conditional branches—that define program logic. Conversely, structural models like Graph Neural Networks (GNNs) or tree-based models focus on Abstract Syntax Trees (ASTs). While these capture structure effectively, they are often computationally expensive, possess narrow receptive fields, and can lose the linear flow of the code.

The Hierarchy Transformer (HiT) bridges this gap. The authors identify that existing hybrid models typically only utilize partial structural information, such as distances between nodes. HiT instead captures the complete hierarchical path from the program root to individual tokens, providing the "operational semantics" necessary for deep code understanding.

2. Methodology

HiT integrates structural information into a sequence-based framework through two primary stages: Hierarchy Extraction and a dual-encoder architecture.

2.1 Hierarchy Extraction

Rather than relying on Abstract Syntax Trees, HiT utilizes a parser (Tree-sitter) to generate a Concrete Syntax Tree (CST). CSTs are preferred because they retain "syntax noise" (e.g., braces, semicolons), ensuring a perfect alignment between structural nodes and the original token sequence. For every token, the model extracts the full path from the root to the leaf. This path is categorized into two levels:

  • Global Hierarchy: Represents the surrounding block structure (e.g., function -> for-loop -> if-statement).
  • Local Hierarchy: Represents the token’s specific role within a statement (e.g., identifying whether a variable is an operand or a target of an assignment).

2.2 The HiT Architecture

The architecture consists of two specialized components:

  1. Hierarchy Encoder: A compact Transformer that processes the root-to-leaf paths into fixed-length "hierarchy vectors."
  2. Sequence Encoder: The hierarchy vector is concatenated with the standard token embedding. This enriched representation is then processed by a larger Transformer that handles the entire code sequence.

This design allows the model to maintain the efficiency of a standard Transformer while gaining an explicit understanding of a token's logical position within the program's hierarchy.

3. Experimental Evaluation

HiT was evaluated across eight datasets spanning four programming languages (Python, Java, C++, and Ruby), covering tasks such as code classification, clone detection, and method name prediction. Key datasets included Project CodeNet, POJ-104, and CodeSearchNet.

3.1 Performance and Efficiency

The results indicate that HiT is particularly effective for complex logic. On the C++1400 classification task, HiT achieved an accuracy improvement of over 25% compared to a vanilla Transformer. Notably, HiT—trained from scratch—outperformed CodeBERT, a pre-trained model with 27 times more parameters, on the C++1000 and C++1400 datasets. This suggests that explicit structural information can be more impactful than sheer model scale for logical reasoning tasks.

From a computational standpoint, the hierarchy encoding adds only a 1% to 5% increase in parameter count. Furthermore, the inclusion of structural hints led to more stable training and faster convergence on difficult datasets.

4. Discussion and Insights

The success of HiT stems from its ability to use structure as a semantic signal. Analysis of the Python800 dataset revealed that over 91% of programs solving the same problem shared identical nested block structures (e.g., while-for-for-for-if). HiT leverages this regularity to disambiguate tokens; for instance, it can distinguish whether a variable i serves as a loop iterator or a partition index based on its hierarchical path.

4.1 Limitations

The model's reliance on CSTs requires the input code to be syntactically correct. Consequently, HiT may struggle with the "broken" or partial code snippets frequently encountered in real-time IDE autocompletion scenarios. Additionally, while the current hierarchy encoder is effective, the authors suggest that more sophisticated tree-traversal methods could further enhance structural capture.

5. Conclusion

The Hierarchy Transformer demonstrates that implanting global and local structural information into sequence-based models provides a powerful and efficient path forward for code representation. By bridging the gap between sequence and structure, HiT achieves state-of-the-art performance without the overhead of traditional graph-based approaches. Future work will explore integrating these hierarchical embeddings into large-scale pre-trained language models to further enhance their reasoning capabilities.

Summary updated

Abstract

Source code representation with deep learning techniques is an important research field. There have been many studies that learn sequential or structural information for code representation. But sequence-based models and non-sequence-models both have their limitations. Researchers attempt to incorporate structural information to sequence-based models, but they only mine part of token-level hierarchical structure information. In this paper, we analyze how the complete hierarchical structure influences the tokens in code sequences and abstract this influence as a property of code tokens called hierarchical embedding. The hierarchical embedding is further divided into statement-level global hierarchy and token-level local hierarchy. Furthermore, we propose the Hierarchy Transformer (HiT), a simple but effective sequence model to incorporate the complete hierarchical embeddings of source code into a Transformer model. We demonstrate the effectiveness of hierarchical embedding on learning code structure with an experiment on variable scope detection task. Further evaluation shows that HiT outperforms SOTA baseline models and show stable training efficiency on three source code-related tasks involving classification and generation tasks across 8 different datasets.
BibTeX
@inproceedings{zhang2023implant,
  author = {Kechi Zhang and Zhuo Li and Zhi Jin and Ge Li},
  title = {{Implant Global and Local Hierarchy Information to Sequence based Code Representation Models}},
  booktitle = {ICPC},
  year = {2023},
  url = {https://openreview.net/forum?id=b2eGTcTcKN},
}
Figure