Explainable Natural Language to Bash Translation using Abstract Syntax Tree
Paper · 2021 · Shikhar Bharadwaj and Shirish Shevade
Summary
A person can know what they want the shell to do without knowing which Bash utility performs the task or which options it needs. Looking up the answer can be difficult for the same reason. The useful information may be in a manual the person has yet to identify. The authors study whether a translation system can turn a plain-language request into a Bash command and show which parts of the documentation support its choice of utility. They evaluate this approach on a filtered command benchmark and examine the explanations it produces for individual predictions.
The translator generates an abstract syntax tree, a representation that records the parts of a command and their relationships. Each node separates a category, such as utility or option, from the specific item that fills that role. The system generates the category first. When the next item is the name of a utility, it can favor candidates whose documentation resembles the request. The authors adapt a Transformer to preserve information about depth and parentage while it generates the tree as a sequence. The resulting tree can then be converted to Bash.
The documentation comparison also supplies the explanation. The same learned filters scan the request and the utility descriptions for short spans. A filter can respond strongly to spans with a related meaning even when their words differ. The authors trace strong contributions to the similarity score back to their locations in both texts. They display those locations in an alignment matrix, where a highlighted region connects part of the request to part of the documentation for a predicted utility. The alignment addresses the utility choice, which is one part of producing a command.
On the filtered NLC2CMD data, the complete system scores 0.651 ± 0.017 on the competition metric across 10 test runs. It scores above the fine-tuned T5 and attention-based Seq2Seq baselines, while a single system from the winning Magnum ensemble has the highest reported mean, 0.685 ± 0.027. Removing any of the proposed components lowers the mean test score. The largest drop comes from removing Parent Attention, which gives an explicit role to a node’s parent during generation. The benchmark credits utility and option choices while ignoring command arguments. The paper’s examples show how the documentation matches can be inspected, and its experiments measure the quality of the command predictions under that scoring rule.
Deep dive: Explainable Natural Language to Bash Translation using Abstract Syntax Tree
How Bash syntax trees and manual pages help translate English requests into shell commands and explain why particular utilities were suggested. · about 37 minutes to read
The problem and its context
From a desired action to a shell command
A Bash command expresses a task in a form the shell can act on. An English request expresses the outcome the person has in mind. The distance between these descriptions involves several decisions. A utility has to be selected, its options have to be chosen, and the objects it operates on have to be supplied in the appropriate places. A request to change ownership throughout a directory, for example, identifies an operation and gives it a scope. The Bash expression encodes the operation through the utility and the recursive scope through an option. Someone unfamiliar with the utility has to discover both pieces.
The authors describe a difficulty that arises before the manual can help. Documentation is generally organized around the utility, while the person begins with a description of a task. Even after the relevant entry has been found, the person has to locate the lines that describe the operation they need. The paper points to lookup tools such as man, apropos and info, and notes earlier criticism of how formal and difficult to read manual pages can be. In the authors’ account, the obstacle for a novice is finding the appropriate documentation and relating its wording to the request.
This motivates two related outputs. The system proposes commands with scores that express their confidence. It also identifies parts of the manuals that contributed to its assessment of the utilities in those commands. A command can tell a reader which utility was selected. A match between the request and the documentation can help the reader see why that utility was considered relevant. The authors suggest that such evidence might help users judge the proposal and learn what the utility does.
The distinction matters because producing a command and explaining its choices use different evidence. Examples of requests paired with commands tell the translator what outputs have been associated with certain wording. Documentation adds a description of what a utility does. A later section of the paper shows how the system can point to phrases in that description. The proposed explanation is thus tied to the evidence used by one part of the translator. Its scope follows from which choices that part of the system influences.
What earlier approaches supplied
The paper places shell translation in a wider line of work applying natural language processing to source code. It names work on generating code, identifying bugs, describing programs and translating between programming languages. These applications give text-processing systems different tasks depending on whether code is the input, the output or both. Source-code summarization is an example with the direction reversed from Bash generation. The system starts with code and attempts to describe it. The Bash task starts with a description and attempts to produce code. A Transformer-based Approach for Source Code Summarization
Closer to Bash translation, the authors discuss the corpus associated with NL2Bash and the Natural Language Context to Command competition, called NLC2CMD. The corpus supplies paired requests and commands. The competition gives systems a common task and a scoring scheme that distinguishes utility choices from the choices of options attached to them. The paper discusses a recurrent encoder–decoder submitted as a baseline for the competition and identifies the winning Magnum approach as an ensemble of Transformers. The authors also mention grammar-guided and retrieval-based approaches to shell translation. NL2Bash
An encoder–decoder has one part that represents the input and another that produces the output incrementally. In the recurrent approach discussed by the authors, attention lets the decoder draw on different parts of the input as it produces different parts of the command. The competition winner illustrates a different use of attention, through the Transformer architecture. The paper treats these approaches as predecessors for the translation task. Its proposed documentation alignment answers a separate question about which phrases from an external description supported the utility choice. Neural Machine Translation by Jointly Learning to Align and Translate · Attention Is All You Need
Earlier work also shaped the decision to represent program structure explicitly. The authors describe a general code-generation approach that uses a grammar to capture the syntax of the target language. Their Bash pipeline uses a parser to obtain trees from the training commands and supplies structural information inside a Transformer. It therefore gets target syntax information from the parsed examples and their representation. The paper also discusses work that devised position encodings for binary trees, work combining code structure with code context for summarization, and work presenting program trees to Transformers for code completion. These comparisons concern ways of exposing structure to the learning system. A Syntactic Neural Model for General-Purpose Code Generation
The authors identify a more direct influence on Parent Attention. Relative attention gives the mechanism that compares positions access to information about a relationship between those positions. In their Bash decoder, the relevant relationship is parentage in a syntax tree. The authors also draw on text convolution, where a filter is applied to successive short spans, and cite earlier analysis of how such filters respond to spans with related meanings. Relative attention informs how the system follows the structure of the output. Convolution informs how it compares the input with documentation. Self-Attention with Relative Position Representations · Convolutional Neural Networks for Sentence Classification
The scope of the prediction
The formal task takes a request and uses a dataset with two sources of supervision. The parallel examples associate a request with a Bash command. The documentation examples associate a utility with text describing it. The system returns candidate commands with confidence scores and, for each utility in a candidate, a matrix connecting request tokens to documentation tokens. A token is an individual input unit after the text has been segmented. One axis of the matrix follows the request in its original order. The other follows the utility description.
The target language is Bash within a defined subset. The authors exclude commands with pipes, command substitution or process substitution. These constructions can express connections between commands or embed one computation within another. The restricted target still gives the system utility names, flags and arguments to organize, while the excluded constructions fall outside the reported task. The restriction is part of the problem definition and is applied when preparing the benchmark.
The method, step by step
The path from a request to a prediction
The method borrows the shape of a familiar activity. A person can consult a manual while deciding which utility fits a task, then use that decision while filling in the rest of the command. In the paper, the request goes through an encoder that makes it available throughout generation. In parallel, a comparison with manual entries produces scores for documented utilities. The scores enter the decoder at a specific point, when it is about to name a utility. A separate readout shows which parts of the texts contributed to those scores.
From an English request to Bash and documentation alignments
The steps in order.
The command representation makes that timing possible. A surface command is a line of tokens. Its syntax tree contains nodes that say what those tokens do in the command. In the paper’s ownership example, the utility name and the flag expressing recursion occupy different kinds of nodes. The node category gives the decoder a signal about the decision it is about to make. The guidance mechanism can use its stock of documentation scores at the utility node, where the scores and the candidates refer to the same kind of object.
The English encoder, tree decoder and guidance branch have different responsibilities. The encoder represents the complete request so that different output decisions can consult it. The decoder represents the generated prefix and its known tree relationships. The guidance branch compares a request with documentation even before the decoder reaches a utility slot. Its result is a single vector for the request, with separate entries for utilities. The same vector is available wherever the decoder reaches a utility choice.
Preparing the request and the command tree
The authors normalize both sides of the parallel examples. On the English side, concrete paths and patterns are replaced during preprocessing, so the input can express that an entity has a certain type without preserving the literal string. The command is also normalized. The parser receives typed arguments and builds an abstract syntax tree, or AST. The English side is then tokenized. The experiment applies the normalization to the comparison systems too, which keeps their translation inputs and targets comparable at the level of this preprocessing choice.
A Bash AST records each node with a structure attribute and a value attribute. The structure attribute answers what kind of part this is. The value identifies the particular utility, flag or argument type. The paper’s ownership example has a node whose structure is utility and whose value is chown. The root has a structural role and receives a dummy value so that it follows the same pair format. The separation creates one vocabulary for categories and another for values.
The authors traverse the tree in level order. All nodes at a given depth are visited before traversal proceeds to the next depth. For each visited node, the sequence records its structure token and then its value token. This gives the decoder a regular alternation. The figure also includes artificial End of Children and End of Tree nodes. These markers carry boundary information used by the tree representation. They are part of the serialized training target, so generation has to account for them along with the node types and values that come directly from the parsed command.
Y = (y¹, …, yⁿ)
Here Y is the serialized reference tree, n is its length in tokens and yⁱ is the row vector representing the token at position i. The superscript identifies a position in the sequence. Each row is one-hot, meaning that the entry for the recorded token is active and its other entries are zero. In the ordering given for preprocessing, odd positions use the structure vocabulary and even positions use the value vocabulary. The decoder can therefore assign probabilities in the relevant vocabulary for each decision.
nlc = (t¹, …, t^#nlc)
Here nlc is the tokenized natural-language request, #nlc is its token count and tⁱ denotes its token at position i. An embedding maps a token into a row of learned numeric features. The source embeddings form a matrix with one row per token and k columns, where k is the embedding dimension. The paper uses T for this matrix. The Transformer encoder processes T into a sequence X with the same number of positions. Each row of X is a representation of a source position informed by encoder processing of the request.
The target embeddings have a different job. A structure token and a value token come from separate vocabularies, so they use separate embedding matrices. Both types of embedding enter the same decoder stack. The decoder has to learn when to emit a category, which value belongs with it, how nodes fit into the current tree, and when the tree ends. The regular pair format supplies the order of the decisions. Tree Coordinates and Parent Attention give the decoder additional information about the object that sequence represents.
How the decoder sees depth and parentage
A sequential representation provides a position for every token. That position records where a token falls in the serialized stream. A node’s level measures something else, namely how far down it lies in the tree. The paper notes that the utility node occurs at the first level in its representation. Knowing the level can therefore help the decoder distinguish what kinds of node are plausible at a particular point. A token’s sequence position gives that clue only indirectly, since positions also depend on the numbers of preceding nodes and their markers.
Tree Coordinates supply a level embedding in addition to the usual sinusoidal position embedding. The decoder starts from the embedded structure or value token, adds the position information and adds the embedding for the level of the node from which the token comes. The structure and value of a node can thus convey different token identities while carrying the same depth information. The result is the initial target representation passed through the decoder layers.
Depth identifies a class of locations within the tree. Parentage identifies the particular earlier node that governs a location. Level order can place several nodes between a child and the token associated with its parent. It can also put neighboring tokens in the sequence that belong to different branches. Parent Attention gives the decoder a way to treat an earlier token differently when it is identified as a parent. It does this inside the self-attention calculation, which lets a target position draw information from earlier target positions.
In the equations below, the superscripts separate token position from layer and attention head. A head is one of the parallel attention calculations within the layer. The mechanism computes a compatibility score between the current position and each available position, converts the scores into weights and uses the weights to collect information. The parent term enters the compatibility score.
eᶩʰᵢⱼ = ⟨zⁱ˒ˡ W_Qᶩʰ, zʲ˒ˡ W_Kᶩʰ + aᶩᵢⱼ⟩ / √kₕ
Here eᶩʰᵢⱼ is the compatibility score from position i to position j at layer l in head h. The rows zⁱ˒ˡ and zʲ˒ˡ are the decoder representations at those positions before this attention update. The matrices W_Qᶩʰ and W_Kᶩʰ project the rows into query and key representations for the head. The angle brackets denote the inner product, which is the sum of products of corresponding coordinates. The denominator is the square root of the head dimension kₕ. The row aᶩᵢⱼ is a learned relation term, with a non-zero contribution reserved for a parent position j for the current position i.
kₕ = k / H
Here kₕ is the dimension allocated to a head, k is the decoder representation dimension and H is the number of heads. Dividing k among H heads gives the scale used in the compatibility equation. The parent term has the dimension of the head’s key representation because the decoder adds it to that representation before taking the inner product.
αᶩʰᵢⱼ = exp(eᶩʰᵢⱼ) / Σⱼ′₌₁ⁱ exp(eᶩʰᵢⱼ′)
Here αᶩʰᵢⱼ is the attention weight assigned to position j by position i for layer l and head h. The function exp exponentiates a score. The sum in the denominator runs over positions j′ from the first position to i, the last position available in this calculation. Each summand is the exponentiated compatibility for one such position. This operation is softmax. It makes the weights over the available positions sum to one. A change in the parent’s score can therefore change the relative weight assigned to the parent and to each of the other positions.
zⁱ˒ˡ⁺¹ = concatₕ₌₁ᴴ [Σⱼ₌₁ⁱ αᶩʰᵢⱼ (zʲ˒ˡ W_Vᶩʰ)]
Here zⁱ˒ˡ⁺¹ is the new representation at position i, following the notation of the paper’s decoder equation. The matrix W_Vᶩʰ projects the row zʲ˒ˡ at position j and layer l into the value space for head h. Each head sums those projected rows with weights αᶩʰᵢⱼ from the softmax. The operation concat joins the resulting head vectors, in order from the first head to H, into one vector. The parent term affects which rows contribute strongly. The value projection determines what information is collected from a row.
The parent bonus in this description is a learned change to compatibility. Its effect depends on the query and the relation vector. The decoder still compares the current position to other positions in the available prefix. This matters for understanding the ablation. Removing Parent Attention removes a way to distinguish a known parent within the attention calculation. The decoder still has its sequence and the other information that the experiment leaves in place.
How the guidance branch reads the manuals
The authors build a collection of utility descriptions by parsing Linux manual pages and adding cleaned descriptions from the community-maintained tldr collection. The unit of comparison is a request paired with the description of a utility. The guidance branch turns each of these texts into a vector with one coordinate per filter. A filter scans short successive stretches of the input. Its strongest response represents the presence of a pattern that it has learned to recognize. A span of consecutive tokens is an n-gram.
A request and a manual can use different words for related ideas. The filters operate on token embeddings and can thus learn to respond to more than one word sequence. In the paper’s analysis, a filter that responds to a phrase about recursively displaying files in a request can also respond to the manual’s language about listing. The two responses occupy the same vector coordinate because they come from the same filter. This shared coordinate system is what allows the comparison to support an alignment.
To construct the request representation, the branch slides filters over the matrix of source token embeddings. A window is associated with the position where it ends. Padding supplies missing rows when a window reaches beyond the start of the request.
Tⁱ = [tⁱ⁻ᵖ⁺¹, …, tⁱ⁻¹, tⁱ], 1 ≤ i ≤ #nlc
Here Tⁱ denotes the window ending at token position i and p is the width of the filter in tokens. The rows denoted by t in this equation are token embeddings, with their superscripts giving positions. The brackets stack the rows in order. The window has p rows and k columns, and the valid ending positions range from the first token to the request’s count #nlc. A padded row is zero where the window would otherwise extend before the first token.
fⁱⱼ = sigmoid(⟨Tⁱ, Fⱼ⟩_F + b_Fⱼ)
Here fⁱⱼ is the response of filter j at the window ending at position i. The matrix Fⱼ is the filter, with the same shape as Tⁱ, and b_Fⱼ is its learned bias. The subscript F on the inner product denotes the Frobenius inner product, which adds the products of corresponding matrix entries. The bias shifts this sum. The sigmoid maps the shifted value into the interval between zero and one. Applying the same filter to each window makes the resulting responses comparable across positions.
fⱼ = [f¹ⱼ, f²ⱼ, …, f^#nlcⱼ]
Here fⱼ is the feature map of filter j for the request. Its entries are the responses fⁱⱼ in order of ending position i, up to #nlc. The feature map preserves location information at this stage. One can look at a response and identify the window that produced it.
vⱼ = maxᵢ fⁱⱼ
Here vⱼ is the largest response of filter j anywhere in the request. The maximum is over its window positions i. This operation is max pooling over time, where time is the position in the text. The pooled coordinate gives the strength of the strongest match for the filter. To explain the score later, the procedure can recover which window supplied that maximum.
v = [v₁, v₂, …, vᵣ]
Here v is the pooled request representation, r is the number of convolution filters and vⱼ is the maximum response for filter j. The vector has one entry for each filter regardless of the length of the request. The guidance branch builds the utility vector wᵘ in the same manner. Its input Dᵘ is the embedding matrix of the description d for utility u. It has #d rows, where #d counts tokens across the description, and k columns. The same set of filter coordinates in v and wᵘ links responses to corresponding patterns.
gᵘ = ⟨v, wᵘ⟩ / (‖v‖ ‖wᵘ‖)
Here gᵘ is the cosine similarity for utility u, v is the pooled request vector and wᵘ is the pooled description vector. The inner product in the numerator sums the products of matching filter coordinates. The double bars denote the Euclidean length of each vector. Dividing by the product of the lengths gives the cosine similarity, which compares the directions of the two vectors. Utilities can consequently receive similar scores from texts of different lengths after the filters have pooled their responses.
g = [gᵘ¹, gᵘ², …, gᵘ^|M|]
Here g is the guidance vector. The superscripts u¹ through u^|M| index the utility entries in the documentation dataset M, and |M| counts those entries. Each coordinate gᵘⁱ holds the cosine similarity for the corresponding utility entry uⁱ. The order in this vector comes from the documentation collection. The decoder’s value vocabulary has its own order, which is handled when the scores enter generation.
How documentation changes a utility choice
The decoder produces a row of scores for the next token. A linear transformation maps a final decoder representation into a score for each item in the relevant vocabulary. These scores, called logits, become probabilities after softmax. Structure tokens use the ordinary projection and softmax. Value tokens likewise start from a projection. When the preceding structure prediction identifies a utility, the generator adjusts the value logits using the guidance vector.
pⁱ ← pⁱ + s ⊙ R(g)
Here pⁱ is the row of value logits at decoder position i, g is the guidance vector and R maps utility scores into the corresponding positions of the value vocabulary. Entries for values that do not name utilities receive zero through this mapping. The vector s is a learned row with one coordinate per value-vocabulary entry. The symbol ⊙ means element-by-element multiplication. The arrow means that the generator replaces the existing logits with their sum with the guidance adjustment. Softmax is applied to the resulting logits.
The condition for this adjustment is expressed through the decoder’s preceding structure prediction. The paper describes checking whether the highest-scored structure label is the utility label. Putting structure before value in a node gives the generator that condition before it has to name the utility. A branch that is filling a flag or a typed argument uses the decoder’s ordinary value scores. In the utility branch, the learned scale governs how strongly each value responds to the corresponding documentation score.
The authors use beam search to generate candidate sequences. Beam search retains a limited set of promising partial sequences as decoding proceeds. Every extension adds a structure or value token, according to the target format. The result is a set of serialized outputs that can be converted back into trees and rendered as Bash predictions. The decoder’s score for a sequence provides the basis for ranking those candidates. The evaluation applies its own rule for assigning confidence to the ranked predictions.
Training the translation and the documentation match
The system is trained end to end, with gradients propagated from a combined objective. Two terms supervise the next-token predictions, separately for the structure and value vocabularies. A further term supervises the guidance branch with information about which utilities appear in the reference command. The training pairs thus tell the decoder which token to produce, and the utility identities in the same pairs tell the guidance branch which descriptions to associate with the request.
L = L_structure + λ₁ L_value + λ₂ L_guide
Here L is the full training objective. L_structure is the cross-entropy for structure predictions, L_value is the cross-entropy for value predictions and L_guide is the cosine embedding loss for documentation matching. Cross-entropy penalizes low probability on the reference token. The coefficients λ₁ and λ₂ scale the value and guidance losses. The authors set λ₁ to 1 and λ₂ to 10 in their experiments.
The cross-entropies can be written by indexing the decoder position and the reference position separately. In the paper’s shifted indexing the output at position i is compared with the reference at i + 1. An even decoder position precedes a structure target in that indexing, and an odd decoder position precedes a value target. This is consistent with the order of the target itself, where a node’s structure comes first.
L_structure = −(1 / (n/2)) Σᵢ∈Nₑ Σⱼ₌₁^|V₁| yⁱ⁺¹ⱼ ln ŷⁱⱼ
Here n is the target length, and n/2 is the number of structure decisions in the paired representation. Nₑ denotes the positive even positions, restricted in the sum to positions with a next target. V₁ is the structure vocabulary and |V₁| is its size. The index j runs over those vocabulary entries. The indicator yⁱ⁺¹ⱼ is the reference one-hot entry for the target at position i + 1. The quantity ŷⁱⱼ is the probability assigned to entry j by the output at position i. The natural logarithm is denoted by ln. The minus sign makes the loss larger when the observed token receives lower probability.
L_value = −(1 / (n/2)) Σᵢ∈Nₒ Σⱼ₌₁^|V₂| yⁱ⁺¹ⱼ ln ŷⁱⱼ
Here Nₒ denotes the positive odd positions used for the next-value predictions. V₂ is the value vocabulary and |V₂| counts its entries. The reference coordinate yⁱ⁺¹ⱼ, predicted probability ŷⁱⱼ, vocabulary index j and logarithm ln play the same roles as in the structure loss, now for value tokens. The normalization n/2 averages the loss over the value decisions. The two expressions give supervision to both parts of each serialized node.
L_guide = (1 / |M|) Σ₍ᵤ,𝒹₎∈M ℓᵤ
Here L_guide is the guidance objective for a request and its reference command, M is the collection of documentation pairs, |M| is its size and each pair (u, d) joins utility u to description d. The sum takes one term ℓᵤ for each pair and divides by the number of pairs. The individual loss depends on whether the reference uses that utility.
ℓᵤ = I(u ∈ U(c)) (1 − cos(v, wᵘ)) + I(u ∉ U(c)) max(0, cos(v, wᵘ))
Here U(c) is the set of utility names used in the reference command c. The symbol ∈ denotes membership, ∉ denotes absence and I returns one when its condition holds and zero otherwise. The function cos is the cosine similarity between the request vector v and the utility vector wᵘ. The maximum takes the larger of zero and that similarity. For a utility used in the reference, the first term encourages a high similarity. For an absent utility, the second term penalizes a positive similarity. Its contribution is zero when the similarity is already at or below zero.
This objective connects the manuals to the paired commands without requiring a human to annotate which spans in the manual correspond to which spans in the request. The training signal says whether a utility belongs to the reference command. The filter responses determine how that signal is distributed across patterns. The explanation is recovered from those responses after training.
Turning a contribution into a span alignment
The procedure starts with the elementwise products of the request and utility vectors. Each product is one filter’s contribution to the numerator of the cosine score. For a fixed request and utility, the denominator is shared across all such terms, so the products supply a ranking of contributions within the pair. A large product indicates a coordinate where the shared filter responded strongly to both texts.
For each selected coordinate, the authors trace the maxima to their windows. The request maximum identifies one span and the documentation maximum identifies another. The alignment matrix starts at zero. The system increments the rectangular region connecting the token positions in those windows. If selected spans overlap, their rectangles can overlap as well, giving the same token pair more weight. The paper’s construction figure illustrates the operation with the top 3 coordinates.
Aⁿˡᶜᵤ ∈ ℝ^(#nlc × #d)
Here Aⁿˡᶜᵤ is the alignment matrix for request nlc and utility u. The real-valued matrix has #nlc rows for request tokens and #d columns for the tokens in the utility’s description. The multiplication sign in the dimensions separates the row count from the column count. A cell records the contribution assigned to its pair of positions by the selected window matches. The alignment can connect several words at once because a filter window can cover a phrase.
The formal output associates such a matrix with each documented utility in a candidate command. The evidence originates in the guidance score that can enter the utility logits. The authors also use the matrices to visualize which terms stand out across requests. The reported implementation and the parsed, cleaned documentation are released by the authors, who identify Linux manuals and tldr as the sources of the descriptions used in the experiments.
Experiments and results
The filtered data and the test splits
The authors take the parallel examples from the NLC2CMD competition data and remove commands containing the excluded constructions. The filtered collection contains 3203 request–command pairs. The experiment uses ten folds. Each run withholds one fold for testing. The other nine are pooled, then divided into training and validation data in a ratio of 9:1. The reported results average over the ten runs, with held-out testing occurring on a different fold in each run.
The validation part has a distinct role in scoring. It is used to choose a setting for how confidence is assigned to ranked outputs. Test examples then assess the system with that choice in place. The paper describes the proposed translator as trained on 2,600 examples and 116 utility descriptions in its discussion of the results. The first figure refers to the amount of parallel training data in that discussion. The second describes the documentation collection available to the guidance branch. The filtered pair count refers to the collection before the run-specific divisions.
Normalization applies to every translator in the comparison. It removes concrete file paths and regular expressions on the request side and makes corresponding changes on the target side. The baselines predict normalized command strings, whereas the proposed system predicts the serialization of a tree parsed from the normalized command. The test metric compares the resulting predictions as commands. This puts the tree system and the string systems on common ground for the particular properties the scorer examines.
What the competition metric rewards
For each request, the scoring procedure takes up to 5 ranked command predictions and compares them with one recorded reference. The main units of comparison are the utilities and their flags. A flag is an option attached to a utility. The scorer visits utility positions in order. A utility at the expected position can receive credit depending on the match between the flag sets. A different utility at that position incurs a penalty. The longer utility sequence sets the number of positions over which the score is normalized.
T = max(|U(c)|, |U(ĉ)|)
Here c is the reference command and ĉ is a predicted command. In the metric, U is the ordered sequence of utilities in a command. The vertical bars denote its length. T is the larger of the two lengths, and it is used as the count of positions for comparison. This use of U retains positional order, while the membership test in the guidance loss asks only whether a utility occurs.
Nᵢ = max(|F(U(c)ᵢ)|, |F(U(ĉ)ᵢ)|)
Here i is a utility position, U(c)ᵢ is the reference utility at that position and U(ĉ)ᵢ is the predicted utility there. The function F gives the set of flags for that occurrence in its respective command. The bars count the elements of the flag sets. Nᵢ is the larger of those counts and is the normalizing quantity in the flag comparison.
S(q) = Σᵢ∈[1,T] (1/T) × [I(U(ĉ)ᵢ = U(c)ᵢ) × (1/2) × (1 + (2 × |F(U(ĉ)ᵢ) ∩ F(U(c)ᵢ)| − |F(U(ĉ)ᵢ) ∪ F(U(c)ᵢ)|) / Nᵢ) − I(U(ĉ)ᵢ ≠ U(c)ᵢ)]
Here q is a prediction pair containing the command ĉ and its confidence δ. S(q) is the single-prediction score as printed in terms of the commands. The sum ranges over utility positions i from 1 through T. The equality and inequality signs compare the predicted and reference utility identities at position i, and I activates the corresponding term when the comparison holds. Inside the flag term, ∩ is the intersection of the two sets and counts shared flags through the vertical bars. The symbol ∪ is their union, whose size includes every flag that occurs in either command. The inner division uses Nᵢ and the outer factor 1/T weights each position in the utility sequence. The paper’s equation gives the general form and leaves the empty flag-set case implicit.
When at least one candidate receives a positive single-prediction score, the request receives the best candidate’s score. When every candidate scores at or below zero, the request receives their mean. These branches make the metric a property of the candidate list. In particular, a useful alternative below the first rank can determine the request score. That is one reason to read the reported values as benchmark scores rather than proportions of first-ranked commands that are fully correct.
Score = { max_{q ∈ A(nlc)} S(q) if some S(q) > 0
{ (1 / |A(nlc)|) Σ_{q ∈ A(nlc)} S(q) otherwise
Here A(nlc) is the set of returned prediction pairs for the request nlc and |A(nlc)| is the size of the set. The maximum takes the best S(q) over the returned pairs q. The sum adds those same scores for the averaging branch. The condition uses zero as the threshold for a positive prediction. The paper reports that the test metric ranges from -1 to 1, with higher scores preferred.
All compared systems use beam search with a beam size of 10, then retain the top 5 candidates for scoring. The candidates are initially sorted by beam score. The paper describes assigning confidence 1 to the top t entries and a lower confidence based on each remaining entry’s beam score. It chooses t on the validation set for each system. The displayed score equations express the utility and flag comparisons without an explicit δ factor, while the decoding procedure separately describes this confidence assignment.
δ = exp(beam_score) / 2
Here δ is the assigned confidence for a candidate below the top t entries, beam_score is that candidate’s score from beam search and exp is the exponential function. The divisor is 2. The count t is selected on the validation fold arrangement for the corresponding system, and the remaining set is the bottom 5 − t among the outputs supplied to the scorer.
The systems being compared
Magnum is the competition winner. Its original submission combines Transformers trained with different seeds and batch sizes. The authors compare against a single member of that ensemble. Both Magnum and the proposed system use 8 attention heads and 6 layers each in the encoder and decoder to process representations with 512 dimensions. Training Magnum takes 2500 steps and uses a warm-up scheduler, batches containing 14,000 tokens, and gradients accumulated over 2 steps. Its command predictions come directly from sequences of normalized command tokens.
T5 supplies a comparison based on pretraining followed by fine-tuning. The authors tried the small, base and large versions and report T5-small, which performed best among them. The input consists of a task prefix asking for English-to-Bash translation followed by the request. The training output is the normalized command. The paper identifies the T5-small implementation used in the comparison as coming from Hugging Face. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer · Transformers: State-of-the-Art Natural Language Processing
Seq2Seq is the recurrent comparison. The encoder has two bidirectional LSTM layers with 256-dimensional representations. An LSTM is a recurrent unit that updates a representation along a sequence. The bidirectional encoder processes the input in both directions. The decoder uses two LSTM layers with 256-dimensional representations and attends to the encoder so that each output step can use a different weighted view of the input.
The proposed system is trained in batches of 10 examples, accumulating gradients over 50 steps before updates, with the default settings of the Adam optimizer. Its encoder and decoder use the Transformer settings described above. The guidance branch uses 200 convolution filters with window sizes 1,2,3,4,5 and 6. The varying windows allow filter responses to cover individual tokens and phrases of different lengths. These settings apply to the translator whose test score is shown below.
The test scores
Translation systems on the filtered NLC2CMD test folds by mean competition score
The documentation-guided tree system scores above T5 and Seq2Seq, with Magnum recording the highest mean.
The numbers
| System or setting | Competition score |
|---|---|
| Seq2Seq | 0.594 |
| T5-small | 0.639 |
| Magnum, single ensemble member | 0.685 |
| Documentation-guided tree system (this paper) | 0.651 |
Across 10 test runs, Seq2Seq scores 0.594 ± 0.032 and T5-small scores 0.639 ± 0.027. The proposed system scores 0.651 ± 0.017. The single Magnum system scores 0.685 ± 0.027. The figures following the ± signs are the standard deviations across the runs. They describe the reported spread under the fold procedure. The complete tree system has the smallest such spread among these rows.
The authors describe the proposal as comparable to Magnum and superior to T5 and Seq2Seq under this evaluation. Magnum has the higher reported mean. The T5 comparison shows that the translator trained on the filtered parallel data and utility descriptions can outperform the fine-tuned T5 variant in this setting. The systems differ in their architecture, training and output representation. The comparison therefore establishes the ranking of the assembled systems under the benchmark. The controlled removals address what can be learned about particular components within the tree translator.
The output representations also differ in length. The authors describe the serialized tree as at least twice as long as the original command and suggest that this makes generation harder. More positions must be generated, including categories and markers, before a complete command can be recovered. In return, the category positions give guidance a defined place to enter. The comparison gives the score achieved with that design. It leaves the difficulty attributable to sequence length as the authors’ explanation of the tradeoff.
What the ablations show
Removing one component at a time
The authors remove Tree Coordinates, Parent Attention and the Guidance Module in separate experiments. They train each resulting architecture to convergence and compare its test score with that of the complete system. The comparisons address how the components contribute in the presence of the others. Parent Attention is evaluated with the rest of the architecture available. Tree Coordinates is evaluated with the decoder still using Parent Attention. The guidance removal tests the contribution of the documentation branch to the configuration that otherwise retains the proposed tree machinery.
Component removals on the filtered NLC2CMD test folds by mean competition score
Every removal lowers the mean, and the largest drop follows removal of Parent Attention.
The numbers
| System or setting | Competition score |
|---|---|
| Without Parent Attention | 0.503 |
| Without Tree Coordinates | 0.597 |
| Without the Guidance Module | 0.630 |
| Complete system (this paper) | 0.651 |
Without Parent Attention the mean test score is 0.503 ± 0.154, compared with 0.651 ± 0.017 for the complete system. This is the lowest mean and the largest standard deviation in the ablation rows. The decoder can still see its available prefix in sequence order. It loses the learned parent relation term in the compatibility calculation. The result supports the usefulness of giving that relationship an explicit role in this serialization. The accompanying spread shows that the observed performance of the reduced architecture changes considerably across runs.
Without Tree Coordinates, the test score is 0.597 ± 0.052. This comparison removes the level embedding while leaving the other proposed components in place. Parentage and depth supply different information. Parentage identifies a connection to a specific earlier position. Depth identifies where the node sits within the tree as a whole. With level order, an absolute position can reflect which depth has been reached, but the correspondence depends on the size of earlier levels. The reported loss of performance is consistent with the explicit level embedding giving the decoder information that remains useful alongside the parent relation.
Without the Guidance Module, the mean test score is 0.630 ± 0.072. The architecture still generates serialized trees with the two structural adaptations. This removal gives the closest mean to the complete system of the reported ablations. It also gives a larger standard deviation than the complete system has. The comparison supports a contribution from the documentation branch to the measured command prediction performance. The removed component is itself a collection of choices, including how the texts are represented and where the resulting guidance is applied. The experiment concerns that component as a whole.
All reported removals yield greater run-to-run spread than the full system. This observation is separate from their effect on the means. For instance, a translator without the guidance branch has a mean closer to the complete system than either of the other reduced systems does, yet it has more spread than the system without Tree Coordinates. The reported statistics describe these architectures under the fold procedure. They leave open which properties of the held-out examples account for differences between runs.
Looking at alignments for particular utilities
The qualitative analysis examines what the filters match. In the example for tree, the input asks for a recursive display of files. The matrix highlights a match between the wording requesting that display and the documentation’s use of the word list. The authors observe that the matched spans share no token. This is evidence that the learned filter response can connect related expressions despite a change of vocabulary. A different highlighted region connects wording about the current directory in the request with similar wording in the manual. In that case, shared words are present.
The figure also presents an alignment for find. The display places the invocation along one axis and the description along the other. A lighter region represents places where more of the selected filters picked spans covering the same token positions. The display thus shows where recurring choices of maximum windows reinforce one another. It is useful to read these regions as blocks of phrase evidence. A rectangle comes from a shared filter coordinate, so even a cell in a strong region need not represent an independent word-to-word link.
The two examples for tree illustrate different ways an alignment can be intelligible to a reader. A phrase about recursive display can relate to a more general term for listing. A phrase about a current directory can overlap substantially with the manual. Both kinds of match can contribute to the same utility similarity score. This is a qualitative demonstration of the kind of evidence returned by the system. It does not supply a measured frequency for either type of match.
What averaging reveals about a manual entry
The authors also aggregate alignments across requests. For a given request and utility, they sum the matrix along the request axis. The result is a vector over documentation positions. Each entry records how much alignment weight reached that position from anywhere in the request. They then average such vectors and apply softmax to form an importance distribution over the description tokens. This operation changes the question from which phrases matched in one request to which words repeatedly attracted weight in the descriptions.
aᵤⱼ = Σᵢ₌₁^#nlc (Aⁿˡᶜᵤ)ᵢⱼ
Here aᵤⱼ denotes the resulting sum for documentation token position j of utility u on the current request. The notation describes the summation the authors perform. The index i ranges over the #nlc request positions. The term (Aⁿˡᶜᵤ)ᵢⱼ is the alignment matrix cell for request position i and documentation position j. After the sum there is one value for each documentation position. Averaging operates on those values across requests, and softmax rescales the averaged vector into a distribution.
One reported example is wget. The aggregate highlights network downloader, words that convey the utility’s function in a compact phrase. The analysis presents additional utilities with tokens shaded by weight. The highlighted material remains in the original text of the description, so the display shows a selection of salient wording from the documentation. The authors suggest that this kind of display could help users learn what individual utilities do. The example establishes what the procedure surfaced in that entry, while the broader educational possibility motivates the interpretation.
Limitations
Boundaries set by the authors
The authors define the target set to exclude pipes, command substitution and process substitution, and enforce that decision before making the experimental splits. The results therefore apply to the filtered NLC2CMD examples. In a construction that joins commands with a pipe, choosing utilities is only part of specifying the behavior. The connection between the commands also matters. In the excluded substitutions, the translator would have to represent an embedded operation and its relationship to the surrounding command. Those capabilities lie outside the reported experiment.
The benchmark also operates on normalized requests and commands. Concrete paths and patterns are abstracted during preprocessing, and the metric ignores arguments. Correct arguments can be decisive in a shell command because they specify the objects on which the utility acts. The test score assesses the utility sequence and flag choices against the reference. It provides no direct measurement of how well the translator restores concrete arguments, resolves their meanings from the request or chooses the intended objects in a real environment.
The paper evaluates a particular serialization of the AST. The authors recognize the added sequence length and propose exploring other ways of turning a tree into a sequence. They also identify richer use of manual pages and the division of invocations into component tasks as possible directions. The discussion of planned prediction belongs to that future-work agenda. The demonstrated translator uses the level-order representation and the description matching procedure laid out in the method.
What follows from the measurement
The evaluation assumes one recorded reference per request. A command that uses a different utility can be penalized even if it would produce the intended result. Conversely, the utility and flag sequence can earn credit while omitting a property that depends on the arguments. The benchmark answers a reproducible comparison question about the recorded pairs. It leaves behavioral equivalence and the success of running the command unmeasured.
The reported score also uses several ranked candidates. A suitable candidate among the retained outputs can determine the score when it receives positive credit. A person inspecting just the first proposal would face a different decision. The paper describes setting confidence from the ranking and tuning its assignment on validation data. It offers neither a separate first-candidate execution result nor a calibration study connecting those confidence values to the probability of real-world success.
The standard deviations summarize variation across the test runs. The means show that the complete system ranks between the single Magnum system and T5-small, and that every tested removal lowers the mean. The paper does not report a significance analysis for these comparisons. The folds share examples across their training portions, and the standard deviations combine variation that may come from the test examples and from fitting the systems on different data. They do not by themselves settle how the same training procedure would behave on an independently collected set of shell requests.
The ablations remove one component at a time. Their strongest conclusion concerns the value of the removed feature when the other components are present. There is no crossed experiment to measure how Tree Coordinates and Parent Attention interact when both are removed, for example. Likewise, the score for removal of the Guidance Module gives no separate number for the guidance loss, the use of both documentation sources or the decision to add the scores only when naming a utility. Those are parts of the assembled branch in the reported design.
The paper’s finding about domain-specific text also has a defined scope. The guidance ablation supports the documentation branch within the proposed architecture. T5 and Magnum differ from that architecture in several respects, including the representation of the output. Their scores cannot assign an isolated effect to manuals or to tree generation. That would require holding other choices fixed while varying one source of information or one representation across otherwise comparable systems.
What the explanations establish
The alignments trace selected filter responses to specific places in the request and manual. Their relationship to the computation is concrete. The selected filters contributed to the utility’s cosine score, and the decoder can use that score during a utility decision. A reader can inspect the spans rather than seeing a score on its own. That is the form of interpretability examined in the paper.
A utility prediction also receives its ordinary decoder logits, and the guidance contribution is scaled by learned parameters before entering them. A high-contribution match within one utility description therefore need not explain why that utility won against a specific alternative or how much the final prediction would change if the phrase were removed. The alignments illustrate evidence for the similarity calculation. They leave the influence of that evidence on an individual final ranking unmeasured.
The method supplies utility-level explanations. Flags and arguments have their own decision positions in the decoder, and the guidance scores are designed for the slot that names the utility. A convincing explanation for the utility can coexist with uncertainty about the options or target objects. The examples show plausible connections between request language and the manual, and the averaged display shows characteristic wording for some utilities. The paper reports no user study measuring whether those displays improve verification, confidence or learning. Its pedagogical claim is a possible application of the evidence it visualizes.
What came after
The later paper in this line of work is Efficient Constituency Tree based Encoding for Natural Language to Bash Translation. Its title places the constituency tree on the encoding side of the task. A constituency tree organizes the words of a request into nested phrases. The 2021 paper modifies the decoding side to reflect the structure of the command being generated. The later paper’s stated focus thus brings explicit tree structure to a different point in the same translation problem. Efficient Constituency Tree based Encoding for Natural Language to Bash Translation
The connection is through the role of syntax in a task with a structured description at each end. On the English side, a phrase can group an action with its scope or object. On the Bash side, a command tree distinguishes the utility from the option or argument assigned to it. These uses of trees concern different representations. The later work cites the earlier paper and takes up constituency-based encoding. Its stated topic supplies the basis for that connection, while its use of manual guidance, parent relations and documentation alignments is unspecified.
Cite
Cite as Shikhar Bharadwaj and Shirish Shevade. 2021. Explainable Natural Language to Bash Translation using Abstract Syntax Tree. Proceedings of the 25th Conference on Computational Natural Language Learning.
@inproceedings{bharadwaj2021explainable,
title = {{Explainable Natural Language to Bash Translation using Abstract Syntax Tree}},
author = {Shikhar Bharadwaj and Shirish Shevade},
booktitle = {Proceedings of the 25th Conference on Computational Natural Language Learning},
year = {2021},
doi = {10.18653/v1/2021.conll-1.20},
url = {https://doi.org/10.18653/v1/2021.conll-1.20}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bharadwaj-2021-explainable-natural-language-bash-translation/