Tree Transformer: Integrating Tree Structures into Self-Attention
Paper · 2019 · Yaushian Wang, Hung-Yi Lee and Yun-Nung Chen
Summary
A sentence has an order, but it also has a structure. Words form phrases, and those phrases fit inside larger ones. A bidirectional Transformer can use words on either side of a position to understand it, yet its attention weights can be hard to read as evidence of that hierarchy. Tree Transformer adds a mechanism that learns where phrases begin and end while the encoder learns to fill in missing words. The authors ask whether the resulting groups agree with human judgments about sentence structure, improve word prediction, and make attention patterns easier to follow.
The mechanism starts with a decision about each gap between neighboring words. Constituent Attention scores how strongly the words on either side belong together. To work out how strongly a more distant pair belongs together, it multiplies the scores across all intervening gaps. A weak link can therefore keep the pair from attending strongly across a likely phrase boundary. Every attention head in a layer uses the same set of structural weights, while retaining its own preferences within those constraints. As the sentence passes through successive layers, links can strengthen and groups can grow. An earlier grouping cannot be undone by weakening its links higher up.
Training follows the masked word prediction objective used by BERT. The inputs provide the words to predict, and the authors use human-annotated trees to assess the resulting structures. On the Wall Street Journal material in the Penn Treebank, the induced trees agree with the reference brackets better than fixed branching patterns and random trees do. In a WSJ-test analysis of an encoder trained on WSJ-all, extracting trees across layers gives an F1 score of 52.0, compared with 49.07 from the best individual layer. In a separate experiment trained on WSJ-train and evaluated on WSJ-test, Tree Transformer gives lower perplexity on masked words than the ordinary encoder, including a comparison in which Tree Transformer has fewer parameters. The attention plots show early emphasis on nearby words and later attention across larger spans.
The additional mechanism carries about 10% parameter overhead, and the authors report a slowdown of 1.2 times. The results also depend on how the encoder learns. Starting with pretrained BERT weights and fine-tuning on WSJ-train yields poorer trees than the best training run from scratch, even when the training loss is lower. Removing positional encoding also reduces parse quality. The approach offers a way to propose phrase structures when annotated training trees are unavailable, a motivation that includes low-resource languages. The experiments establish its behavior on Wall Street Journal text. The authors make their implementation available in the Tree-Transformer repository.
Deep dive: Tree Transformer: Integrating Tree Structures into Self-Attention
Tree Transformer learns which words form phrases and uses those groups to guide attention, with tests on parsing and masked word prediction. · about 37 minutes to read
The problem and its context
A sentence has an order and a hierarchy
In a sentence such as “The old clock stopped before dawn,” the words occupy a single sequence. A reader can also see a group around “the old clock” and another around “before dawn.” Inside the first group, “old clock” forms a smaller unit. A constituent is a group of words treated as a unit in such an analysis. A constituency tree records these groups as nested spans. A branch divides a larger span into the smaller spans it contains, and the words sit at the ends of the branches.
This form of parsing asks where those groups are. An encoder can make effective use of a sentence without displaying the same groupings in an obvious form. Its attention scores say how much weight it gives other positions when updating a representation. A head might repeatedly look to the preceding word, or it might give strong weight to a named entity. The authors point to such recognizable patterns in earlier attention visualizations. Reading a hierarchy off those weights is a separate task. A collection of strong pairwise connections can cross several possible phrase boundaries, and an isolated preference for adjacent words says little about which phrases belong together higher up.
The question matters because the bidirectional Transformer had already become a useful starting point for natural language processing. Pretraining on raw text and adapting the resulting representations to a particular task had produced strong results across the tasks discussed in the paper. That success gives researchers a reason to examine where the representations come from. If attention is one means by which a word acquires information from its context, changing the routes that attention favors is a way to test a particular account of how contextual information should be assembled.
Tree Transformer narrows that account to ordered spans. In the authors’ design, it should be easy for words in a short phrase to exchange information early. A later layer should be able to use the information in that phrase alongside information in a neighboring phrase. The same operation can recur until a larger stretch of the sentence is available to attention. The question is then which gaps should act as boundaries, at which layers, for each individual sentence.
Earlier ways to put structure into an encoder
The paper draws on work in which the computation itself followed a tree. A recursive network can build a representation for a larger phrase out of representations for its children. A sentence representation then emerges by applying that operation up the tree. The paper cites Tree-Structured Long Short-Term Memory Networks in this line of work. It also cites Recurrent Neural Network Grammars, which tie the generation of syntactic structure to the generation of language. These approaches give hierarchy an explicit place in the computation.
Other work in the paper illustrates why it was attractive to supply that structure. Its examples include String-to-Tree Neural Machine Translation and Learning to Parse and Translate, as well as Linguistically-Informed Self-Attention for semantic role labeling. The closest precedent identified by the authors uses phrase boundaries to restrict attention for sentence encoding. These examples situate the proposal in a field that already had reasons to use syntax and several ways to provide it.
A common route was to obtain trees from a supervised parser. Such a parser depends on human linguistic annotation, which takes effort to produce. The authors identify two circumstances in which relying on a supervised parser becomes difficult. An appropriate annotated corpus may be unavailable for the language. In another case, the source material used to develop the parser may differ from the target text. Even when a parser exists, the question of how well its output serves the new setting remains.
Tree Transformer borrows the order of composition from recursive networks. It implements that order through changes to the attention weights of a layered encoder. Positions remain available across the stack, and what changes is how freely they can exchange information. It can therefore keep the surrounding Transformer architecture while assigning the task of finding phrase boundaries to an added component.
Learning structure from a task with observable answers
The paper calls the search for hidden trees in raw text grammar induction. In this formulation, the sentence is observed, and its internal grouping is something the learner has to infer. A prediction task makes that search trainable. If a particular organization helps an encoder recover information from the sentence, the training objective can favor the computations that led to that organization. The observed answers for the training task are words. The reference trees enter when the authors assess which groupings the encoder has learned.
The preceding grammar induction work in the paper shows several ways to create this incentive. In the reinforcement learning approach, parsing operations are actions and the performance of a downstream task supplies the reward. A successful sequence of operations is one that leads to a representation useful for that task. PRPN estimates syntactic distances between words and uses the resulting structure to guide access to its reading network’s memory. Ordered Neurons, or On-LSTM, changes the gates and activation in a recurrent network so that some hidden information can persist longer than other information. These approaches embed different assumptions about what structure should do during processing.
The authors also discuss an unsupervised recurrent grammar, URNNG. It brings together a recurrent grammar decoder and a network that infers trees, using variational inference to connect the two. DIORA organizes the search differently. It uses inside–outside dynamic programming to compose representations across possible binary trees and encourages agreement between representations produced by the inside and outside computations for a sentence. Both approaches address the problem of learning about structures that are unavailable as direct training targets.
Compound PCFG puts the explanation in a probabilistic grammar. A context-free grammar describes how larger categories can expand into smaller ones. Its probabilistic form assigns weights to possible expansions. The work described in the paper trains by maximizing sentence likelihood with the possible structures taken into account. The paper also places its work in a tradition that includes the Generative Constituent-Context Model.
These predecessors help specify the gap the authors address. There were ways to infer a tree through recurrence, recursive composition, or a grammar, and there were ways to guide attention with syntactic structures obtained elsewhere. Tree Transformer lets the grouping emerge inside self-attention as part of the encoder’s own work. Its training task comes from the existing practice of language modeling and pretraining. The architectural question is how to make that task give the encoder a reason to develop a hierarchy of spans.
The method, step by step
From neighboring words to phrases
Consider how the paper illustrates the expression “the cute dog.” A layer can treat “cute” and “dog” as a close pair while the link to “the” is still relatively weak. A deeper layer can strengthen the gap to the left of “cute,” giving all the words in the longer expression more opportunity to interact. Something similar can happen around “its tail,” which can eventually become part of a larger phrase about what the dog is doing. The diagram uses this growth from neighboring words to larger stretches as the organizing principle for the encoder.
The distinction between a group in the drawing and a group in the computation is important. The drawing shows firm boundaries so a reader can see the intended organization. Internally, a gap has a continuous link score. Small scores make it hard for attention to cross a gap, while large scores permit stronger interactions. The module can express uncertainty about a boundary by giving it a score between those extremes. It can learn these preferences through masked word prediction because the scores enter the attention calculation directly.
An attention head still determines which positions are informative for its current query. The new module determines how strongly the current layer favors keeping the two positions together. Think of the attention head as proposing a weight for each possible source of information. The constituent prior reduces that weight if the source lies across a likely boundary. Each head applies the same structural information to its own proposals.
At the next layer, the encoder works with updated representations, and the constituent module has another opportunity to assess the neighboring links. It keeps the link strength that has already accumulated and can add to it. A short group can thus become part of a longer one. The same decisions serve another purpose after training. The authors read the weaker links across layers as clues for where to split the sentence into branches.
How Tree Transformer learns and extracts phrase structure
The steps in order.
Computing the ordinary attention weights
The starting point is scaled dot-product attention. A query is a vector that represents what information a position is seeking. A key is a vector that represents how a position can be matched to that query. When the encoder takes their dot product, the result gives a score for using that source position. It compares that score with the alternatives in the same row of the attention matrix.
E = softmax(QKᵀ ÷ d)
Here E is the matrix of ordinary attention probabilities. Its entry E[i,j] refers to attention from position i to position j. Both indices range over the N positions of the input, so the matrix has N rows and N columns. Q holds the query vectors as rows, and K holds the key vectors as rows. Kᵀ is the transpose of K, so multiplying Q by Kᵀ supplies one dot product for each ordered pair of positions. The division by d scales every score. The softmax function turns the scores in each row into non-negative weights that sum to one.
d = √dₖ
Here d is the scale in ordinary attention, dₖ is the number of components in each query or key vector for the head, and √ denotes the square root. The constituent module uses a different scale for its own query and key vectors.
Multi-head attention performs the query and key comparisons in parallel with different learned projections. Individual heads can therefore give high weights to different positions. The paper expresses the relationship between the head width and the output width as follows.
d_model = h × dₖ
Here d_model is the dimension of the multi-head output, h is the number of heads in the layer, × denotes multiplication, and dₖ is the dimension used for a single head. The added constituent module works with vectors of dimension d_model. Its projections belong to that module and have their own parameters.
Making neighboring links compete
For the new module, the source of evidence for a boundary is a comparison across a single gap. The module creates a link query for each position and a link key for each possible neighbor. It computes a score for the right neighbor this way.
s[i,i+1] = (q[i] · k[i+1]) ÷ d
Here i is the position of the querying word and i+1 is the next position to its right. q[i] is the link query at i, k[i+1] is the link key at the neighboring position, and · denotes their dot product. Both vectors have d_model components. s[i,i+1] is the resulting score for a link in that direction, and d is the link score’s scaling factor. The same procedure with the key from the preceding position gives the leftward score. Because the query and key have distinct roles, the score from a word to its neighbor can differ from the score in the reverse direction.
d = d_model ÷ 2
Here d scales the neighboring scores, d_model is the width of the link query and key vectors, and ÷ 2 means division by two. This explains the two different uses of d in the paper. Ordinary attention uses the head’s query and key dimension in its square-root scale. The local link calculation uses half the full link vector dimension.
The directional scores indicate how compatible individual links are. The next operation makes the possible links from a position compete. When both neighbors are present, the word has a fixed amount of probability to distribute between them.
(p[i,i+1], p[i,i−1]) = softmax(s[i,i+1], s[i,i−1])
Here i+1 is the right neighbor of i and i−1 is its left neighbor. s[i,i+1] and s[i,i−1] are the raw scores of those links. The softmax over this pair gives p[i,i+1], the rightward probability, and p[i,i−1], the leftward probability. The two probabilities sum to one. An increased share for one direction leaves a smaller share for the other.
This competition gives the word a reason to express a relative preference. The authors report that without it the encoder tends to connect the entire sequence, leaving little structural restriction on ordinary attention. Even when a word’s neighbors both have plausible connections to it, the normalization asks which connection is more strongly supported at that layer. This is a constraint on the calculation of the adjacent links. Ordinary attention, which comes later, can still consider positions across the sentence and use their constituent weights to scale the result.
To define a single score for a gap, the module considers the directional probabilities from both sides of it. It takes their geometric mean.
â[i] = √(p[i,i+1] × p[i+1,i])
Here â[i] is the current layer’s proposed link strength for the gap after position i. The probability p[i,i+1] goes from position i to position i+1, and p[i+1,i] goes from the right-hand position back to i. The product, indicated by ×, is followed by a square root, indicated by √. A weak preference from either side pulls down the joint score. The result is a single value for the gap, usable in either direction.
The two uses of attention are now visible. The link operation asks which neighboring words seek each other out, using learned projections chosen for that purpose. The attention heads ask which information sources are useful for updating each position. A mutually strong neighboring link can let the heads consult each side of the gap freely, while the individual heads retain their freedom to place different weights on the available positions.
Keeping a grouping available at later layers
If the encoder used each layer’s local proposal directly, phrases could repeatedly assemble and break apart. The paper imposes a particular relationship between the layers. A proposed link can add strength to what earlier layers have accumulated, using a fraction of the room that remains before the link reaches its maximum.
aˡ[k] = aˡ⁻¹[k] + (1 − aˡ⁻¹[k]) × âˡ[k]
Here l is the current layer, indicated by the superscript ˡ, and l−1 is the preceding layer, indicated by ˡ⁻¹. The index k identifies the gap between positions k and k+1. aˡ[k] is the accumulated link at the current layer, and aˡ⁻¹[k] is its inherited strength. âˡ[k] is the current proposal obtained by combining the two directional probabilities across the gap. The term in parentheses is how much link strength remains available up to 1. The multiplication scales that remainder by the proposal, and the addition preserves everything inherited.
a⁻¹[k] = 0
Here the superscript −1 represents the state before the first numbered layer, k ranges over the neighboring gaps, and 0 means that the initial state supplies no links between distinct positions. The first layer therefore introduces the earliest evidence of grouping.
The update makes each link nondecreasing with depth. A gap can stay at the same strength when the new proposal contributes nothing, and a link that has reached its maximum stays there. Since the links along a span all follow this rule, the accumulated evidence that positions in that span belong together can only stay constant or increase. If groups are drawn by applying a fixed cutoff to the links, neighboring groups can join as scores rise. A group connected at one layer stays connected at the next.
This is the sense in which the encoder builds a hierarchy. The mechanism does not hard-code that one layer represents noun phrases and another represents clauses. It establishes a direction in which the grouping can change. Which gaps become easy to cross early and which remain weak until later depend on the representations and learned projections. Several gaps can strengthen together, so a layer can bring more than a pair of groups into the same span.
Turning gap scores into a constituent prior
Ordinary attention needs a weight for every pair of positions. The constituent module has produced a value only for each neighboring gap. It connects these descriptions through the idea that two words in a continuous constituent must be joined through the words lying between them. If a pair straddles a likely boundary, strong links elsewhere along the route still leave that boundary in the path.
C[i,j] = ∏ₖ₌ᵢʲ⁻¹ a[k]
Here C is the constituent prior for the current layer and C[i,j] is its entry for positions i and j, with i to the left of j in this expression. ∏ denotes a product, and k ranges from i through j−1. The term a[k] is the accumulated score of the gap after position k. The superscript j−1 gives the last gap to cross. The same product serves the reversed pair, making the prior symmetric. A position paired with itself has no intervening gap, for which the empty product gives full weight.
For immediate neighbors, the prior is just the score for their gap. For words farther apart, every intervening gap contributes. The authors choose multiplication because a small factor reduces the value of the whole product. Addition would allow evidence of strong links elsewhere to compensate for a weak boundary in a different way. A consequence of multiplication is that a longer route can also receive a modest weight when it crosses several links that are individually fairly strong.
The paper describes computing the product in log space. The transformed calculation adds the logarithm of each gap score and converts the result back to the original scale.
C[i,j] = exp(∑ₖ₌ᵢʲ⁻¹ log(a[k]))
Here C[i,j] is the same pairwise prior, ∑ means to add the terms for the gaps from k=i through k=j−1, and a[k] is the link score at gap k. log is the natural logarithm, and exp is the exponential function that reverses it. This expresses the product as a sum during the intermediate computation. The authors use it to address the numerical difficulty of repeatedly multiplying small probabilities.
The matrix has the same shape as the ordinary attention matrix. Its symmetry records a fact about the intended grouping. If a pair belongs to a shared constituent, that relationship applies in both directions. The head’s attention can still be directional because the query at one endpoint and the query at the other endpoint make different comparisons.
Applying the prior and training the encoder
With a constituent weight available for every pair, the layer multiplies that weight by the ordinary attention weight for the pair. The paper places this operation after the attention softmax.
E = C ⊙ softmax(QKᵀ ÷ d)
Here E is the attention matrix used under the new constraint. C is the current layer’s constituent prior, and ⊙ means elementwise multiplication, matching each entry of the prior to the corresponding attention entry. Q and K are the query and key matrices of the ordinary head, Kᵀ is the transpose of the key matrix, and d is the ordinary attention scale. The row-wise softmax gives the head’s normalized weights before multiplication.
The position of the multiplication determines the effect. Strong prior weights preserve more of the ordinary attention, while weak prior weights suppress the corresponding entries. In the stated equation the product is the final operation on the weights, so a row of the resulting matrix can sum to less than one. Each layer computes its own prior and passes it to every head in the layer. Accordingly, there is a shared answer to where the plausible boundaries lie and a separate answer from each head about which information matters within those boundaries.
The architecture illustration reaches a top layer in which the whole example sentence is grouped together. This is the easy limiting case to understand. When the prior gives full strength to every pair, the multiplication leaves the usual attention weights intact. When some links remain weak, some pairs are still suppressed. The cumulative update gives later layers a way to loosen the restrictions. The actual degree of loosening depends on the links that have been learned.
For training, the authors take the masked word objective from BERT. Some input positions are obscured, and the encoder uses the remaining context to predict the missing material. Bidirectionality allows context before and after a missing position to contribute. Since the constituent prior affects the representations used for those predictions, the prediction loss can adjust the parameters that produce it. The tree constraint creates a family of possible information routes. Predicting the words provides the training signal that favors particular routes.
The experiments use WordPiece for subword tokenization, with a vocabulary of 16k tokens. WordPiece allows an input word to be represented through smaller units from that vocabulary. In describing the architecture and parsing, the paper generally speaks of word positions and neighboring words. The reported shared settings include a hidden width of 512 for the encoder and Constituent Attention, 8 attention heads, and a feed-forward width of 2048. The dropout rate is 0.1. Dropout is a training setting that temporarily drops some activations. The number of layers is varied because the stack depth determines how many times a group can be enlarged before prediction.
Reading a parse out of the learned links
Once training has finished, the authors use the accumulated neighboring links to produce a conventional tree. The association between a link and a split runs in opposite directions. A strong link is evidence for keeping the neighboring positions together. A weak link is evidence for putting a boundary between them. For a particular span, the smallest internal link supplies a candidate split.
A single layer already supports a greedy procedure. Start with the complete span, split it at the weakest gap, and repeat for each resulting span. It is greedy because each split uses the weakest gap available in the current span, committing to that decision before considering its descendants. That procedure provides a way to turn relative link preferences from one layer into a hierarchy and serves as a comparison in the paper.
The authors’ proposed extraction procedure starts from the late layers and works downward. At higher layers it looks for weak gaps that could divide large spans. After a division, the recursion moves towards earlier layers, whose links can distinguish smaller groups within the spans. A candidate minimum is accepted as a breakpoint when it falls below 0.8. This condition matters at the top of the stack, where the links can all be close to their maximum. A minimum there could be a slight dip among otherwise strong links.
The procedure also has a lower cutoff, written m in the paper. Layers below it contribute no further splitting evidence. The authors describe 2 or 3 as typical settings. They exclude the earliest layers because including them can give poorer parses. Together the ceiling on acceptable link strength and the cutoff on layer depth limit how far the method will pursue evidence for subdivisions. The resulting tree can leave a small group with several word children, as the paper’s illustrated parse does.
There is a useful change in perspective between training and extraction. In the forward pass, strong links help words inside a span exchange information. During extraction, weak links indicate where to divide a span, and the resulting divisions are evaluated against reference brackets. This gives the authors a direct test of whether the organization learned for word prediction also resembles the organization in an annotated sentence.
Experiments and results
What the Wall Street Journal tests measure
For the parsing experiments, the data come from the Penn Treebank’s Wall Street Journal section. A treebank supplies sentences alongside human analyses that can be used as a reference. The authors train with masked word prediction on WSJ-train and also run a condition on WSJ-all. The latter includes the validation and test text. In each case the training objective uses the text, while the parsing evaluation compares induced groupings with human annotations. Which text was available during training still matters when interpreting the result.
The authors evaluate on WSJ-test and WSJ-10. WSJ-test contains 2416 sentences from the Penn Treebank test split, with unrestricted sentence length. WSJ-10 contains 7422 sentences selected from the whole Penn Treebank under a length restriction of 10 after punctuation is removed. A length-restricted collection emphasizes short examples. The unrestricted set also includes longer sentences, in which a system has more potential locations to consider when deciding where a phrase ends.
The main parsing metric is F1 for constituency brackets. A successful bracket chooses the same span boundaries as a reference constituent. Precision measures how often the predicted brackets are reference brackets, while recall measures how many reference brackets the procedure recovers. F1 combines the two. This matters for a procedure that can stop subdividing a span. Predicting fewer brackets can help precision if the omitted ones were wrong, while it can hurt recall if it leaves out real internal groups.
The authors’ best reported grammar induction setting uses Adam with a learning rate of 0.0001. The first and second moment settings, written β₁ and β₂, are 0.9 and 0.98. These are the settings attached to the parsing experiments. The masked word comparison also uses Adam, with a different value for the second moment setting.
Parsing baselines and the reported results
The simplest references for the parsing task are left-branching, right-branching, and random trees. A fixed branching scheme keeps applying its preferred direction regardless of the words it sees. A random tree supplies a further comparison with a grouping that does not rely on the learned links. The authors report that Tree Transformer beats these trivial alternatives on WSJ-test. Its output thus agrees with the reference spans more often, by the F1 comparison, than those elementary ways of organizing the words.
The main learned comparisons on WSJ-test are PRPN, On-LSTM, and Compound PCFG. The authors describe their training material and evaluation settings as matching those of the relevant Tree Transformer comparisons. They also report results for DIORA and URNNG, with a qualification about the experimental conditions. DIORA uses the Multi-NLI corpus, and URNNG uses a subset of the One Billion Word Benchmark with 1M in training data. The paper characterizes these as larger training resources and notes some differences in the evaluation settings. Agreement or disagreement among those scores therefore reflects differences in experimental conditions as well as differences in how trees are learned.
The WSJ-10 comparisons have another input distinction. Some earlier systems, including CCM, DMV+CCM, and UML-DOP, use part-of-speech tags during training. A tag supplies a category such as noun or verb. These categories can help identify recurring patterns in short sentences. Tree Transformer uses word prediction and learns its neighboring links without those inputs. The paper cautions against directly comparing the scores of systems with this difference in available information.
A quantitative result the authors discuss in detail is the comparison between taking link scores from a single layer and using the proposed extraction across layers. This is the WSJ-test analysis of the condition trained on WSJ-all. The best single layer is layer 3, which gives F1 of 49.07. The multilayer procedure reaches 52.0. Both use an encoder whose organization was learned through the same prediction task. The measurement changes how the resulting link scores are read into a tree.
Tree extraction strategies on WSJ-test, bracket F1
Extraction across layers recovers reference brackets better than the strongest single-layer procedure.
The numbers
| System or setting | F1 |
|---|---|
| Greedy extraction from layer 3 | 49.07 |
| Multilayer extraction (this paper) | 52.0 |
The authors also compare the recall of different kinds of reference constituents. Tree Transformer readily recovers noun phrases and adverb phrases relative to its recovery of verb phrases and adjective phrases. That tells a reader something an overall F1 score cannot localize. Correct grouping is uneven across categories. The recall analysis groups results by the labels of reference constituents, giving a way to see which kinds of span the induced trees recover.
Greater depth improves parsing in the comparisons the authors discuss, up to the point at which further layers cease to help. They report that improvement stops above a depth of 10. Their explanation follows the link update. Once a sufficiently high layer has brought the words into a common group, extra layers have little distinct grouping to contribute to tree extraction. Additional encoder computation can still change the representations used for word prediction.
Predicting a masked word on WSJ-test
The masked word experiment asks whether the same structural bias changes the encoder’s ability to recover text. The inputs come from a separate training and test arrangement. The encoders train on WSJ-train with the BERT masked language objective and are evaluated on WSJ-test. The authors select the reported configurations by their performance on the validation set.
A left-to-right evaluation would ask the system to predict a word from the words before it. That would leave out a source of information the bidirectional encoder is built to use. In the paper’s test, an evaluation input contains the whole sentence with one word replaced by [MASK]. Every word in a test sentence takes a turn as the missing word, with all the others present for that prediction. A sentence therefore contributes as many individual evaluation inputs as it has words. This arrangement fixes the masking choices and presents the same prediction problems to the systems being compared.
The metric is perplexity over the masked words. Each prediction supplies a probability for the original word at the missing position. The authors aggregate those probabilities on a logarithmic scale and transform the result as follows.
perplexity = exp(−∑ log(p) ÷ n_mask)
Here p is the probability assigned to the actual missing word for an evaluated position. log is the natural logarithm, and ∑ sums those logarithms across the masked words in the evaluation. The minus sign makes the summed quantity a loss, n_mask is the number of masked words, and division by it gives the average loss per word. The exp function takes the exponential of that average. Assigning higher probability to the actual missing words reduces perplexity. The metric concerns the probability given to every correct answer, which can change even when the most probable guess stays the same.
For this experiment, Adam uses a learning rate of 0.0001, with β₁ set to 0.9 and β₂ set to 0.999. The authors keep the training settings alike across the ordinary and tree-guided encoders, varying depth and making a wider comparison where they want to check the effect of parameter count. The enlarged ordinary Transformer is designated 10-B. The paper identifies its increased hidden size as the reason for its larger parameter count.
The reported direction is lower WSJ-test masked word perplexity for Tree Transformer. The advantage appears even in a comparison where the tree-guided encoder has fewer parameters than the ordinary encoder. This comparison addresses the possibility that the new module improves prediction merely by enlarging the network. The paper attributes improved prediction to the way the induced structure guides composition, with nearby information brought together earlier and broader context becoming easier to use later. The experiment measures the effect of the overall architecture on this prediction task.
The added Constituent Attention module brings about 10% in parameter overhead when added to an otherwise comparable encoder. The paper reports the computation as 1.2 times slower. The smaller-parameter comparison and the overhead statement refer to different comparisons. Changing depth or hidden size can give Tree Transformer a lower total parameter count than a particular ordinary encoder, while adding the module to an otherwise fixed encoder still carries a cost.
What the ablations show
Where to stop reading layers
The bottom-layer comparison changes the extraction procedure applied to an encoder trained on WSJ-all. The variable m specifies the earliest layer from which the parser can take evidence. A small value gives the procedure access to fine distinctions near the input. A larger value gives it only the link scores that have accumulated later. The comparison measures which portion of the stack is most useful for producing reference-like brackets.
Setting m to 3 gives the best result in the authors’ analysis. They report poorer extraction when they include the earliest layers. Those layers can produce strong evidence for some local pairs, yet local affinity alone can be a weak guide to which completed spans deserve brackets. A connection between neighbors can help the encoder predict words without being the best foundation for a decision about a full phrase. The authors connect their finding to prior work on Linguistic Knowledge and Transferability of Contextual Representations.
Choosing too high a cutoff also reduces quality. The accumulated links toward the top of the stack tend to be close to 1. At that stage, many positions are already strongly connected, leaving fewer clear distinctions between the gaps. Those layers can offer a broad context for the encoder while offering little evidence about which smaller spans to split. The best lower cutoff therefore sits between early local evidence and late links that have mostly saturated.
The analysis varies extraction depth while keeping the learned architecture in place. A lower layer can be useful to the forward pass even if greedy splitting from its scores gives poor brackets. Information passed onward from that layer can affect both the representations and the links at subsequent layers. The cutoff determines which scores are useful to a specific reader of the network, the parser, after training has finished.
What an individual layer supplies
To examine how useful each layer is by itself, the authors apply greedy extraction to the accumulated links from each layer in turn. Layer 3 produces the strongest single-layer result, with WSJ-test F1 of 49.07. That coincides with the best lower cutoff in the multilayer procedure. The scores at that depth thus work both as a standalone source of boundaries and as the earliest permitted evidence in the better multilayer extraction.
The multilayer result of 52.0 gives a direct comparison with that single-layer approach. Information accessible through the whole extraction procedure leads to better bracket agreement than the best fixed selection of a layer. The authors interpret the result as evidence that later layers add higher-level structure, including patterns at the level of clauses. A later layer can help identify a broad division, after which an earlier layer supplies sharper distinctions inside the parts.
The comparison changes more than the quantity of link scores available. The multilayer procedure also decides when to accept a weak link and when to look at a different layer. The scores support the value of that combination of learned links and extraction rules. A claim about which particular rule accounts for the gain would require comparisons that vary those choices individually.
Varying the total depth addresses a related question during training. A deeper stack gives the link update more stages in which to build larger groups. The paper’s parsing results improve with additional layers until they level off above 10. That behavior is consistent with the authors’ observation that the upper layers can approach a state of broad connectivity. Adding stages after that point provides a diminished source of boundary distinctions for the parser, even though the added stages still participate in encoding.
Why the local normalization and positional encoding matter
The authors describe a failure mode when neighboring softmax is removed. A word can then give strong scores to both sides without the competition imposed by the local probability distribution. The system tends to join the words into a single group. In terms of the pairwise prior, strong links across the sequence allow distant positions to interact freely, weakening the architectural pressure towards early separation into phrases.
This observation explains the specific role of softmax in the local module. The structural bias requires opportunities to give some gaps a lower score than others. If prediction can be made easier by letting information flow everywhere immediately, the word objective can favor that shortcut. The local competition makes it harder for each position to endorse both adjacent connections strongly at once. The paper describes the failure qualitatively, so its value is in identifying a tendency of the learned links under this change.
The authors also try removing positional encoding and report a drop in induced parse quality. Positional encoding gives the encoder information about a token’s place in the sequence. Constituent Attention already has access to local order through its definition of a neighbor, and the prior uses gaps along the ordered path between positions. The removal experiment shows that these provisions still leave value in the ordinary positional signal. The paper retains positional encoding in the reported architecture.
The authors suggest that the learned structure provides additional positional information in practice. Earlier layers favor nearer information, and later layers can reach across the larger spans that have formed. The removal result concerns the ordinary positional encoding. The idea that hierarchical growth itself supplies positional information is an interpretation of how the resulting encoder organizes its attention.
Starting with pretrained BERT
A further comparison changes initialization. The authors initialize the encoder from pretrained BERT and then carry out fine-tuning on WSJ-train. They report that this route can reach lower training loss than training from scratch while producing parses well below their best results. Good fit to the training objective and agreement with the treebank therefore come apart in this setup.
Their explanation is that the pretrained heads already learned a different organization for processing the sentence. With those representations in place, the encoder can keep reducing the prediction loss without developing strong phrase boundaries in the added module. This is a difference in what the training signal asks of a fresh encoder and an encoder that already makes effective use of context. When useful computations are available early in training, the pressure to reorganize them around the new prior may be weaker.
The comparison provides a concrete check on how to interpret the word objective. Masked word prediction serves as the signal for learning the links, but a low prediction loss can be reached through more than one organization of attention. A parser still needs its own evaluation if the intended outcome is an analysis that agrees with annotated constituents.
What the attention plots reveal
The paper uses two kinds of heat maps to examine interpretability. The first displays the constituent prior. A cell indicates the strength with which the layer treats its row and column positions as part of the same group. Early in the displayed example, the strong regions are small and close to the diagonal. The authors identify short nominal groupings in them, including the words around “american airlines unit.” The diagonal location reflects the small distance between positions, and the blocks show which nearby positions receive stronger support together.
In later layers, the blocks grow. At layer 6, the authors identify a broad span beginning at “involved” and extending through “lines,” which they analyze as an adjective phrase. At layer 9, the displayed grouping covers the sentence apart from its opening “but.” This last detail gives a sentence-level illustration of saturation together with a boundary that remains perceptible near the top. The size of the block follows the hierarchy constraint, while its endpoints provide evidence about which spans the trained module favored.
The appendix plots the actual attention weights for an ordinary Transformer and Tree Transformer. Each display averages the heads of a layer. That operation gives an overview of where attention goes across the layer and can smooth over head-specific differences. The tree-guided encoder shows early interactions among nearby words, including some within-phrasal links the authors identify, followed by attention across wider spans. The ordinary encoder in the comparison also attends strongly to nearby words in its first layer. By its third layer, the visible attention is more widely distributed.
The distinction between the two plots is important for the authors’ interpretation. A constituent-prior plot shows which routes the added module favors. An attention plot shows where the heads put weight after that structural signal has been applied. The first makes it possible to locate a learned boundary. The second shows how visible that boundary is in attention as a whole. The comparison supports the narrower claim that the tree-guided architecture makes a progression from smaller to larger spans easier to see.
The label analysis puts those examples in context. The paper can display an adjective phrase that appears clearly in an individual sentence while reporting weaker adjective-phrase recall in aggregate. A successful example shows the kind of span the system can learn. Constituent recall shows how consistently a category appears among its recovered spans. The results also allow different induction methods to have different profiles even when their overall bracket scores summarize them on the same scale.
Limitations
Limits the authors identify
The initialization experiment is the paper’s clearest stated limitation. The authors obtain a lower training loss in some runs started from pretrained BERT while finding that the induced parses remain poorer than their best results. They interpret this as a consequence of attention having already acquired a useful organization for prediction. The added module may then contribute little syntax that the extraction procedure can recover. A training objective that permits several effective ways to use context leaves room for this outcome.
The authors also identify a limit to increasing depth. High layers tend to give very strong accumulated links, so their scores offer weak evidence for individual breakpoints. The improvement in parsing stops above a depth of 10 in the reported comparison. For extraction, an upper layer whose words are all close to sharing one constituent has largely lost the distinction between the boundaries of smaller phrases. Its broad connectivity can still serve the encoder’s prediction task.
The choice of the bottom layer and the acceptance threshold belong to the parsing procedure. The authors say that including the lowest layers hurts parse quality and that their parser is relatively insensitive to the particular threshold, which they set at 0.8. Dependence on a bottom cutoff follows from their observation that the most useful layer range is narrower than the full stack. These decisions qualify the idea that a tree is simply present in the attention weights. The learned links supply graded evidence, and the extraction procedure decides which evidence becomes a branch.
The paper also marks limits on direct comparisons. DIORA and URNNG use larger training resources and somewhat different evaluation settings, and some short-sentence baselines receive part-of-speech information. Results under those conditions describe each system’s behavior with its own inputs and evaluation choices. The authors use the comparisons with more closely matched conditions to give a clearer point of reference.
Limits of the evidence in the setup
The experiments on WSJ-train and WSJ-all answer different questions. The grammar induction condition trained on WSJ-all can encounter the text of the test sentences while learning to predict words. It still receives no reference trees in that objective. Its parsing score measures agreement with reference brackets in a setting that allowed access to the test text. The separately trained masked word comparison uses WSJ-train and evaluates on WSJ-test. The stronger condition for an unfamiliar-text interpretation comes from experiments with that kind of separation between the splits.
The motivation about scarce annotations is broader than the corpus used for evaluation. A system that learns from raw text offers a plausible route to analyzing data for which gold trees are unavailable during training. The paper’s parsing experiments establish evidence on written English from the Wall Street Journal. Performance on other languages, genres, and domains is an open question in the scope of these experiments. A corresponding evaluation would need a way to inspect or score the induced structures where the training assumption about labels is most useful.
The two prediction and parsing metrics also have distinct meanings. Masked word perplexity measures how much probability the encoder assigns to a missing word when the rest of its sentence is available. The deterministic masking procedure gives it the same kind of surrounding evidence at every test position. Bracket F1 measures agreement with selected phrase boundaries in human analyses. Lower perplexity can be achieved with cues other than constituent structure, as the initialization comparison illustrates. Better bracket agreement says more about recovering spans than it does about how well a sentence can be generated from left to right or how well its representations transfer to another task.
The comparison with a larger ordinary Transformer weakens an explanation based completely on parameter count. It leaves several aspects of the new architecture bundled together. The prior favors interaction within a learned span, it tends to restrict attention over more intervening gaps, and its application after softmax can reduce the total attention weight contributed to a position. The reported comparisons establish what happens when this combination is present. They give less direct evidence about which of its effects is responsible for the perplexity advantage.
The link values also have an architectural reason to grow with depth. Their monotone update ensures that earlier links remain available. An expanding block in a heat map therefore illustrates how the constraint works. Where the blocks form, where a boundary persists, and how well the resulting spans agree with annotated trees provide the additional evidence that those patterns convey something about the sentence. The label-specific recall makes that evidence more precise by identifying categories for which span recovery is weaker.
Attention averages give a readable picture of a layer’s preferences, with limits on the conclusions they support about an individual prediction. A shared prior can guide every head while those heads distribute their own weights differently. Averaging hides some of those differences. The visualizations show where structural restrictions appear and how the distribution of weights changes across layers. Establishing the influence of a particular link or head on a chosen word prediction would require a comparison that changes it and observes the resulting prediction.
Finally, the extracted tree has the representational limits of the method. It consists of continuous spans found by deciding where to split an ordered sequence. The extraction procedure returns brackets, and the analysis by constituent type uses the reference labels to assess them. A correct span can therefore count as a recovered noun phrase even though the procedure supplied its boundaries alone. Learning a useful hierarchy of spans, assigning grammatical labels to them, and recovering the syntax of other kinds of text are distinct evaluation targets.
What came after
The citing works take attention and structure into several different settings. The titles indicate where that connection lies in each case, from grammar in a Transformer to discourse in long-form generation and attention during logical reasoning. A citation establishes that the later work refers to Tree Transformer. Carrying over the adjacent-word scores, cumulative links, shared prior, or extraction procedure would be a more specific relationship.
Syntax as a bias in Transformer grammars
Transformer Grammars (2022) addresses the closest question to the original paper. It aims to add syntactic inductive biases to Transformer language processing at scale. An inductive bias is a preference built into a system that makes certain kinds of solution easier for it to learn or express. Tree Transformer gives a concrete example of such a preference. It makes information exchange within learned constituents easier early in the stack and allows those constituents to grow as links strengthen.
The later work’s stated focus places the relationship between grammar and the Transformer at the center. The original paper shows how to express a constituency preference through relative link strengths trained by masked prediction. A grammar-centered design raises the related question of how syntactic composition can be made part of a Transformer’s computation at scale. The shared subject is the effect of building grammatical structure into the architecture.
From sentence constituents to discourse control
RSTGen (2022) pursues fine-grained, interpretable control in text generation, specifically for longer texts. That brings the connection into discourse analysis, where the units of interest can extend beyond individual phrases. The aim of control gives structure a different job. Tree Transformer learns a sentence’s grouping while building its representations, and a reader can inspect that grouping afterwards. In long-form generation, interpretable control concerns how a structural choice can help steer the output.
Both settings make the organization of text an explicit part of the problem. The unit of organization and the intended result differ. In the earlier paper, the reference for the learned grouping is a set of sentence brackets. In RSTGen’s stated aim, the outcome is more controllable long-form composition. The relationship sits at the level of using readable structure to shape the processing of language.
Attention as a point of intervention in reasoning
Improving Chain-of-Thought for Logical Reasoning via Attention-Aware Intervention (2026) treats attention as a place to intervene in reasoning. Its stated objective concerns chains of reasoning. Tree Transformer applies a structural intervention during sentence encoding. Each constituent weight controls how strongly attention can cross a particular span at a given layer. In both cases, attention is part of the computation being changed, so it offers a way to influence which information is brought together.
The outcome of interest has shifted from phrase induction and missing-word probabilities to logical reasoning. Bracket agreement and attention heat maps answer the questions posed by Tree Transformer. They could say little by themselves about the validity of a chain of reasoning. This difference gives the citing connection a clear scope. The original study tests whether directing attention through learned groupings can change what a Transformer recovers from a sentence and how visibly it organizes that information. The later work takes the idea of intervening on attention into a task whose success depends on the reasoning it produces.
Cite
Cite as Yaushian Wang, Hung-Yi Lee and Yun-Nung Chen. 2019. Tree Transformer: Integrating Tree Structures into Self-Attention. Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP).
@inproceedings{wang2019tree,
title = {{Tree Transformer: Integrating Tree Structures into Self-Attention}},
author = {Yaushian Wang, Hung-Yi Lee and Yun-Nung Chen},
booktitle = {Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP)},
year = {2019},
doi = {10.18653/v1/d19-1098},
eprint = {1909.06639},
archivePrefix = {arXiv},
url = {https://doi.org/10.18653/v1/d19-1098}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/wang-2019-tree-transformer-integrating-tree-structures/
References
- Roee Aharoni and Yoav Goldberg. 2017. Towards string-to-tree neural machine translation (https://www.aclweb.org/anthology/P17-2021). In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers). our card
- Rens Bod. 2006. An all-subtrees approach to unsupervised parsing (https://doi.org/10.3115/1220175.1220284). In Proceedings of the 21st International Conference on Computational Linguistics and the 44th Annual Meeting of the Association for Computational Linguistics. OpenAlex ↗ · Scholar ↗
- Glenn Carroll and Eugene Charniak. 1992. Two experiments on learning probabilistic dependency grammars from corpora. In WORKING NOTES OF THE WORKSHOP STATISTICALLY-BASED NLP TECHNIQUES. OpenAlex ↗ · Scholar ↗
- C.Goller and A.Kuchler. 1996. Learning task-dependent distributed representations by backpropagation through structure. In Proceedings of International Conference on Neural Networks (ICNN'96). OpenAlex ↗ · Scholar ↗
- Ciprian Chelba, Tomas Mikolov, Mike Schuster, Qi Ge, Thorsten Brants, Phillipp Koehn, and Tony Robinson. 2013. One billion word benchmark for measuring progress in statistical language modeling. arXiv preprint arXiv:1312.3005. our card
- Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805. our card
- Li Dong, Nan Yang, Wenhui Wang, Furu Wei, Xiaodong Liu, Yu Wang, Jianfeng Gao, Ming Zhou, and Hsiao-Wuen Hon. 2019. Unified language model pre-training for natural language understanding and generation. arXiv preprint arXiv:1905.03197. our card
- Andrew Drozdov, Pat Verga, Mohit Yadav, Mohit Iyyer, and Andrew McCallum. 2019. Unsupervised latent tree induction with deep inside-outside recursive autoencoders. In North American Association for Computational Linguistics. OpenAlex ↗ · Scholar ↗
- Chris Dyer, Adhiguna Kuncoro, Miguel Ballesteros, and Noah A. Smith. 2016. Recurrent neural network grammars. In Proc. of NAACL. our card
- Akiko Eriguchi, Yoshimasa Tsuruoka, and Kyunghyun Cho. 2017. Learning to parse and translate improves neural machine translation (https://www.aclweb.org/anthology/P17-2012). In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers). our card
- Phu Mon Htut, Kyunghyun Cho, and Samuel Bowman. 2018. Grammar induction with neural language models: An unusual replication (https://www.aclweb.org/anthology/W18-5452). In Proceedings of the 2018 EMNLP Workshop BlackboxNLP: Analyzing and Interpreting Neural Networks for NLP. Association for Computational Linguistics. OpenAlex ↗ · Scholar ↗
- Yoon Kim, Chris Dyer, and Alexander Rush. 2019a. Compound probabilistic context-free grammars for grammar induction (https://www.aclweb.org/anthology/P19-1228). In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 2369–2385. our card
- Yoon Kim, Alexander M. Rush, Lei Yu, Adhiguna Kuncoro, Chris Dyer, and Gábor Melis. 2019b. Unsupervised recurrent neural network grammars. arXiv preprint arXiv:1904.03746. our card
- Dan Klein and Christopher D. Manning. 2002. A generative constituent-context model for improved grammar induction (https://www.aclweb.org/anthology/P02-1017). In Proceedings of 40th Annual Meeting of the Association for Computational Linguistics. our card
- Dan Klein and Christopher D. Manning. 2005. Natural language grammar induction with a generative constituent-context model (http://dx.doi.org/10.1016/j.patcog.2004.03.023). Pattern Recogn. OpenAlex ↗ · Scholar ↗
- Nelson F. Liu, Matt Gardner, Yonatan Belinkov, Matthew E. Peters, and Noah A. Smith. 2019. Linguistic knowledge and transferability of contextual representations. arXiv preprint arXiv:1903.08855. our card
- Mitchell P. Marcus, Mary Ann Marcinkiewicz, and Beatrice Santorini. 1993. Building a large annotated corpus of english: The penn treebank (http://dl.acm.org/citation.cfm?id=972470.972475). Comput. Linguist. our card
- Alec Radford, Jeff Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. OpenAlex ↗ · Scholar ↗
- Yikang Shen, Zhouhan Lin, Chin wei Huang, and Aaron Courville. 2018a. Neural language modeling by jointly learning syntax and lexicon (https://openreview.net/forum?id=rkgOLb-0W). In International Conference on Learning Representations. OpenAlex ↗ · Scholar ↗
- Yikang Shen, Shawn Tan, Alessandro Sordoni, and Aaron Courville. 2018b. Ordered neurons: Integrating tree structures into recurrent neural networks. arXiv preprint arXiv:1810.09536. OpenAlex ↗ · Scholar ↗
- Noah A. Smith and Jason Eisner. 2005. Guiding unsupervised grammar induction using contrastive estimation. In In Proc. of IJCAI Workshop on Grammatical Inference Applications. OpenAlex ↗ · Scholar ↗
- Richard Socher, Cliff Chiung-Yu Lin, Andrew Y. Ng, and Christopher D. Manning. 2011. Parsing natural scenes and natural language with recursive neural networks. In Proceedings of the 28th International Conference on International Conference on Machine Learning. OpenAlex ↗ · Scholar ↗
- Emma Strubell, Patrick Verga, Daniel Andor, David I Weiss, and Andrew McCallum. 2018. Linguistically-informed self-attention for semantic role labeling. In EMNLP. our card
- Kai Sheng Tai, Richard Socher, and Christopher D. Manning. 2015. Improved semantic representations from tree-structured long short-term memory networks. arXiv preprint arXiv:1503.00075. our card
- Jesse Vig. 2019. Visualizing attention in transformer-based language representation models. arXiv preprint arXiv:1904.02679. OpenAlex ↗ · Scholar ↗
- Adina Williams, Nikita Nangia, and Samuel Bowman. 2018. A broad-coverage challenge corpus for sentence understanding through inference (https://www.aclweb.org/anthology/N18-1101). In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers). our card
- Wei Wu, Houfeng Wang, Tianyu Liu, and Shuming Ma. 2018. Phrase-level self-attention networks for universal sentence encoding (https://www.aclweb.org/anthology/D18-1408). In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pages 3729–3738. OpenAlex ↗ · Scholar ↗
- Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V. Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, and et al. 2016. Google's neural machine translation system: Bridging the gap between human and machine translation (http://arxiv.org/abs/1609.08144). arXiv preprint arXiv:1609.08144. OpenAlex ↗ · Scholar ↗
- Dani Yogatama, Phil Blunsom, Chris Dyer, Edward Grefenstette, and Wang Ling. 2017. Learning to compose words into sentences with reinforcement learning. In International Conference on Learning Representations. OpenAlex ↗ · Scholar ↗
- Poorya Zaremoodi and Gholamreza Haffari. 2018. Incorporating syntactic uncertainty in neural machine translation with a forest-to-sequence model (https://www.aclweb.org/anthology/C18-1120). In Proceedings of the 27th International Conference on Computational Linguistics. OpenAlex ↗ · Scholar ↗