---
title: "CAST — paper by Shi et al. (2021) — summary and ideas"
description: "CAST splits the syntax tree of a Java method into blocks, reconnects their representations, and uses them to write a short code summary."
canonical: "https://research.elamur.ai/free/en/papers/shi-2021-cast-enhancing-code-summarization-hierarchical/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/shi-2021-cast-enhancing-code-summarization-hierarchical/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2021](https://md.research.elamur.ai/free/en/papers/2021/) / CAST: Enhancing Code Summarization with Hierarchical Splitting and Reconstruction of Abstract Syntax Trees

# CAST: Enhancing Code Summarization with Hierarchical Splitting and Reconstruction of Abstract Syntax Trees

Paper · 2021 · Ensheng Shi, Yanlin Wang, Lun Du et al.

**Authors:** [Ensheng Shi](https://md.research.elamur.ai/free/en/authors/ensheng-shi/), [Yanlin Wang](https://md.research.elamur.ai/free/en/authors/yanlin-wang/), [Lun Du](https://md.research.elamur.ai/free/en/authors/lun-du/), [Hongyu Zhang](https://md.research.elamur.ai/free/en/authors/hongyu-zhang/), [Shi Han](https://md.research.elamur.ai/free/en/authors/shi-han/), [Dongmei Zhang](https://md.research.elamur.ai/free/en/authors/dongmei-zhang/) and Hongbin Sun · **Year:** 2021 · **Venue:** Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing · **Licence:** [CC BY 4.0 (ACL Anthology)](https://creativecommons.org/licenses/by/4.0/)

Cited by **10** papers in our library of the 163,136 papers whose bibliographies we read · Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing · [licence](https://creativecommons.org/licenses/by/4.0/)

- [Publisher's page](https://aclanthology.org/2021.emnlp-main.332/)
- [PDF](https://aclanthology.org/2021.emnlp-main.332.pdf)
- [DOI 10.18653/v1/2021.emnlp-main.332](https://doi.org/10.18653/v1/2021.emnlp-main.332)
- [arXiv 2108.12987](https://arxiv.org/abs/2108.12987)

## Summary

A short description can help a developer understand what a method does before reading its implementation. Writing those descriptions takes time, and producing them automatically requires a system to decide which details matter. The words in the source give clues, particularly through method and variable names. The way instructions are nested gives another kind of evidence. A loop can say what the method visits, while a condition inside it can say what happens to each item. CAST is a method for using both kinds of evidence in automatic [text summarization](https://md.research.elamur.ai/free/en/concepts/text-summarization/).

The authors start from an abstract syntax tree, or AST, which represents a method as a hierarchy of constructs. Large trees are expensive to process directly with a recursive neural network, and converting a tree to a sequence makes some of its relationships harder to use. CAST separates the tree into smaller parts using rules that identify constructs such as loops and conditionals. It keeps runs of simple statements together and leaves placeholders where nested constructs have been split off. A first recursive network encodes each part. A second follows the links between parts to combine what it learns about a block with what it learns about the blocks inside it. The resulting representations reach a decoder along with a separate encoding of the code tokens. The decoder can also copy tokens from the source.

The experiments use the Java benchmarks TL-CodeSum and Funcom, where the reference description is the opening sentence of the method’s Javadoc. CAST leads the baselines on BLEU-4, ROUGE-L, METEOR and CIDEr on both benchmarks. On Funcom, the authors report about 40 minutes per CAST training epoch and 21 hours per HybridDrl epoch. Removing the copy mechanism lowers the reported scores. Removing the hierarchical aggregation generally lowers them too, with Funcom METEOR as the exception. In an assessment of 50 test methods, developers rated CAST highest for similarity to the reference, naturalness and informativeness. The paper reports statistically significant differences against the selected baselines for those judgments, with an exception for naturalness against CodeAstnn.

The experiments support splitting at the level of blocks and giving the encoder a way to reconnect them. They also show why the source words remain useful alongside the tree. A structural representation can help the system decide what happened, while the token stream can supply the name that makes the description specific. The evidence concerns Java methods that could be parsed and paired with Javadoc descriptions. The authors make the implementation, data and splitting rules available.

## Deep dive: CAST: Enhancing Code Summarization with Hierarchical Splitting and Reconstruction of Abstract Syntax Trees

CAST splits the syntax tree of a Java method into blocks, reconnects their representations, and uses them to write a short code summary. · about 37 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Which details belong in a method description?

A developer looking at a method can use a short summary to decide how closely to read the body. For that purpose, a summary should convey some recognizable action or result. An inventory of local variables, punctuation and statement types would be a poor substitute. Even a fluent sentence can give a misleading impression if it describes an initialization and leaves out the operation the initialization makes possible. The research task is therefore to turn an implementation into a short account that preserves its important behavior.

The paper’s running example makes the selection problem concrete. The method visits the columns of a table and handles each column as a resource or as a relation. Setup statements and a return are also present. The loop and the conditional inside it jointly explain the action emphasized by the reference description. The loop identifies the scope of the work, and the conditional supplies what distinguishes the work done within that scope. Describing the iteration alone leaves the reader with little sense of its purpose. Naming the possible outcomes alone leaves out what the outcomes apply to. That combination is the kind of information CAST tries to make accessible to a summary generator.

There are several ways to represent the evidence in the source. The code token sequence preserves the words and symbols the programmer wrote and their order. A name may offer a direct clue about a data structure or operation. An abstract syntax tree makes relationships among constructs explicit. A parent node can stand for a loop, with other nodes representing the parts belonging to it. A conditional nested in the loop appears beneath it in the tree. Both views come from the same method, but they make different facts easy to find. CAST uses this distinction to organize the input to a generator for [code and programming languages](https://md.research.elamur.ai/free/en/topics/code-and-programming/).

The tree is built by a parser, a program that analyzes source according to the language’s grammatical rules. The resulting hierarchy represents how an expression or statement fits into a larger construct. A node can have children, and a child can be the root of a subtree with children of its own. In the running example, the loop continues to have the conditional inside it even if the names used in the condition are changed. An encoder can learn from that relationship separately from the names. The relevant operation is [parsing](https://md.research.elamur.ai/free/en/concepts/parsing/).

#### What earlier approaches made available

The authors describe early rule-based and information-retrieval approaches that treated source code as text. Such approaches could act on words that appeared in the implementation. The paper places them alongside later neural approaches that also use tokens, although the latter learn numerical representations and can weigh different parts of the input during generation. CodeNN, for example, uses attention to obtain context from code and generates a description from that context. Another line of work used attention over a moving window of tokens to produce very short descriptions resembling descriptive function names. The paper treats the latter as a related goal with a different form of output.

A sequence-to-sequence system learns to turn an input sequence into an output sequence. In code summarization, the input can be a sequence obtained from the method and the output is a sequence of words in the description. An encoder produces states from the input, and a decoder uses those states as it generates. Attention lets a decoder give some input states greater influence at a particular output position. The authors situate code summarization in this tradition, which also underlies the neural approaches they cite from [machine translation](https://md.research.elamur.ai/free/en/topics/machine-translation/).

The NCS system shows how far a code-token channel can go by itself. It uses a Transformer to connect evidence from positions across the input, including positions separated by many other tokens. A method’s name and an operation inside its body can both contribute to an encoded state even when they are far apart in source order. CAST later uses the NCS design as the basis of its token channel. The earlier study is [A Transformer-based Approach for Source Code Summarization](https://md.research.elamur.ai/free/en/papers/ahmad-2020-transformer-based-approach-source-code/).

Other approaches turn the syntax tree into an input a sequence encoder can consume. Structure-based traversal visits nodes in a prescribed order and writes out a sequence that reflects the visit. HDeepcom and Astattgru provide separate inputs for source code and the AST-derived sequence. A traversal can supply structural cues, and two channels give the decoder access to both those cues and the source vocabulary. The encoder still processes the traversal as a succession of positions. The authors argue that this leaves it with a weaker account of the original hierarchy than an encoder whose operations follow parent–child relationships directly.

Code2seq samples paths through the tree. A path gives the relationship between nodes along a selected route, and attention can select relevant paths while a summary is being produced. The input is useful because individual paths can bind together parts of the code that occur far apart in the source. The collection of sampled paths supplies partial views of the overall organization. From CAST’s perspective, the remaining question is how to represent a complete enclosing block, including the relationships among the smaller constructs that contribute to it.

A different family of approaches performs neural computation over trees. The paper discusses tree-based convolution and recursive networks, as well as the tree version of a long short-term memory network used by HybridDrl. HybridDrl encodes a sequence and a tree, joins the evidence through attention, and uses reinforcement learning. The tree branch requires converting the AST into a binary tree, a form in which a node can have at most two children. The CAST authors associate that conversion with greater depth and lost structural information. A neural operation performed over the converted hierarchy has to work through the extra levels it introduces.

The paper also mentions other uses of program structure. Some research represents code idioms as tree segments. Other work uses graph neural networks for source representations. It places ensemble and pretraining approaches in the broader research on representing code. Those lines of work establish the range of alternatives under consideration. The comparisons most directly relevant to CAST concern methods that take a full AST, linearize some account of it, or divide it into smaller trees.

#### Why the size of a tree matters

The scale of the input is part of the design problem. In TL-CodeSum, the reported maximum AST node count is 6,165 and the maximum depth is 74. In Funcom, the corresponding maxima are 550 nodes and a depth of 32. Node count describes how much material an encoder may need to process for a method. Depth describes how far a child can sit below the root. These figures are maxima for the datasets, so they illustrate the size and depth the encoder may encounter. A method with nested constructs can require information to pass through several successive operations before it reaches the root.

That chain matters during training as well as encoding. The result at an ancestor depends on values computed for its descendants. During learning, the signal used to adjust a parameter also travels through such dependencies. The authors motivate shallower computation with the problems of vanishing or exploding gradients. A vanishing signal makes a distant dependency difficult to learn, while an exploding signal can make updates unstable. Their proposal changes the path between a syntax node and the global representation by first summarizing a local part and then propagating the summary through a smaller tree.

ASTNN had already addressed size by breaking a method into statement trees. It encodes the small trees and combines their representations in sequence with a recurrent neural network. CAST takes up both decisions that this design separates. It sets boundaries around units that can retain several related statements, and it uses the syntax of the method to decide how their representations should meet. A run of setup statements can remain together, while the block for an inner conditional can retain its relationship to the loop enclosing it. The difference concerns both the content of a part and the structure in which those parts are combined.

### The method, step by step

#### From one method to a summary

CAST follows the encoder–decoder design with two encoders. One starts from the AST and supplies structural context. The other starts from the token sequence and supplies lexical context, meaning evidence carried by individual tokens and the positions around them. A decoder attends to both sources as it generates text. The paper bases the token encoder and decoder on the [Transformer and attention](https://md.research.elamur.ai/free/en/concepts/transformer/).

The distinctive operations occur in the AST encoder. A traversal identifies points where the tree can be separated. The cut produces a smaller tree and a link recording where that tree belonged. CAST learns a vector for each smaller tree, then walks the links to produce vectors informed by the contents of nested parts. The decoder can consult the resulting states, including states associated with portions of the method. The token channel continues to provide states at code-token positions. These are also the positions used when the decoder considers copying a token.

How CAST turns a method into a summary The steps in order.

#### How the splitter chooses a boundary

A preorder traversal visits a node before visiting its descendants. This gives the splitter a chance to recognize a composite construct, such as an `If` or `While`, before processing all the syntax below it as part of the current tree. When a splitting rule applies, the traversal leaves a placeholder at the construct’s position and takes the detailed tree rooted there as material for another part. Splitting can recur within that part. A placeholder therefore answers where the detail belongs in the enclosing tree, while the new subtree supplies the detail itself.

The rules divide a method into units with different jobs. The overview tree, denoted `OvT`, sketches the method at a high level. The signature tree, `SigT`, carries information from the method signature. A sequence of simple statements can go into a statement-group tree, `StmtsT`, and a composite block can produce a `BlockT`. Grouping consecutive simple statements keeps related material together and avoids giving every simple statement its own entry in the structure tree. Composite constructs get boundaries of their own because they introduce levels in the syntax.

The splitting procedure alternates between keeping such units together and looking inside them for further blocks. At a particular level, much of the internal syntax of the current block is available for local encoding. The detailed contents of an inner composite block are deferred to a subtree below it. Repeating this process until there are no further nested blocks to take out gives every extracted portion a place in a higher-level structure tree. Each node of that structure tree stands for a part, and its edges indicate which parts came from within other parts. The original AST edges within an individual part are still available to the first encoder.

In the running example, the detailed walkthrough labels the overview `T₁`. Its principal body entries represent the initial statements, the loop, and the final statement group. The initialization group is `T₃`, with 4 initialization statements. The loop part is `T₅`. A placeholder within it marks a nested conditional whose detail goes into `T₄`. The final group is `T₆`, which contains the return statement. The walk through the method illustrates why the rules can produce a group of ordinary statements and a composite block at the same level. Both are body segments, even though their syntax calls for different treatment.

The loop and the conditional also illustrate the direction of the link. A reader can start with the overview and ask what a particular loop does, then follow its placeholder to the test performed during iteration. CAST’s aggregation later works bottom up, so the information computed for the test can inform the loop representation. The loop in turn contributes to the overview. In the reference description, the treatment of a column belongs to the operation performed while iterating. The recorded links give the encoder an explicit route for bringing those details together.

This choice of boundary is grammatical. It does not depend on whether the reference mentions a part or on a prediction of the contribution that part will make to the sentence. The initialization and return portions are still available even though the running reference emphasizes the loop and conditional. The split makes selection possible at more useful levels. The decoder subsequently learns, from method–summary pairs, which evidence to use. The paper presents the main organization of the rules and makes the full rule specification and implementation available.

#### Encoding the nodes within a part

Once the split is complete, a recursive neural network, abbreviated RvNN, processes the tree inside each part. A node starts with a vector associated with its token or syntactic label. Such a vector is an embedding, a numerical representation whose components can be transformed and combined with other vectors. The same operation is applicable at several locations in the tree. The result for a node depends on its own embedding and the results for its immediate children. CAST’s first stage uses these [word embeddings](https://md.research.elamur.ai/free/en/concepts/word-embeddings/) for AST tokens as inputs to the recursive computation.

```
Tₜ = (Vₜ, Eₜ)
```

Here `Tₜ` is the subtree indexed by `t`. `Vₜ` is its node set and `Eₜ` is its edge set. The ordered pair identifies the constituents of the subtree and the links that determine where the recursive operation is applied. At this stage, these links connect nodes within one part of the split AST.

```
hᵢ⁽ᵗ⁾ = tanh(Wᶜ cᵢ⁽ᵗ⁾ + (1 / |Chₜ(vᵢ)|) ∑[vⱼ ∈ Chₜ(vᵢ)] Wᴬ hⱼ⁽ᵗ⁾)
```

In subtree `t`, `vᵢ` is the node indexed by `i`, `cᵢ⁽ᵗ⁾` is its token embedding and `hᵢ⁽ᵗ⁾` is the hidden state computed for it. `Chₜ(vᵢ)` is the set of its immediate children in the subtree, and the vertical bars denote the number of children. The sum runs over each child `vⱼ`, indexed by `j`, and uses its already computed state `hⱼ⁽ᵗ⁾`. The trainable matrix `Wᶜ` transforms the current node’s embedding and the trainable matrix `Wᴬ` transforms the children’s states. The factor `1` divided by the child count turns their sum into a mean. The function `tanh` is the hyperbolic tangent applied to the components after adding the current-node and child contributions.

```
hᵢ⁽ᵗ⁾ = Wᶜ cᵢ⁽ᵗ⁾
```

This is the paper’s rule for a leaf `vᵢ`, a node that has no children. The vector `hᵢ⁽ᵗ⁾` is computed from the leaf’s embedding `cᵢ⁽ᵗ⁾` in part `t` and the same learned projection `Wᶜ`. The separate leaf rule supplies the base case for the bottom-up computation and avoids dividing by an empty child count.

A child contributes a vector of the same kind as its parent’s final state, so it can carry information from more than one level below. For instance, local syntax specifying a part of the loop can influence the state for a construct that contains it. The averaging operation means that each child at a node contributes through the same transformation and with the same scalar weight in that operation. Descendant structure can still matter because a different grouping changes which states get combined first. At a given parent, permuting the child states leaves their mean unchanged. That property matters when interpreting preservation of structure. The operation uses the tree’s nesting and is insensitive to sibling order at the point where it computes the mean.

The subtree vector comes from all node states. This is a pooling operation, which converts a collection of vectors into a single vector of the same width. CAST uses the largest component value it finds for each dimension.

```
sₜ = maxpool({hᵢ⁽ᵗ⁾ ∣ vᵢ ∈ Vₜ})
```

Here `sₜ` is the vector used to represent all of `Tₜ`. The braces enclose the collection of states `hᵢ⁽ᵗ⁾` for the nodes `vᵢ` belonging to `Vₜ`, and the vertical bar means that the collection includes each state satisfying that membership condition. `maxpool` picks a maximum independently in each vector dimension. The state that supplies one component of `sₜ` can differ from the state that supplies another component.

Pooling gives a feature detected low in a subtree a direct path into its vector. It also compresses the representation. Once a subtree has been pooled, the next stage sees the selected component values and the subtree’s placement in the structure tree. It cannot use the pooling output to recover which node supplied each value or how often that value occurred. The compact representation is useful precisely because the next stage can operate once per subtree while the fine-grained operations stay local to the parts.

#### Passing information from nested blocks to enclosing blocks

The second recursive operation runs on the structure tree `T`. Its nodes are subtrees rather than individual syntax tokens. Each such node begins from the pooled state of its part, then takes account of its child parts. The first RvNN is reused across the parts for their internal syntax, and the second has its own learned parameters to operate on pooled representations.

```
hₜ⁽ᵃ⁾ = tanh(Wˢ sₜ + (1 / |Ch(vₜ)|) ∑[vₖ ∈ Ch(vₜ)] Wᴮ hₖ⁽ᵃ⁾)
```

The node `vₜ` in structure tree `T` stands for subtree `Tₜ`, with pooled vector `sₜ`. The vector `hₜ⁽ᵃ⁾` is its state after aggregation, indicated by the superscript `a`. The set `Ch(vₜ)` contains its immediate children in the structure tree, and the vertical bars give their count. The sum runs over a child `vₖ` indexed by `k`, whose aggregated state is `hₖ⁽ᵃ⁾`. The trained matrix `Wˢ` projects the local subtree vector and `Wᴮ` projects each child state. The numerator `1` in the reciprocal makes the child term an average. The function `tanh` combines the projected local and child terms through a componentwise hyperbolic tangent. The displayed mean is the contribution from children at a node that has them.

For the conditional in the example, the pooled vector summarizes the syntax inside its own part. Its aggregated state contributes to the node for the loop. The loop also has its own local vector, obtained before information from the conditional was brought in. Combining them makes it possible to represent the effect of the conditional in the context of the iteration that encloses it. One step higher, the overview state can incorporate the loop as a whole alongside the other parts of the method.

Reconstruction here means using the recorded hierarchy to reassemble information. The decoder has access to a sequence of aggregated states, obtained by visiting the nodes of the structure tree in preorder. That sequence includes the root state incorporating information from across the tree, as well as states for individual parts that incorporate their own descendants. Using a sequence as the interface gives attention a collection it can query. The states in that collection have already undergone computation along the tree edges. This is how the architecture can present the decoder with a convenient sequence while giving each entry information conditioned on its place in the hierarchy.

The two stages also distinguish two scales of recursion. Within a part, recursion follows relationships among syntax nodes. Across parts, it follows relationships among the extracted blocks. If the full AST has several nested constructions, local recursion can stop at placeholders, with the longer-range relationship handled by the structure tree. This is the authors’ basis for expecting a more manageable training process. The paper assesses the design through timings and comparisons of complete systems and variants.

#### Encoding the code tokens

The token channel attends over embeddings obtained from the source sequence. The paper uses a Transformer encoder with multiple attention heads and relative position representations. A head learns its own way of projecting token vectors and comparing positions. Relative position information lets an attention computation distinguish relationships involving the same apparent token types at different offsets. The general Transformer framework comes from [Attention Is All You Need](https://md.research.elamur.ai/free/en/papers/vaswani-2017-attention-all-need/).

```
c = (c₁, …, cₙ)
```

The sequence `c` contains the input code-token embeddings. The vector `cᵢ` is the embedding at position `i`, and `n` is the number of code-token positions. The ellipsis stands for the intervening positions in source order.

```
eᵢⱼ = ((Wᑫ cᵢ)ᵀ (Wᴷ cⱼ + aᵢⱼᴷ)) / √dₖ
```

The score `eᵢⱼ` measures how strongly position `i` queries position `j` in one head. The pair `cᵢ` and `cⱼ` supplies the two code embeddings. The learned matrix `Wᑫ` projects the first into a query, and `Wᴷ` projects the second into a key. The vector `aᵢⱼᴷ` adds the relative position representation for the key side. The superscript `T` denotes transposition, so the multiplication between the projected query and the adjusted key is a dot product. The denominator `√dₖ` is the square root of the query and key dimensionality, `dₖ`.

```
αᵢⱼ = exp(eᵢⱼ) / ∑[k from 1 to n] exp(eᵢₖ)
```

The weight `αᵢⱼ` is the share of attention at query position `i` assigned to source position `j`. The function `exp` is the exponential. The numerator applies it to the compatibility score `eᵢⱼ`. The sum in the denominator runs over positions indexed by `k`, beginning at `1` and ending at the number of code positions `n`. The term `eᵢₖ` is the score for the same query position paired with position `k`. Normalization produces attention weights that sum to one for the query.

```
oᵢ = ∑[j from 1 to n] αᵢⱼ (Wⱽ cⱼ + aᵢⱼⱽ)
```

The output `oᵢ` is the vector for position `i` in the head. Each position `j`, from `1` to `n`, supplies its embedding `cⱼ` after projection by the learned value matrix `Wⱽ`. The vector `aᵢⱼⱽ` adds relative position information on the value side. The weight `αᵢⱼ` scales this adjusted value. The resulting code states are written as `o = (o₁, …, oₙ)`, where `o` is the sequence and the ellipsis denotes the states of the intervening positions.

The query and key computation determines how much to retrieve. The value computation determines what a selected position contributes. In the method example, these operations give the token channel a way to relate a name to operations involving it elsewhere in the method. The subtree channel supplies a different view, organized around the structures in which operations occur. The decoder has access to both even when a clue is prominent in only one channel.

#### Looking up the two sources in sequence

At each summary position, the decoder begins from a state produced by attention over the summary sequence. It then uses cross-attention, an attention operation in which the query comes from the decoder and the keys and values come from an encoder. CAST puts the two cross-attention operations in series. The summary state first queries the AST states. The result of that operation then queries the code-token states. Thus the second lookup is conditioned on the structural information retrieved in the first.

The paper introduces `l` as the number of subtrees, and its source sequences have one AST state per subtree and one code state per code token. The printed decoder equations use `n` as the upper bound for both sources, and the prose following them interchanges the meanings of `m` and `n` relative to the sequences introduced immediately before. The equations below use `l` for the AST bounds and `n` for the code bounds, in agreement with those sequences. The decoder also writes the value projection with and without the decoder subscript. The notation here uses that subscript throughout to identify the decoder projections.

```
eᵃˢᵗᵢⱼ = ((W_dᑫ sᵢ)ᵀ (W_dᴷ hⱼ⁽ᵃ⁾)) / √dₖ
```

Here `eᵃˢᵗᵢⱼ` is the AST attention score for summary position `i` and structure-tree position `j`. The query input `sᵢ` comes from summary self-attention and belongs to the sequence of `m` summary positions. It is distinct from the pooled vector `sₜ` in the tree encoder. The key input `hⱼ⁽ᵃ⁾` is the aggregated AST state in preorder position `j`. The learned decoder projections `W_dᑫ` and `W_dᴷ` produce a query and a key. The transposition sign `T` makes their product a dot product, and `√dₖ` again scales it by the square root of their dimensionality.

```
αᵃˢᵗᵢⱼ = exp(eᵃˢᵗᵢⱼ) / ∑[k from 1 to l] exp(eᵃˢᵗᵢₖ)
```

The weight `αᵃˢᵗᵢⱼ` is the normalized importance of AST position `j` for summary position `i`. The exponential `exp` converts each score into a positive term. The numerator uses the score for position `j`, and the denominator sums the terms for all AST positions indexed by `k`, from `1` through `l`. The notation `eᵃˢᵗᵢₖ` denotes the score when the same summary query considers position `k`.

```
zᵢ = ∑[j from 1 to l] αᵃˢᵗᵢⱼ W_dⱽ hⱼ⁽ᵃ⁾
```

The vector `zᵢ` is the AST cross-attention result for summary position `i`. The learned decoder value matrix `W_dⱽ` projects the AST state `hⱼ⁽ᵃ⁾` at each position `j`. The sum covers positions `1` through `l` and scales each projected vector by its attention weight `αᵃˢᵗᵢⱼ`.

```
eᶜᵒᵈᵉᵢⱼ = ((W_dᑫ zᵢ)ᵀ (W_dᴷ oⱼ)) / √dₖ
```

The code attention score `eᶜᵒᵈᵉᵢⱼ` pairs summary position `i` with code position `j`. The learned query projection `W_dᑫ` now acts on the AST lookup result `zᵢ`. The learned key projection `W_dᴷ` acts on the code-token state `oⱼ`. The superscript `T` transposes the projected query for the dot product. The denominator `√dₖ` is the same type of dimensional scaling used for the AST score.

```
αᶜᵒᵈᵉᵢⱼ = exp(eᶜᵒᵈᵉᵢⱼ) / ∑[k from 1 to n] exp(eᶜᵒᵈᵉᵢₖ)
```

The code attention weight `αᶜᵒᵈᵉᵢⱼ` is the normalized importance of code position `j` for summary position `i`. The function `exp` is applied to the score `eᶜᵒᵈᵉᵢⱼ` for that position. The denominator uses the scores `eᶜᵒᵈᵉᵢₖ` for all code positions `k` from `1` to `n`.

```
yᵢ = ∑[j from 1 to n] αᶜᵒᵈᵉᵢⱼ W_dⱽ oⱼ
```

The output `yᵢ` is the code cross-attention result for position `i`. For every code position `j` from `1` to `n`, the matrix `W_dⱽ` projects its state `oⱼ` to a value vector. The attention weight `αᶜᵒᵈᵉᵢⱼ` determines that vector’s contribution to the sum.

The separation between the scores clarifies why the order matters. The AST stage can bring a subtree or its descendants into the current summary context. The code stage can then select token evidence using that updated context. This procedure is repeated within the decoder layers, whose self-attention and cross-attention use multiple heads. After the stacked decoder operations, a softmax output gives a probability distribution over the vocabulary used to generate summary tokens. The two encoder streams have by then contributed through attention. The copy operation gives the decoder a further way to use the source.

#### Choosing a vocabulary word or a source token

The motivation for copying is that useful source words can be rare even when they are informative. The authors estimate that about 28% of summary tokens in Funcom are copied directly from the source. Method and variable names are examples. After preprocessing, it may be the component of a name that matches the description. A decoder with a fixed vocabulary can use the token encoder to understand such a component while still having no vocabulary entry for it. The copy distribution assigns probabilities to source positions and can put the component into the output that way.

```
Pₜ⁽ᶜ⁾(i) =
  exp(⟨Wᶜᵖ hᵢ⁽ᶜ⁾, hₜ⁽ˢ⁾⟩) /
  ∑[k from 1 to T_c] exp(⟨Wᶜᵖ hₖ⁽ᶜ⁾, hₜ⁽ˢ⁾⟩)
```

Here `Pₜ⁽ᶜ⁾(i)` is the copy probability for code position `i` when filling summary position `t`. The vector `hᵢ⁽ᶜ⁾` is the encoded state at that source position and `hₜ⁽ˢ⁾` is the current decoder state. The learned projection `Wᶜᵖ` maps the source state into the space of the decoder state. The angle brackets denote an inner product. The exponential function `exp` is applied to the resulting score. The denominator performs the same operation for all source positions `k` from `1` to `T_c`, where `T_c` is the length of the code-token sequence.

```
γₜ = sigmoid(Γ(hₜ⁽ˢ⁾))
```

The scalar `γₜ` is the learned weight given to generating from the vocabulary at summary position `t`. The feedforward network `Γ` takes the summary state `hₜ⁽ˢ⁾` and outputs a score. The `sigmoid` function turns that score into a probability. The gate can therefore give different weight to vocabulary generation at different places in the description.

```
Pₜ(w) = γₜ Pₜ⁽ᵍ⁾(w) + (1 − γₜ) ∑[i such that wᵢ⁽ᶜ⁾ = w] Pₜ⁽ᶜ⁾(i)
```

The final probability `Pₜ(w)` is the probability of emitting token `w` at summary position `t`. The vocabulary softmax supplies `Pₜ⁽ᵍ⁾(w)`, which is multiplied by the generation weight `γₜ`. The other weight, `1 − γₜ`, multiplies the probability of obtaining `w` from the code. That probability is a sum over positions `i` at which the source token `wᵢ⁽ᶜ⁾` equals `w`. The term contributed by each such position is `Pₜ⁽ᶜ⁾(i)`. If the same token occurs at several positions, their copy probabilities contribute to the same output choice.

The final distribution can reward both ways of reaching the target. An ordinary word can have vocabulary probability and also receive probability from matching source positions. A rare token found in the code can benefit from the copy route. The system learns the gate and the rest of the decoder together by maximum likelihood. In this setting, that means increasing the probabilities assigned to the observed tokens in the reference descriptions. The paper uses AdamW to update the learned parameters, citing [Decoupled Weight Decay Regularization](https://md.research.elamur.ai/free/en/papers/loshchilov-2017-decoupled-weight-decay-regularization/).

#### Preparing the pairs used for learning

Both corpora pair Java methods with descriptions. The authors follow the original train, validation and test partitions. The target text comes from the opening sentence in each method’s Javadoc description. On the input side, CAST needs a successful parse to obtain its tree. The authors remove cases the ANTLR parser cannot parse, so the resulting corpora count the method–summary pairs available after that filtering. Training updates use the training data, while the benchmarks retain separate validation and test portions.

The token stream undergoes several transformations. The authors split identifiers at camel-case and snake-case boundaries, replace numerals with `<NUM>` and string literals with `<STRING>`, and lower-case the text. This makes the lexical units presented to the encoder more regular. It also determines what the decoder can copy. A source identifier represented as several lower-cased pieces gives the copy operation access to those pieces. Values represented by generic placeholders supply the presence of a literal category through the token stream. These choices define the paper’s [tokenization](https://md.research.elamur.ai/free/en/concepts/tokenization/).

The implementation is based on [OpenNMT](https://md.research.elamur.ai/free/en/papers/klein-2017-opennmt-open-source-toolkit-neural/). The authors allocate vocabularies of 10,000 entries for AST tokens, 30,000 for code tokens and 50,000 for summary tokens. These vocabularies serve different parts of the architecture. The AST vocabulary provides input embeddings for syntax nodes, the code vocabulary provides input embeddings for the source sequence, and the summary vocabulary determines what the vocabulary branch can generate. Copying extends the last branch’s choices to tokens available at source positions.

Training uses batches of 128 and a learning rate of `10⁻⁴`. The epoch limits are 200 for TL-CodeSum and 40 for Funcom. Early stopping uses patience 20 as a measure against overfitting, so the limits describe the maximum schedules instead of the stopping point of each run. The paper reports timings on a server with 4 NVIDIA Tesla V100 GPUs. These settings place the empirical cost of the method in the context of the particular implementation and training setup.

### Experiments and results

#### Benchmarks and the basis of comparison

The filtered TL-CodeSum corpus contains 83,661 source and summary pairs. The filtered Funcom corpus contains 2,111,230. These are dataset totals across their retained partitions. The reported benchmark performance concerns the test sets. Retaining the original partition scheme keeps the evaluation tied to benchmarks used in earlier work. The parse requirement matters for understanding what was evaluated, since a system based on ASTs needs its input to be accepted by the parser. Both corpora use Java, despite the substantial difference in their size.

The baselines cover several ways to encode source. CodeNN and Attgru use sequential evidence. NCS is a Transformer approach to code tokens, while Code2seq uses paths from the syntax tree. The paper also compares HybridDrl, HDeepcom and Astattgru, which incorporate both lexical and structural evidence through different encoding strategies. These comparisons ask whether CAST is competitive across several types of summarizer. Because they differ in architecture and source representation, their relative scores reflect the choices made by each complete system.

CodeAstnn was constructed to make the comparison with ASTNN closer. The authors add a code-token encoder like CAST’s so that the systems can be compared with lexical evidence available in both. The CodeAstnn branch still divides the AST at statement granularity and combines its subtree states through a recurrent sequence. CAST has a block-based split and joins the resulting vectors through the structure tree. The authors therefore frame this as a comparison of the AST representations, a category that includes both where the tree is cut and how its parts are combined.

The comparison with NCS asks a related question from the other direction. CAST assumes that the token sequence has genuine predictive value and uses an encoder from a strong token-only approach. The tree channel must add something beyond a useful lexical starting point. Similarly, the comparison with Astattgru asks whether the way structural evidence is encoded makes a difference when there is already an AST channel. Simply providing an AST-derived input is common to both approaches. The information made available at each decoder lookup differs.

#### Automatic scores and training time

The paper evaluates the generated summaries with BLEU-4, ROUGE-L, METEOR and CIDEr. All compare generated text with reference text. They are used here to score a short description against the Javadoc sentence paired with the method. The authors report BLEU, ROUGE-L and METEOR as percentages. Their underlying scale is `[0,1]`. CIDEr is shown on its `[0,10]` scale as a raw score. These reporting conventions matter because the displayed score magnitudes represent different scales across metrics. The cited methods include the [BLEU score](https://md.research.elamur.ai/free/en/concepts/bleu/) and [CIDEr](https://md.research.elamur.ai/free/en/papers/vedantam-2014-cider-consensus-based-image-description/).

The authors also specify the BLEU implementation. Earlier code summarization studies use versions with differences in how the score is computed, including BLEU-ncs and BLEU-FC. CAST uses BLEU-CN. A score can therefore be compared under the paper’s declared protocol, while a value in a different study needs the implementation checked as well. ROUGE-L is drawn from [ROUGE](https://md.research.elamur.ai/free/en/papers/lin-2004-rouge-package-automatic-evaluation-summaries/).

The main comparison reports that CAST leads all evaluated baselines on all four metrics on TL-CodeSum and Funcom. That is a ranking on the test benchmarks, and the results discussion gives the ordering instead of stating the individual metric values. Among the systems using only code or only AST evidence, the authors single out NCS as stronger and attribute its performance to attention across long token sequences. Astattgru and CodeAstnn score above Attgru, which the authors connect to the value of adding a structural channel. CAST also leads the AST representation comparisons with HybridDrl, Code2seq and Astattgru.

The practical cost comparison is particularly visible on Funcom. The authors report about 40 minutes for a CAST epoch on Funcom and 21 hours for a HybridDrl epoch on that benchmark. They also report about 10 minutes for a CAST epoch on TL-CodeSum. An epoch is a pass through the training data, and per-epoch time includes the behavior of the architecture and its implementation on the training workload. The paper uses these observations to support the claim that the two-stage tree encoder is practical to train. Per-epoch time and time to a selected stopping point are distinct measurements, especially when schedules and early stopping can differ.

CAST training time per epoch on TL-CodeSum and Funcom CAST takes longer per epoch on Funcom than on TL-CodeSum.

**The numbers**

| System or setting | minutes per training epoch |
| --- | --- |
| CAST on Funcom | 40 |
| CAST on TL-CodeSum (this paper) | 10 |

The settings in the chart differ in their datasets. This is a view of the reported workload for CAST on each benchmark. The comparison with HybridDrl concerns the Funcom workload specifically, where the paper gives a timing for the tree-based baseline in hours. Together, the observations give the reader a sense of the training burden under the authors’ setup. They do not quantify what share of the time is spent in syntax encoding, token encoding, decoding or preparing batches.

#### How developers judged the summaries

The human study considers CAST, Astattgru, NCS and CodeAstnn. The authors randomly select 50 Java methods from the held-out test sets, with 25 from TL-CodeSum and 25 from Funcom. The comparison is based on descriptions generated for these same methods. That lets the raters assess systems against the same underlying pieces of code and corresponding reference descriptions.

There are 10 volunteers. According to the authors, they have strong English skills and over three years of experience developing software. Each summary receives scores from four volunteers, and their ratings are averaged. The scale runs from 0 to 4, with higher ratings indicating better performance. The study distinguishes agreement with the reference, naturalness and informativeness. Naturalness is assessed through fluency and grammaticality. Informativeness concerns how much content from the method survives in the description, with the raters instructed to set fluency aside for that judgment.

These categories allow several distinct outcomes. A sentence can repeat the reference’s central point in awkward English. It can read smoothly while giving little information about the code. It can also give useful information about the method while choosing a different phrasing or emphasis from the Javadoc sentence. The separation is especially relevant to a system designed to retain relationships between blocks. A developer needs to judge whether the output describes the operation represented by those relationships, and the informativeness criterion directly asks for a judgment about content drawn from the method.

CAST has the highest reported average rating in each category. The authors emphasize informativeness as the clearest advantage and interpret it as evidence for more complete descriptions. They also apply Wilcoxon signed-rank tests to the human ratings. This kind of test compares paired observations by using the ranks and directions of their differences. The paper reports p-values below 0.05 at a 95% confidence level for the improvements over the compared systems, except for naturalness against CodeAstnn. The highest mean naturalness rating and the exception in the significance tests are compatible. The observed ordering of averages and the evidence for a reliable difference answer different questions.

The running method gives a qualitative counterpart to those measurements. The authors compare descriptions that capture only part of the intended action with one that conveys both the iteration and the treatment of each column. The example makes it possible to trace the relevant pieces back to separate subtrees, then to place them in the same operation through the structure tree. The aggregate ratings tell how developers responded to descriptions across the sampled methods. The example shows how an omission can matter in a concrete output, even when that output reads like a plausible description of code.

### What the ablations show

#### Keeping the split and removing the aggregation

The first ablation, `CASTₐ`, removes the second recursive operation. It takes the vectors produced by subtree pooling and uses them as the structural inputs to the decoder. That leaves the block boundaries and the first recursive encoder in place. Each local vector already knows something about the syntax of its own part. The change is that the vector for an enclosing part has not been updated by passing information up from the detailed subtrees below it.

In the running example, the loop subtree can still provide information about iterating over columns, and the detached conditional can still provide information about choosing how to handle a column. Both remain accessible to attention. In full CAST, the loop state can also incorporate the conditional before attention sees either state. The ablation tests the practical value of giving the decoder representations that have already combined these pieces along the tree.

The variant’s scores fall relative to full CAST except for METEOR on Funcom. This pattern supports the value of the aggregation in the particular split-and-decode architecture. It also places a limit on how uniformly the effect appears in the reported evaluation. The exception is within a single metric on one corpus, while the other comparisons favor full CAST. The results discussion does not give the magnitudes of those changes, so the direction and coverage of the effect are clearer than its size.

The ablation isolates removal of the hierarchical computation from a system that still has the information needed to recognize local constructs. It does not hold recursive capacity constant while supplying the same subtree vectors in a different topology. A comparison with an additional, equally sized sequence aggregator would isolate a narrower question about whether the advantage comes specifically from following the original relationships. The reported ablation answers the closer architectural question of whether the full CAST pipeline benefits from its second recursive stage.

#### Keeping the encoders and removing copying

The second ablation, `CAST꜀`, keeps the source encoders and removes the copy mechanism. The decoder still attends to the code tokens and the tree states. It can use their evidence to choose a word from the summary vocabulary. It loses the branch that assigns probability directly to occurrences of a token in the source. This is an output-side intervention, so it helps separate the effect of being able to write a source token from the effect of using the token sequence as context.

Full CAST scores above the copy-free variant. The authors connect the improvement to rare tokens, particularly ones outside the vocabulary for generation. That explanation follows from the mechanics of the distribution. An identifier component can receive a probability through a source position even if the generation branch cannot emit it. The comparison measures the result of enabling that mechanism across the whole benchmark. It does not break out a score for descriptions with rare identifiers or report how frequently a correct output token came primarily from the copy branch.

The two interventions address different stages of one prediction. Hierarchical aggregation changes the evidence supplied to the decoder. Copying changes the available choices when the decoder turns evidence into an output token. A system can assemble the right account of a method’s operation yet produce a less informative description if it misses the name needed to identify the object. It can also reproduce a name that appears in the source while overlooking an important action. The ablations indicate that both stages contribute in CAST. Since the paper varies them separately, the comparisons give the effect of removing each while leaving the other in the full system.

#### What the comparisons say about splitting

The authors report that CAST remains ahead of other baselines with either of the individual ablations. They argue that the split supplies useful block-level evidence even before the second recursion has been applied. They compare this with breaking the AST into separate statements. On TL-CodeSum, their statement-level CodeAstnn subtrees are reported as 71% smaller than CAST’s. The statistic concerns subtree size. It shows that the granularity difference between the methods is substantial on that corpus.

The practical meaning of that size difference depends on what stays together. In CAST, a run of related setup statements can contribute to a common subtree representation. A loop can have its own local structure even when its nested condition is represented separately. A statement-level system can still learn relationships among the statements through its sequence aggregator. It receives a different unit of input there, and it has to derive links across those units from their states and order. Thus the comparison with CodeAstnn bears on both the information inside each vector and the route available for combining vectors.

The other baselines clarify particular tradeoffs. A sampled AST path retains a relation along that path. An AST traversal supplies cues from a linear visit. A full-tree approach operates on a much larger tree in the HybridDrl comparison, and its binary conversion changes the recursion it performs. The reported ordering is consistent with CAST’s motivation for encoding manageable parts and keeping an explicit hierarchy among them. The ablation of the second stage provides more direct evidence about adding hierarchical aggregation to a block split than the between-system results provide about choosing the split itself.

### Limitations

#### Limits stated by the authors

The authors identify Java as the only language tested. The architecture can in principle accept another abstract syntax hierarchy, and the paper describes language-specific work that would have to precede such an experiment. The splitter needs a visitor for traversing the target language’s AST and applying the intended rules to its constructs. The units chosen for Java, such as grouped statements and extracted blocks, exercise assumptions about the form of a method and what belongs together. A cross-language experiment would be needed to show that an adapted set of rules gives similar benefits.

The authors also point to independent design choices that can affect a summarizer. They give token embeddings, beam search and teacher forcing as examples. Beam search keeps several possible continuations during generation, while teacher forcing concerns supplying the observed preceding tokens during training. Such choices can affect absolute scores or change the conditions under which a structural representation is helpful. The paper’s comparisons give evidence for CAST in its experimental design. The authors leave more extensively controlled comparisons and combinations with other techniques as future work.

The third concern is the quality of the targets. The first Javadoc sentence is a practical source of reference descriptions, and the authors note that it can mismatch the code. An opening sentence can omit behavior that a knowledgeable developer would consider important. This affects both learning and evaluation. During learning, the generator is rewarded for reproducing the details and choices of emphasis found in these sentences. During evaluation, a useful description can be penalized for using a different expression or including information that the reference leaves out. The authors identify better collection of high-quality summaries as a way to address the problem.

#### What follows from the experimental setup

The bounds on the input are narrower than Java alone. The benchmark pairs used by CAST have a parseable method and an associated Javadoc description from which a target can be obtained. The results describe code under those conditions. The experiment gives no score for cases removed by the parser filter. The token preprocessing further narrows the observable surface forms. Normalized literals and split identifiers support many behavior-level descriptions, while tasks requiring exact original names, numeric values or strings would depend on what information could be carried through under a different setup.

A second limit concerns the interpretation of structural preservation. The splitter explicitly records relationships between parts, and the second recursion uses those relationships. The learned vectors remain compressed representations. Mean aggregation treats a fixed collection of child vectors identically whatever their ordering at that node, and max pooling retains extreme component values. The lexical encoder has relative position information, and the decoder can query separate states for different subtrees. Together, these expose richer evidence than a single vector for the entire method. The representation is still evaluated by the description it helps produce, rather than by whether someone can reconstruct every syntactic or semantic distinction from its vectors.

The experiments likewise support particular claims about efficiency. The reported CAST and HybridDrl timings give a practical comparison on Funcom. They do not form a controlled substitution of a full-tree RvNN into an otherwise identical CAST system. Computation, architecture and the representation of the tree differ between the two systems. As a consequence, the measurements show the elapsed time for the reported configurations, while the authors’ account of shorter recursive paths gives a mechanism that could explain part of the difference. The paper does not report direct measurements of gradients demonstrating how much of the timing or score difference comes from easier propagation.

The evidence for the chosen block boundaries also has a particular scope. CodeAstnn supplies a useful contrast because it preserves a separate lexical input and also uses recursion and pooling within subtrees. Its sequential aggregation changes at the same time as the granularity of the split. The ablation within CAST changes aggregation while keeping the split fixed. Reading these together gives a reason to credit the complete representation and more direct evidence for the aggregation stage. The results cannot determine whether the same block boundaries would be best under each alternative aggregator or how much of CAST’s total advantage is attributable to boundary choice alone.

Finally, the human study checks a small random sample of test methods against selected competitors. Multiple judgments per description and shared test methods support comparative scoring on the sample. The criteria still ask raters to judge a short description, and the result does not measure whether a developer completes a maintenance task faster or makes a better decision about modifying code. The significance exception for naturalness against CodeAstnn is part of that evidential picture. The most direct human evidence is the preference observed for CAST’s descriptions under the study’s similarity, fluency and content criteria.

### What came after

There are no documented follow-up studies to trace here. Three questions remain unanswered in the paper: whether the block rules carry over to another language, how much the choice of split points contributes to the gain with aggregation kept constant, and how well the method fares against descriptions gathered expressly to explain code. These are directions the experiments motivate, with Java summarization as the setting in which the authors demonstrated the method.

The released implementation, data and splitting specification make the central design available for further comparisons. The particular contribution a follow-up would need to examine is the combination of local recursion over syntactic parts and a second recursion over their nesting. A future study could retain that representation while changing the decoder or the benchmark, or hold the rest of the system fixed while varying the split. The paper establishes the starting result for such comparisons through its benchmark rankings, component removals and developer assessments.

## Cite

Cite as Ensheng Shi, Yanlin Wang, Lun Du, Hongyu Zhang, Shi Han, Dongmei Zhang and Hongbin Sun. 2021. CAST: Enhancing Code Summarization with Hierarchical Splitting and Reconstruction of Abstract Syntax Trees. Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.18653/v1/2021.emnlp-main.332](https://doi.org/10.18653/v1/2021.emnlp-main.332) · [arXiv 2108.12987](https://arxiv.org/abs/2108.12987)

```bibtex
@inproceedings{shi2021cast,
  title = {{CAST: Enhancing Code Summarization with Hierarchical Splitting and Reconstruction of Abstract Syntax Trees}},
  author = {Ensheng Shi, Yanlin Wang, Lun Du, Hongyu Zhang, Shi Han, Dongmei Zhang and Hongbin Sun},
  booktitle = {Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing},
  year = {2021},
  doi = {10.18653/v1/2021.emnlp-main.332},
  eprint = {2108.12987},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.18653/v1/2021.emnlp-main.332}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
