Elamur Research

Efficient Constituency Tree based Encoding for Natural Language to Bash Translation

Paper · 2022 · Shikhar Bharadwaj and Shirish Shevade

Summary

A person can describe a command-line task in ordinary English without knowing which Bash utility performs it or which options that utility accepts. Translating the description into a command means making those choices and putting the results in an order Bash can interpret. The authors observe that some choices correspond to whole phrases in the request. A phrase specifying the current directory, for example, can supply a command argument, while a phrase describing an inode number can point to an option for selecting files. The paper asks whether making these phrases explicit helps a translator work with a smaller input representation.

The Segmented Invocation Transformer, or SIT, uses constituency parsing to find those phrases. It first replaces details such as file paths and patterns with markers for their types. A constituency tree then shows how words group into phrases. Cutting the tree at a chosen height produces a sequence of short segments. SIT averages the token and position representations inside each segment and sends the resulting sequence to a Transformer encoder. A standard Transformer decoder uses that encoded sequence to generate the command. The decoder can therefore attend to a phrase through a single vector, even when the phrase contains several words.

On the competition version of the NL2Bash corpus, SIT scored 0.438 on the NLC2CMD test metric, averaged over 5 runs. A single member of Magnum, the competition-winning ensemble, scored 0.428. The metric rewards agreement on utility order and flags, incorporates prediction confidence, and leaves arguments unscored. SIT had 9M parameters, compared with 45M for the Magnum system used in the comparison. The authors report a median CPU inference speedup of almost 1.8x in a benchmark that excluded constituency parsing.

The authors also traced command-token predictions back to the input segments using Integrated Gradients, a technique for estimating how input features contribute to a prediction. In a manual review of 100 test examples, positively attributed segments frequently gave enough information to identify a utility or flag. They did so less frequently for arguments, whose literal forms were often hidden by normalization. The analysis also found commands containing utilities or flags that had no clear counterpart in the request. Phrase structure gives the translator useful clues, while some choices still depend on how a task can be carried out in Bash.

Deep dive: Efficient Constituency Tree based Encoding for Natural Language to Bash Translation

How constituency trees help translate English requests into Bash, with a smaller Transformer, higher benchmark scores, and faster CPU decoding. · about 34 minutes to read

The problem and its context

From a description to a command

A shell utility names an operation. Its flags configure the operation, and its arguments can supply such things as a location or a pattern. A user can express these details in a sentence without supplying the shell vocabulary. Conversely, a phrase that is perfectly clear about the desired result may leave open which utilities should produce it. The translator has to recover the requested operation and decide how to express it in Bash. That combination makes the task an instance of semantic parsing, in which an utterance is mapped to a representation of its meaning.

The authors motivate the task through the practical value of the command line. A person familiar with the utilities and their options can express complicated operations compactly and combine utilities when a single operation is insufficient. Learning the interface requires knowing which facilities exist and remembering how to invoke them. An English interface would let someone specify the task in terms they already know. The research problem is to learn the connection between those descriptions and the commands that implement them from examples of the two read together.

The paper calls the English request an invocation. An invocation and its reference Bash command describe the same task at different levels. In the paper’s example involving an inode number and the current directory, the directory phrase specifies where the operation is to take place. The reference expresses that choice with a directory argument. The inode phrase is associated with a flag, and the pattern mentioned by the user supplies an argument for it. The action named by the main verb corresponds to a utility used within the command. The sentence never has to name those Bash components for a reader to understand the task.

This example shows why phrases are useful units to investigate. The separate words in a directory expression can have wide uses across the corpus. Together they may identify a specific location relevant to command construction. Similarly, an operation and the condition that restricts it can both appear in a single sentence and supply different parts of the eventual command. The authors’ manual inspection of training examples suggests that such correspondences occur frequently enough to justify making phrase boundaries part of the translator’s design. The paper calls this the synchronous structure of the task.

The correspondence is partial. The same reference command can contain supporting machinery that the invocation leaves implicit. A phrase can also contribute information to more than one output decision, and the order in which a sentence presents details can differ from the order Bash requires. A translator still needs to learn which components to generate and when to combine them. The proposed architecture gives that learning process a preferred unit for reading the input. The authors introduce no annotated links between particular phrases and command components during training.

How earlier systems represented the task

The paper puts Bash generation in a longer line of work on formal representations of language. Early semantic parsers used hand-written rules and representations such as first-order logic, forms enriched with lambda calculus, and database query languages. Subsequent statistical work sought to learn rules from paired utterances and formal expressions. The authors cite work on learning relaxed categorial grammars and inducing probabilistic grammars from logical forms as examples of the move towards learning from parallel data.

Another line of work used an encoder to read the utterance and a decoder to write the target expression. An attention mechanism let the decoder bring different parts of the encoded input into focus as the output grew. The paper discusses Language to Logical Form with Neural Attention and Latent Predictor Networks for Code Generation in this context. This general way of learning to translate an input sequence into an output sequence made it possible to approach several kinds of formal targets within a common framework.

Some systems gave the output a more explicit structure. Abstract Syntax Networks organized the decoder into modules selected according to the emerging output tree. A Syntactic Neural Model for General-Purpose Code Generation supplied grammar information about the language being generated. Both illustrate how knowledge of the target can shape the generation process. SIT places its structural intervention at the input. It uses the syntactic shape of the English request to decide which tokens to combine before encoding.

For Bash specifically, the original NL2Bash work contributed paired data and an encoder–decoder approach. The paper describes other research on sequence translation, abstract syntax networks, and nearest-neighbor methods on a custom dataset, as well as the development of a command-line assistant. The NLC2CMD competition provided a common setting for comparing systems. Earlier work by the SIT authors drew on descriptions of Bash utilities and abstract syntax trees to produce explanations alongside commands. Those features concerned the commands or information about their utilities. In the authors’ account of earlier Bash translators, the English input still entered as a token sequence without the phrase grouping investigated here.

There was already precedent for using constituency trees on the input side of machine translation and semantic parsing. The paper describes a translation system that accumulated information hierarchically within the Transformer to represent constituency structure. It also discusses a semantic parser that combined constituency and dependency information in a graph and passed that representation to a recurrent decoder. Those approaches used more of the tree or graph during encoding. SIT takes from the tree just enough information to define a partition of the input, then passes the encoder a shorter sequence. That choice connects the linguistic question about useful groupings with the engineering question about how much computation the translator needs.

The method, step by step

The input and the expected output

The procedure starts with an English invocation and ends with a ranked collection of candidate Bash commands. Each candidate carries a confidence score. The training material supplies paired requests and reference commands, giving the translator examples of what belongs on either side. At inference, the reference is unavailable. The system parses the request, forms its segment representations, and builds candidate commands one output token at a time.

The paper describes the parallel dataset as a set of pairs.

D := {(nlc, c)}

Here D is the dataset. The symbol := introduces its definition, the braces indicate a set, and the parentheses group the two members of each pair. The symbol nlc denotes a natural-language invocation from the space I of possible invocations. The symbol c denotes its Bash command from the space C of possible commands.

The predicted command and confidence have their own notation.

(ĉ, δ), with ĉ ∈ C and δ ∈ [0, 1]

The hat on ĉ marks a predicted command, and δ is the confidence assigned to that prediction. The membership sign ∈ says that the prediction belongs to the set C of Bash commands and that the confidence lies in the specified interval. Square brackets include both endpoints, 0 and 1. In the task definition, the predicted command is meant to carry out the requested operation. In the experiment, an evaluation function awards credit using selected features of the reference command.

From an English request to ranked Bash candidates

The steps in order.

From an English request to ranked Bash candidatesStep 1: Normalize paths and patterns1. Normalize paths and patternsStep 2: Parse the English request into a constituency tree2. Parse the English request into a constituency treeStep 3: Cut the tree into ordered phrase segments3. Cut the tree into ordered phrase segmentsStep 4: Add token and position embeddings4. Add token and position embeddingsStep 5: Average embeddings within each segment5. Average embeddings within each segmentStep 6: Encode the segment sequence6. Encode the segment sequenceStep 7: Decode and rank candidate commands7. Decode and rank candidate commands

Normalize the request and locate its phrases

File paths and regular expressions can be essential to a request, even when their precise spelling contributes little to identifying the operation. The preprocessing used in the study abstracts away those surface forms. The invocation side replaces patterns and paths with markers for their types. Preprocessing also applies to the command side and is shared across the systems in the accuracy comparison. The authors use the natural-language toolkit and Bash parser distributed by the NLC2CMD organizers for this part of the procedure.

Next comes the parse of the normalized English. A constituency tree represents a sentence as phrases nested inside larger phrases, with the individual tokens at the leaves. A node can cover a group of words that functions together, such as the expression for the directory in which an operation is to occur. Other nodes cover smaller groups within that expression, and nodes farther up the tree can cover the expression along with the construction it modifies. The authors obtain these trees with the Stanford CoreNLP parser.

The algorithm needs a single ordered sequence of segments, so it decides which subtrees to keep. It measures a node’s height by counting the edges on the longest path from that node down to a leaf it contains. A leaf is at the bottom of this scale. For an internal node with branches of different depths, the deepest branch determines the height. The decision therefore depends on tree shape. A height limit does not prescribe a fixed number of words per segment.

The traversal starts at the top of the tree and explores it depth first, visiting branches from left to right. When it reaches a node whose height is strictly below the chosen threshold, it keeps the whole subtree at that node. It reads the tokens at the leaves as one segment and continues with the rest of the tree. If the height is at or above the threshold, it descends to the children and applies the same decision there. Thus a phrase that passes the test is taken as a unit before any of its possible subphrases are considered for separate segments.

The left-to-right traversal preserves the order of the original tokens. Once a subtree is retained, its leaves are accounted for and the traversal does not subdivide them. A segment can be a single word or a group of words. The cut discards the internal hierarchy of each selected subtree once its leaves have been gathered. It also discards the higher branches that linked one selected subtree to another. What survives for the encoder is the grouping and the order, instead of a new set of embeddings for all the nodes in the tree.

The authors selected a height threshold of 4 using validation performance. A change in the threshold can change how much of an expression is bundled together. Accepting nodes higher in the tree can put more words into a joint representation, which leaves a shorter sequence for the encoder. Accepting only lower nodes can retain more separate units for attention. The chosen threshold fixes how the translator makes that tradeoff on the reported benchmark.

Represent the segments as vectors

The paper writes the tokenized invocation as an ordered list.

nlc = [t₁, t₂, …, tₙ]

Here nlc is the input invocation. Each t with a subscript is a token at the indicated position, and n is the length of the invocation in tokens. The subscripts start at 1, and the ellipsis stands for the intervening tokens. The square brackets in this expression indicate an ordered sequence.

The output of the tree cut is another ordered list.

[s₁, s₂, …, sₖ]

Each s with a subscript is a segment at the indicated place in the input order. The symbol k counts the segments, the first index is 1, and the ellipsis covers the remaining positions between the first and last entries. A segment gathers a contiguous span of the token sequence because its leaves come from a single selected subtree.

The paper expresses the membership of an individual segment as follows.

sᵢ = [tⱼ, tⱼ₊₁, …, tⱼ₊ₙᵢ₋₁]

Here i indexes a segment, j indexes the first token in that segment, and nᵢ is its token count. The subscript j + 1 advances by one position in the invocation. The last subscript, j + nᵢ − 1, identifies the final token in the span. The ellipsis denotes the tokens between those displayed positions.

The counts of the segment lengths have to account for the whole input.

∑ᵢ₌₁ᵏ nᵢ = n

The summation sign ∑ adds the lengths nᵢ of the segments. Its index i begins at 1 and ends at k, the number of segments. The result n is the number of input tokens. The equality captures the absence of skipped tokens or overlap in the partition.

A token needs a numerical representation before it can go into the encoder. SIT gives it a token embedding, a vector associated with its identity. It also gives it a sinusoidal positional embedding, a vector determined by where the token occurs in the invocation. The two vectors are added at the token level. This happens while each token still has its own position, so the vectors fed into a segment’s average include position information from the original sequence.

The averaging layer takes the arithmetic mean of the resulting vectors for all the tokens in each segment. Each coordinate in the segment vector is the average of that coordinate across the segment’s tokens. All the token vectors in a segment carry equal weight in this operation. There is no learned selector inside the averaging layer. The external parser determines the groups, and a simple calculation supplies a joint representation for each of them.

There are k vectors at the end of averaging, each with the same dimensionality as a token embedding. A singleton segment passes along the vector for its one token. A longer phrase contributes one vector of the same width. The order in which these segment vectors arrive comes from the tree traversal. The design retains some position information through the input vectors and reduces the decoder’s eventual access to individual words, since it will receive the segment-level encoder representations.

A reader can follow the paper’s directory example through these stages. If the relevant directory expression falls inside one selected subtree, its words contribute jointly to a segment vector. During encoding, that vector can acquire context from other segments, such as the expression for the operation or the condition on the files. When the decoder reaches a position where it needs to supply the location, it can attend to the encoder representation associated with that part of the request. The architecture permits such a correspondence. The training data and learned parameters determine whether the decoder uses it.

Encode the request and generate candidates

After pooling, SIT applies the encoder design from Attention Is All You Need. The encoder’s self-attention lets a segment representation incorporate information from the other segments. A location phrase might be relevant to the main operation, a condition on the operation, or another aspect of the request. Its grouping does not settle that relationship. The encoder processes the entire sequence of segment vectors so that each can be interpreted in context.

The decoder uses the standard Transformer arrangement. Its self-attention processes the output prefix, the command tokens generated so far. Its cross-attention consults the encoded input as it predicts a continuation. In attention terms, the decoder supplies a query at the current output position. It compares that query with keys derived from the encoded input to obtain weights, then uses those weights to combine the corresponding values. The keys determine how strongly each source position is consulted, and the values supply the information gathered from those positions. Because SIT has already grouped the invocation, its source positions are segments.

The authors use an embedding dimension of 256 for SIT. The encoder has 3 layers, with 4 attention heads in each layer. The decoder has 6 layers and 8 heads per layer. Attention heads allow a layer to compute several sets of attention weights and combine their results. The feed-forward sublayers in both the encoder and decoder have dimension 1024. Those sublayers process the representation at each position after information has been exchanged through attention.

SIT learns by back-propagation using cross-entropy, which rewards assigning high probability to the reference output tokens. The authors apply label smoothing of 0.1. Smoothing modifies the training targets so that the entire probability mass is not placed on the reference token. The training batch size is 499 tokens, and gradients are accumulated over 150 batches. Accumulation lets information from successive batches contribute to the same parameter update. The tree cut happens before the learned encoder. The reference command supervises the eventual token predictions, with no separate target telling the translator which segment to consult at each output position.

The translators use beam search at inference. Beam search maintains several candidate prefixes and extends them as generation proceeds, which keeps more than the locally preferred continuation in play. The authors use 10 beams and return the top 5 predictions. For evaluation, the predictions at the head of the ranking receive confidence 1, with the number receiving that treatment chosen on the validation set.

δ = exp(beam_score) / 2

Here δ is the confidence used for a returned candidate outside the group assigned full confidence. The name beam_score denotes the score assigned to that candidate by beam search, exp is the exponential function, and / 2 divides its result by 2. The paper uses p for the number of leading candidates given confidence 1. Each system has its own validation-tuned p, and the rule in the block applies to the remaining 5 − p candidates, where 5 is the size of the returned list. The same kind of confidence policy is used across the comparisons.

Why fewer source positions can save decoding time

The paper analyzes cross-attention during one decoder step. With the token sequence compressed, the decoder has a key and value for each segment rather than for each original input token. Suppose the representations have dimension d and the input has k segments. In the paper’s single-head analysis, source representations can be arranged in a matrix with k rows and d columns. Multiplying by a projection with d rows and d columns forms the projected values. Projecting the decoder state into a query instead involves just one input vector of dimension d.

O(kd²)

The notation O describes the order of growth in the work being counted. Here k is the number of source segments and d is the embedding dimension. The exponent ² squares the dimension, accounting for a dense projection of width d applied across the source positions. The paper gives this cost for forming the value matrix. Forming the keys uses a projection of the same shape and has the same order of growth.

O(d²)

Here O again indicates the order of growth, and d² is the square of the embedding dimension. This expression is the cost of projecting a single decoder vector to get the query. The number of source positions does not enter that projection.

Next the decoder compares the query with every key so that it has a score for every segment. A softmax converts the resulting scores into weights. For each score, the key–query comparison operates on vectors of width d. The softmax operates over the resulting list of k scores.

O(kd + k)

In this expression O marks the order of growth, k counts the segments, and d gives the vector dimension. The product kd represents work for the key–query comparisons. The added k represents work for normalizing the list of scores.

O(kd)

Here O is the order of growth, k is the number of values to aggregate, and d is the width of every value. This is the cost of forming the weighted combination once the attention weights are available. The paper combines the steps and absorbs lower-order work into the overall expression.

O(kd² + d² + kd)

The notation O summarizes the growth of work in the cross-attention calculation for the step. The first term, kd², accounts for the source projections. The next, d², accounts for the query projection. The term kd accounts for comparing the query with the keys and aggregating the values, with the softmax cost absorbed at this level of the analysis. The two variables are still the segment count k and the embedding dimension d.

O(k) for segments, O(n) for tokens

Here O gives the order of growth in the length of the encoder sequence when d is held fixed. The symbol k counts segment positions in SIT and n counts token positions in a Transformer that encodes the full input. The saving comes from using a smaller sequence when a cut groups several tokens into a segment. Both forms are linear in the number of positions available to cross-attention.

The decoder repeats its attention operations as it extends a command, so a reduction in source length can matter at successive output steps. The calculation concerns one part of inference. It gives a reason to expect less cross-attention work with segments and leaves the time needed to parse the sentence outside its accounting. The experiments measure elapsed time for the translation systems at a specified stage of their pipelines.

Experiments and results

A rotating train, validation, and test split

The authors use the NL2Bash data supplied for the NLC2CMD competition at NeurIPS 2020. The dataset contains approximately 10k English request and Bash command pairs drawn from Stack Overflow. The paired commands cover over 100 Bash utilities. That variety matters for the benchmark. A system must choose among many utilities while also determining how a particular utility should be configured and whether the desired operation calls for several utilities.

The data are partitioned into 5 folds. For each run, the authors hold out one fold and divide it equally between validation and testing. They pool the other four folds for training. The held-out fold changes across the 5 runs, so the reported test result is an average over runs with different partitions. Validation provides a place to choose settings such as the constituency cut threshold and the confidence policy before reporting the corresponding test scores.

The accuracy results summarize these runs with a mean and standard deviation. The mean describes the benchmark score across the runs, and the standard deviation describes the spread of the run scores around that mean. This setup provides evidence about performance under the chosen split procedure. The reported score also depends on how the competition defines a good candidate list, which differs from checking whether a single predicted command exactly matches the reference string.

What the competition metric rewards

A Bash command can express a useful portion of a request while differing from the reference in some details. It can also share many tokens with the reference and still use the wrong utility. The competition organizers therefore proposed a task-specific score. The paper discusses it in relation to the BLEU score, exact match, and template accuracy. BLEU measures forms of sequence overlap used in translation evaluation. Exact match requires the predicted expression to coincide with the reference. The NLC2CMD score instead checks which utilities occur in which slots and how their flags agree.

Under this metric, each utility is compared with the reference utility at the same position. If the utilities agree, the score takes the sets of flags associated with them into account. A shared flag supports the prediction, while missing or redundant flags reduce the flag contribution. If the utilities disagree, the position receives a penalty. The score weights the result by the candidate’s confidence. Arguments, including the paths and patterns abstracted during preprocessing, are outside the scoring rule.

To describe the calculation, the paper treats each invocation as having a single reference command and evaluates a set of up to 5 candidates.

A(nlc) = {q | q = (ĉ, δ)}, with |A(nlc)| ≤ 5

The symbol A denotes the translation system in the metric’s notation, and A(nlc) is the collection it returns for the invocation nlc. The braces indicate the collection and the bar inside them means “such that.” Each element q comprises a predicted command ĉ and a confidence δ. The vertical bars around A(nlc) count the returned candidates. The inequality ≤ bounds that count by 5.

The length used to normalize utility comparisons is the longer of the two utility sequences.

T = max(|U(c)|, |U(ĉ)|)

Here T is the number of utility positions used for normalization. The function U extracts the sequence of utilities from its command argument. The symbols c and ĉ refer to the reference and predicted commands, respectively. The vertical bars give the lengths of their utility sequences, and max chooses the larger length. Using the longer sequence makes a utility that appears on just one side relevant to the comparison.

The reference and prediction can also have different numbers of flags for a utility position.

Nᵢ = max(|F(U(c)ᵢ)|, |F(U(ĉ)ᵢ)|)

Here i indexes a utility position. The expressions U(c)ᵢ and U(ĉ)ᵢ refer to the utilities at that position in the reference and the prediction. The function F gives the flag set of the corresponding utility occurrence in its own command. The vertical bars count flags in a set, and max takes the larger count. The quantity Nᵢ is the denominator for the flag adjustment at position i.

S(q) = (δ / T) × ∑ᵢ₌₁ᵀ [
  I(U(ĉ)ᵢ = U(c)ᵢ) × (1 / 2) ×
    (1 + (2 × |F(U(ĉ)ᵢ) ∩ F(U(c)ᵢ)| − |F(U(ĉ)ᵢ) ∪ F(U(c)ᵢ)|) / Nᵢ)
  − I(U(ĉ)ᵢ ≠ U(c)ᵢ)
]

The function S scores one candidate q. The quantity δ is that candidate’s confidence, and T is the longer utility sequence length. The summation runs over utility positions i from 1 through T. The function I is an indicator, taking value 1 when its condition holds and 0 otherwise. The first condition tests equality between the predicted and reference utility at that position. The second uses ≠ to test disagreement and subtracts the corresponding penalty. In the flag calculation, ∩ gathers flags present in both sets and ∪ gathers flags present in either set. The bars count the flags in those sets. Multiplication by 2 weights the shared count, subtraction removes the union count, and division by Nᵢ scales the adjustment by the larger flag count. The constants 1 and 1 / 2 give the matching-utility term its base and scale. The outer multiplication averages the contributions over utility positions and applies the candidate confidence.

This expression explains why utility identity and utility order both matter. When a position matches, flag agreement can change how much credit that position earns. A flag appearing in just one command expands the union without expanding the intersection. When the utilities at a position disagree, the mismatch penalty applies and the flag comparison contributes no reward there. The paper gives the flag adjustment in terms of Nᵢ and leaves the zero-denominator convention for the case of two empty flag sets implicit in its printed presentation.

Finally, the candidate scores are combined into the score for the invocation.

Score = max{S(q) | q ∈ A(nlc)}                 if some S(q) > 0
Score = (1 / |A(nlc)|) × ∑q ∈ A(nlc) S(q)     otherwise

Here Score denotes the result for the invocation nlc. The function S gives the score of an individual candidate q, and A(nlc) contains all returned candidates. In the first branch, the maximum is taken over candidates belonging to that collection, as indicated by ∈, and the branch applies when at least one candidate’s score is greater than 0. The bar in the maximum specifies which candidates are eligible. In the second branch, the summation adds their scores and division by |A(nlc)|, the collection’s size, takes the mean. The constant 1 in the reciprocal supplies that averaging factor.

A good match among the candidates can therefore determine the result even if other candidates score poorly. When every candidate receives a nonpositive score, each contributes to the average. Confidence enters before the choice of branch because it is part of the single-candidate score. The reported test score reflects the candidate list and its confidences, and ranges from -1 to 1 with higher values indicating better performance. Its agreement criterion is the utility-and-flag structure that the competition set out to measure.

Which systems were compared

The main comparison is with Magnum, the winning NLC2CMD entry. The original entry combines several Transformers trained with different random seeds and batch sizes. The paper benchmarks a single member of that ensemble against a single SIT system. Magnum’s embedding width is 512. Its encoder and decoder each have 6 layers and 8 attention heads per layer. The reported schedule calls for 2,500 training steps with a warm-up, 14,000 tokens per batch, and gradients accumulated across two batches. In addition to representing the source differently, the two systems have different widths, encoder depths, and training settings.

The recurrent Seq2Seq baseline is an attention-based encoder–decoder of the kind described in Neural Machine Translation by Jointly Learning to Align and Translate. Its encoder uses two bidirectional LSTM layers of dimension 256. Bidirectionality lets those layers read the token sequence in both directions. Its decoder uses two LSTM layers of dimension 256, going forward through the output and attending to the encoded input as it generates.

Explainable-NL2BashAST adds an explanation objective and uses the abstract syntax structure of Bash. The authors run the implementation accompanying the earlier work. It supplements the paired corpus with descriptions of Bash utilities. Its inclusion shows how SIT compares with another structurally informed translator whose design choices serve a different purpose. The earlier system represents command syntax and produces explanations. SIT uses the syntax of the English request to form a shorter source sequence.

The remaining comparisons use T5 and CodeT5. The authors adapt the T5 checkpoint from the text-to-text approach described in Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. CodeT5 was pretrained on programming languages for tasks involving code understanding and generation. For both systems the authors prepend a short translation instruction to the invocation and perform fine-tuning on the competition data. They try the small and base variants of each and report the small variants, which performed better in their tests.

T5-small and CodeT5-small are trained with batches of 32 examples, and the authors use validation performance to choose the number of epochs. Their vocabularies are based on subword tokenization, which can represent a word using multiple units. The other systems build vocabularies from the competition corpus using whitespace-separated words. These differences affect what each system predicts at an output step and how many steps a command can occupy. The comparison tests each translation approach with the vocabulary and training choices the authors specify for it.

Translation scores

NLC2CMD competition scores on the NL2Bash test splits

SIT has the highest mean score, followed by a single member of Magnum.

NLC2CMD competition scores on the NL2Bash test splitsT5-small: 0.316T5-small0.316CodeT5-small: 0.355CodeT5-small0.355Seq2Seq: 0.362Seq2Seq0.362Explainable-NL2BashAST: 0.390Explainable-NL2BashAST0.390Magnum (single member): 0.428Magnum (single member)0.428SIT (this paper): 0.438SIT (this paper)0.438
The numbers
System or settingNLC2CMD competition score
T5-small0.316
CodeT5-small0.355
Seq2Seq0.362
Explainable-NL2BashAST0.390
Magnum (single member)0.428
SIT (this paper)0.438

SIT’s mean NLC2CMD test score is 0.438 with a standard deviation of 0.018 across the runs. Magnum’s single-member comparison has a mean of 0.428 and a standard deviation of 0.010. These are the highest two means in the reported experiment. Explainable-NL2BashAST scores 0.390 with a standard deviation of 0.012. Seq2Seq scores 0.362 with a standard deviation of 0.012. CodeT5-small scores 0.355 with a standard deviation of 0.025, and T5-small scores 0.316 with a standard deviation of 0.021.

The authors suggest that vocabulary contributes to the relative performance of the pretrained translators and the recurrent baseline. The from-corpus vocabulary restricts the words available to the recurrent system, while T5 and CodeT5 retain their existing sub-word vocabularies. The paper relates this hypothesis to the competition winners’ observation that reducing vocabulary size helped on the task. CodeT5’s higher score than T5 is an observed comparison between their reported configurations. The role of vocabulary size or code pretraining in that comparison remains a proposed explanation.

The authors also offer an account of the result for Explainable-NL2BashAST. The design is intended for commands that use one utility, and the paper describes the output sequence as twice the length of a Bash command. A longer sequence makes beam search do more work as it generates and ranks prefixes. This offers a possible explanation for why the system trails Magnum on the benchmark. The reported experiment compares the full systems and leaves the individual contributions of the output representation and explanation objective unresolved.

SIT has 9M parameters. Magnum, as used here, has 45M. The paper reports the comparison as a 5x gain in parameter efficiency and associates it with SIT’s smaller encoder. A smaller parameter count means fewer learned values to store. The paper uses that count to motivate an expectation of lower resource demands for deployment. Runtime memory use and power consumption are separate quantities from parameter count.

CPU inference timing

The authors time inference on 1K test examples on a 6-core Intel Core i5-10400 CPU. They use the benchmarking utility included in PyTorch. For each thread setting, they repeat the measurement 25 times and report the mean, median, and interquartile range of the timings. The mean averages the repeats, the median describes their middle, and the interquartile range describes the spread of the middle portion. The repeated trials help distinguish typical elapsed time from variability across executions.

Median CPU inference time on the 1K-example NL2Bash test batch with 6 threads

SIT completes the timed inference stage sooner than a single member of Magnum.

Median CPU inference time on the 1K-example NL2Bash test batch with 6 threadsMagnum (single member): 83.89Magnum (single member)83.89SIT (this paper): 45.83SIT (this paper)45.83
The numbers
System or settingseconds
Magnum (single member)83.89
SIT (this paper)45.83

With 6 CPU threads, the mean for Magnum is 84.80 seconds and the mean for SIT is 45.68 seconds. Their interquartile ranges in that setting are 3.83 seconds and 1.84 seconds, respectively. With 1 CPU thread, the median is 144.51 seconds for Magnum and 59.22 seconds for SIT. The medians with 3 threads are 92.17 seconds for Magnum and 47.62 seconds for SIT. SIT has lower reported median times throughout the thread settings the paper tests. The authors describe the median speedup as nearly 1.8x.

These timings begin after constituency parsing for SIT. The measured time is for translation from the already prepared input. That boundary connects the test to the decoder analysis, which counts the work of looking up source information during generation. It also means that the timing represents one stage of the interface a user would experience. A request arriving as raw English would require the omitted parsing step before the translation stage could benefit from the shorter sequence.

Profiling helps explain where inference time goes within that stage. The authors find that the decoder takes substantial time because it generates successive output positions. They list building the self-attention and cross-attention matrices using keys, queries, and values as one of the most time-consuming tasks. The source compression directly reduces the number of keys and values available to cross-attention. Differences in overall architecture can affect the rest of the runtime as well, so the observed speedup is a measurement of the compared systems instead of a measurement of the averaging layer alone.

What the ablations show

The paper reports no controlled ablation that removes or replaces constituency-derived segmentation while holding the architecture fixed. Its additional evidence comes from runtime profiling and an attribution analysis that checks where a trained SIT system draws support for its output.

How the attribution test works

The attribution experiment asks whether the decoder’s predictions depend on segments a reader would associate with the corresponding command components. The authors use Integrated Gradients. The method looks at how a prediction changes in response to small changes in its input representation. It accumulates this information along a path from a baseline input to the actual input. The score for a segment is thus tied to a change from a chosen reference condition, with the trained translator held fixed throughout the calculation.

In this experiment, the reference condition is a sequence of padding tokens represented by zero vectors. The path runs in a straight line through the embedding space from that baseline to the actual invocation. Points along the path are intermediate vector inputs to the translator. They serve to estimate how contributions accumulate across the path. The authors use 5K steps to approximate the integral, citing the nonlinearity of the architecture. They set negative attributions to zero for their alignment inspection, so the displayed heatmaps highlight positive contributions.

The heatmaps place invocation segments along one axis and command tokens along the other. A positive entry indicates that the attribution method assigns support from the given segment to the prediction of the given output token. A prominent entry can suggest an interpretable connection. The manual analysis asks a stricter question about readability. If a person looks only at the positively attributed segments for a component, do those segments give enough information to infer that the component should appear? Mere relatedness between an input phrase and an output component is insufficient under that criterion.

The first illustrated example concerns loading a script located alongside the running script. The utility that loads the script is associated with the part of the invocation that describes loading it. The output also contains a way to derive the containing directory. The relevant prediction receives positive attribution from segments referring to the folder and its location. The example shows how a command token can draw on more than one segment when a user describes a location indirectly.

Another example concerns a recursive change of ownership and group. The recursive flag receives positive attribution from the word that expresses recursion, a correspondence the authors judge correct. Some positive attribution also falls on a segment involving normalized patterns, which provides a less plausible explanation for that flag. The same example illustrates why the ownership utility fails the manual test. The positive evidence includes the phrase about the owner and group, but the segment that expresses changing them receives no positive attribution for the utility. Information about who or what is involved leaves the action itself open.

The authors count the recursive flag as correctly attributed in that example, even with the additional questionable positive contribution. Their test asks whether a reader can infer the presence of the component from the positive evidence. Its result can therefore be favorable while the alignment includes extraneous segments. The ownership utility shows the complementary case. A segment can be relevant to the topic of the output and still fail to justify the actual operation. Both observations help explain what the component-level counts capture.

Where the correspondences hold

The authors manually examine 100 randomly sampled examples from the test set. They identify 129 utility occurrences and judge 94 of them correctly attributed, or 72.87%. For flags, 110 of 160 are correctly attributed, or 68.75%. For arguments, 84 of 244 are correctly attributed, or 34.43%. Each rate is calculated within its component class and describes whether the positive input segments pass the authors’ manual criterion. These rates are separate from the competition score.

Utilities and flags more frequently have interpretable attributions under this criterion than arguments. The authors connect the lower rate for arguments to normalization. A path or pattern in the original request may be a distinctive piece of evidence for the corresponding command argument. After abstraction, the attribution procedure can highlight a segment containing a type marker, while the output slot may require a more specific association. The result reflects the representations used in this experiment. It leaves open how well literal argument identities could be aligned in a system that retained them.

The authors also identify cases where the requested result requires utility choices that the user leaves implicit. A reference command can include a utility that transforms the output of another utility through a pipe, even when the request describes only the final result. An input segment may express the desired transformation without explicitly calling for that additional utility. Certain flags that combine conditions also lack a clear stand-alone phrase in the invocation. The decoder must learn conventions for implementing the request that go beyond matching each segment with a visibly corresponding command component.

Taken together, the qualitative examples and the sample counts establish that interpretable phrase-to-component associations occur in the trained system and show where the pattern breaks down. They answer a different question from the timing profile. The attribution results concern the relationship between the output and particular pieces of the source. Profiling concerns which computations consume time. A controlled comparison with other kinds of segmentation would be needed to measure how much of either reported advantage specifically depends on constituent boundaries.

Limitations

Limits the authors identify

The authors identify constituency parsing as a bottleneck for realizing the full efficiency of the approach. The timing comparison excludes the Stanford CoreNLP step. For an interface that starts with a new raw request, that step is part of the work. The comparison establishes that the stages timed for SIT run faster than the corresponding Magnum stages under the reported CPU setup. The total time from English input to proposed command remains unmeasured. The authors suggest investigating faster parsers and cite parsing work with throughput around 1K sentences per second. That figure refers to the cited parsing work, while the paper’s experiments use CoreNLP.

The authors also scope their investigation to Bash as the target representation. They expect some of the same structure in tasks such as translating English to SQL, where a phrase might supply a condition or describe another part of a query. The paper leaves applying the method to SQL as future work. Whether a tree cut preserves the right information in such a task depends on how the target components relate to the source phrases. The Bash benchmark supplies no SQL accuracy or runtime result.

A further limit appears in the authors’ attribution analysis. Some command components are implied by the way a result is achieved and have little direct alignment with individual segments. Utilities introduced to transform an intermediate result and flags introduced to represent a logical combination are examples. This makes the paper’s proposal a way of favoring useful local groupings, with the rest of the translation still learned from whole examples. The authors’ observations show which parts of the command are harder to explain through a direct phrase correspondence.

Limits visible in the evaluation

The test metric measures utility order, flag agreement, and candidate confidence. A command with the wrong path or pattern can receive credit for its utilities and flags. The use of a single reference also gives the score a particular implementation of the task to check against. A different valid implementation that uses different utilities or arranges them differently can disagree with the reference structure. These properties matter when interpreting the headline score. It measures the competition’s chosen features of translation quality. The paper leaves execution success and preservation of literal arguments unmeasured.

The candidate rule further shapes what the score means. The best positive candidate can determine the score for an invocation, and the list is evaluated using confidence assignments tuned on validation data. The result therefore concerns a ranked set under the competition scoring procedure. A setting in which a user acts on the first suggestion would ask a different evaluation question. The reported means also incorporate a different data partition in each run. The standard deviations describe variation in that setup, and the paper supplies no paired significance analysis for the difference between SIT and the single Magnum member.

The systems used for the efficiency comparison have different widths and numbers of encoder layers, along with different training arrangements. This is relevant to both the timing and the accuracy result. Shortening the encoder sequence reduces the number of source positions available to attention, as the complexity analysis shows. The smaller network also changes how much work is done per position. The benchmark demonstrates the combined result of SIT’s design choices. It leaves open how a full-token Transformer matched to SIT in width and depth would score or how quickly it would run. It likewise leaves performance relative to the complete Magnum ensemble open.

The segmentation itself compresses the source in a specific way. After position information is added, averaging produces a single vector for an entire span. Subsequent decoder attention addresses that vector through the encoder, so words pooled into the same segment cannot be selected independently as source positions. This can be helpful when a phrase behaves as one unit. It can make distinctions harder to recover when separate words within a segment serve different purposes. The paper reports the threshold selected on validation data and does not characterize accuracy or speed across a range of cuts. It also supplies no comparison with partitions of similar length obtained without a constituency tree.

The parser is another dependency of this design. A different parse can alter which nodes satisfy the cut condition and thereby change the input sequence reaching the encoder. All reported experiments use the same constituency parser. The study does not measure how often parsing errors change the chosen segments, how those changes affect translation, or whether switching to a faster parser preserves benchmark performance. Those questions are separate from whether the parser runs quickly enough for an application.

Finally, the attribution results rely on the selected zero-vector baseline, the clipping of negative scores, and the authors’ manual criterion. Positive attributions can show that some source segments support an output in a way that a reader recognizes. The method leaves inhibitory effects outside the displayed analysis. It also leaves open what would happen to the generated command if a segment were changed or removed. The interpretable examples and manual counts give evidence of correspondence within the trained system. They do not isolate the effect of tree-derived pooling during training.

The resource findings have a similarly specific scope. Parameter count is directly reported, and the CPU benchmark measures elapsed inference time at the chosen stage. Operational memory and energy were motivations for a smaller system. The paper does not measure either in a running interface. End-to-end cost would depend on the parser as well as the encoder, decoder, and search procedure.

What came after

There is no later citing work to trace here. The authors close with two directions for extending the research. One is to test whether English requests for SQL queries contain useful phrase-to-component correspondences, then measure whether pooling those phrases helps generate queries. The other is to replace the constituency parser with a faster one and assess the efficiency of the complete translation pipeline. The Bash experiments establish the starting point for both questions: the system can use a sequence of syntactically selected phrases to generate competitive command candidates, and its timed translation stage benefits from operating on that shorter representation.

Cite

Cite as Shikhar Bharadwaj and Shirish Shevade. 2022. Efficient Constituency Tree based Encoding for Natural Language to Bash Translation. Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2022.naacl-main.230

@inproceedings{bharadwaj2022efficient,
  title = {{Efficient Constituency Tree based Encoding for Natural Language to Bash Translation}},
  author = {Shikhar Bharadwaj and Shirish Shevade},
  booktitle = {Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies},
  year = {2022},
  doi = {10.18653/v1/2022.naacl-main.230},
  url = {https://doi.org/10.18653/v1/2022.naacl-main.230}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bharadwaj-2022-efficient-constituency-tree-based-encoding/