Title: TREE-STRUCTURED ATTENTION WITH HIERARCHICAL ACCUMULATION

Abstract: Incorporating hierarchical structures like constituency trees has been shown to be effective for various natural language processing (NLP) tasks. However, it is evident that state-of-the-art (SOTA) sequence-based models like the Transformer struggle to encode such structures inherently. On the other hand, dedicated models like the Tree-LSTM, while explicitly modeling hierarchical structures, do not perform as efficiently as the Transformer. In this paper, we attempt to bridge this gap with "Hierarchical Accumulation" to encode parse tree structures into selfattention at constant time complexity. Our approach outperforms SOTA methods in four IWSLT translation tasks and the WMT'14 English-German translation task. It also yields improvements over Transformer and Tree-LSTM on three text classification tasks. We further demonstrate that using hierarchical priors can compensate for data shortage, and that our model prefers phrase-level attentions over token-level attentions. * Work done during an internship at Salesforce Research Asia, Singapore. 1 Given GPUs, a "constant parallel time" process can perform all its computations at once algorithmically.

1. INTRODUCTION:

Although natural language has a linear surface form, the underlying construction process is known to be hierarchical (Frege, 1892) . As such, different tree-like structures have been proposed to represent the compositional grammar and meaning of a text, such as constituency and dependency trees. Leveraging the hierarchical structures of language gives models more structural information about the data and improves performance on the downstream tasks (Tai et al., 2015; Eriguchi et al., 2016) . Despite that, state-of-the-art neural models like the Transformer still prefer the linear (sequential) form of natural language (Vaswani et al., 2017; Ott et al., 2018; Devlin et al., 2018) . This is because the linear form allows us to develop simple but efficient and scalable techniques (like self-attention which operates at constant parallel time complexity 1 ) to train models at a large scale. Yet, there is still no concrete evidence that these models learn grammatical and constituency structures implicitly. However, ad hoc tree-structured models (Socher et al., 2013; Tai et al., 2015; Shi et al., 2018) often operate on recursive or recurrent mechanisms, which are not parallelizable, thus hindering their application in larger-scale training. Besides, such models are designed to only operate at the sentence-level (i.e., single tree), limiting their application to document-level processing.

We propose a novel attention-based method that encodes trees in a bottom-up manner and executes competitively with the Transformer at constant parallel time complexity. In particular, our attention layers receive as input the constituency tree of a piece of text and then model the hidden states of all nodes in the tree (leaves and nonterminals) from their lower-layer representations according to the tree structure. As attentions typically have query, key and value components, our model uses hierarchical accumulation to encode the value component of each nonterminal node by aggregating the hidden states of all of its descendants. The accumulation process is three-staged. First, we induce the value states of nonterminals with hierarchical embeddings, which help the model become aware of the hierarchical and sibling relationships between the nodes. Second, we perform an upward cumulative-average operation on each target node, which accumulates all elements in the branches originating from the target node to its descendant leaves. Third, these branch-level representations are combined into a new value representation of the target node by using weighted aggregation. Finally, the model proceeds to perform attention with subtree masking where the attention score between a nonterminal query and a key is activated only if the key is a descendant of the query.

Our contributions are threefold. First, we present our attention-based hierarchical encoding method. Our method overcomes linear parallel time complexity of Tree-LSTM (Tai et al., 2015) and offers attractive scalability. Second, we adopt our methods within the Transformer architecture and show improvements across various NLP tasks over strong baselines. In particular, our model leverages tree-based prior to improve translation quality over the Transformer baselines in the IWSLT'14 English-German and German-English, the IWSLT'13 English-French and French-English, and the WMT'14 English-German translation tasks. Furthermore, our model also exhibits advantages over Tree-LSTM in classification tasks including Stanford Sentiment Analysis (SST) (Socher et al., 2013) , IMDB Sentiment Analysis and Subject-Verb Agreement (Linzen et al., 2016) . Finally, our analysis of the results suggests that incorporating a hierarchical prior using our method can compensate for the lack of data in the context of machine translation. We also demonstrate that the model has natural and consistent preference for phrase-level attention over token-level attention. Our source code is available at https://github.com/nxphi47/tree transformer.

2. RELATED WORK:

The Transformer framework has become the driving force in recent NLP research. For example, it has achieved state-of-the-art performance in machine translation tasks (Vaswani et al., 2017; Shaw et al., 2018; Ott et al., 2018; Wu et al., 2019) and self-supervised representational learning (Devlin et al., 2018; Radford et al., 2018; Lample & Conneau, 2019; Yang et al., 2019) . The self-attention layers in the Transformer encode a sequence at constant parallel time complexity, which makes it parallelizeable and scalable. On the other hand, there have been many proposals to use parse trees as an architectural prior to facilitate different downstream tasks. Socher et al. (2013) adopt a recursive compositional method over constituency trees to solve sentiment analysis in a bottom-up manner. Tree-LSTM (Tai et al., 2015) improves the task performance by using an LSTM structure to encode trees recurrently. Both of the proposed methods, while effective, operate sequentially in parallel time complexity. Tree structures have also been used as an architectural bias to improve machine translation (Eriguchi et al., 2016; Shi et al., 2018; Yang et al., 2017) . Constituency trees can also be decoded in a top-down manner, as proposed in (Alvarez-Melis & Jaakkola, 2017; Gū et al., 2018) . Besides, they can also be learned in an unsupervised way (Kim et al., 2019; Shen et al., 2018; 2019; Yaushian Wang & Chen, 2019) . Meanwhile, Strubell et al. (2018) ; Hao et al. (2019) ; Harer et al. (2019) attempted to incorporate trees into self-attention. Hewitt & Manning (2019) showed that dependency semantics are already intrinsically embedded in BERT (Devlin et al., 2018) . Concurrently, Yaushian Wang & Chen (2019) suggested that BERT may not naturally embed constituency semantics.

Our approach encodes trees in a bottom-up manner as Tai et al. (2015) and Socher et al. (2013) . But it differs from them in that it leverages the attention mechanism to achieve high efficiency and performance. Plus, it is applicable to self-and cross-attention layers in the Transformer sequenceto-sequence (Seq2Seq) skeleton. Unlike previous methods, our model works with multi-sentence documents (multi-tree) seamlessly. Our model also differs from Strubell et al. (2018) ; Hao et al. (2019) ; Harer et al. (2019) in that their methods only use tree structures to guide and mask tokenlevel attentions, while ours processes all the nodes of the tree hierarchically. In this paper, while applicable to dependency trees, our approach focused primarily on constituency trees because (1) constituency trees contain richer grammatical information in terms of phrase structure, and (2) there is as yet no evidence, to the best of our knowledge, that constituency structures are learned implicitly in the standard self-supervised models.

3. BACKGROUND -TRANSFORMER FRAMEWORK:

The Transformer (Vaswani et al., 2017) is a Seq2Seq network that models sequential information using stacked self-and cross-attention layers. The output O of each attention sub-layer is computed via scaled multiplicative formulations defined as: 

A = (QW Q )(KW K ) T / √ d; Att(Q, K, V ) = softmax(A)(V W V ) (1)

O = Att(Q, K, V )W O (2) where softmax is the softmax function, Q = (q 1 , ..., q lq ) ∈ R lq×d , K = (k 1 , ..., k l k ) ∈ R l k ×d , V = (v 1 , ..., v l k ) ∈ R l k ×d

are matrices of query, key and value vectors respectively, and W Q , W K , W V , W O ∈ R d×d are the associated trainable weight matrices. A denotes the affinity scores (attention scores) between queries and keys, while Att(Q, K, V ) are the attention vectors. Then, the final output of a Transformer layer is computed as:

EQUATION

where φ represents the typical serial computations of a Transformer layer with layer normalization (LN) and feed-forward (FFN) layers. For simplicity, we omit the multi-head structure and other details and refer the reader to Vaswani et al. (2017) for a complete description.

4. TREE-BASED ATTENTION:



4.1. ENCODING TREES WITH HIERARCHICAL ACCUMULATIONS:

To encode hierarchical structures in parallel, we need to represent the tree in a data structure that can be parallellized. Given a sentence X of length n, let G(X) be the directed spanning tree which represents the parse tree of X produced by a parser. We define a transformation H such that H(G(X)) = T (X) ∆ = (L, N , R). In this formulation, L denotes the ordered sequence of n terminal nodes (or leaves) of the tree (i.e., L = X), and N denotes the set of m nonterminal nodes (or simply nodes), each of which has a phrase label (e.g., NP, VP) and spans over a sequence of terminal nodes.2 R contains a set of rules indexed by the nonterminal nodes in N such that for each node x ∈ N , R(x) denotes the set of all nodes that belong to the subtree rooted at x. For example, for the nonterminals g and h in Figure 1 , R(g) = {g, c, h, d, e} and R(h) = {h, d, e}.

There might be various ways to transform the tree G(X). For a tree-encoding process, a particular transformation is legitimate only if the resulting data structure represents only G(X) and not any other structures. Otherwise, the encoding process may confuse G(X) with another structure. In other words, the transformation should be a one-to-one mapping. Our transformation H satisfies this requirement as shown in the following proposition (see Appendix 7.1 for a proof).

Proposition 1 Suppose G(X) is a parse tree and there exists a inverse-transformation I that converts T (X) to a graph I(T (X)), then I can only transform T (X) back to G(X), or:

I(H(G(X))) = G(X) or I = H -1 (4)

We now describe the tree accumulation method using T (X). Figure 1 shows the overall process. Let L = (l 1 , ..., l n ) ∈ R n×d and N = (n 1 , ..., n m ) ∈ R m×d be the hidden representations of the leaves L = (x L 1 , ..., x L n ) and nodes N = (x N 1 , ..., x N m ), respectively. We define an interpolation function F : (R n×d , R m×d ) → R (m+1)×n×d , which takes L, N and R as inputs and returns a tensor S ∈ R (m+1)×n×d . The row i and column j vector of S, or S i,j ∈ R d , is defined as:

S i,j = F(L, N , R) i,j =    l j if i = 1 n i-1 else if x L j ∈ R(x N i-1 ) 0 otherwise.

(

EQUATION

where 0 denotes a zero vector of length d. Note that the row and column arrangements in S reflect the tree structure (see Figure 1 ). Next, we perform the upward cumulative-average (upward-CA) operation U on S to compose the node representations in a bottom-up fashion over the induced tree structure. The result of this operation is a tensor Ŝ ∈ R m×n×d , in which each nonterminal node representation is averaged along with all of its descendants in a particular branch. More formally,

EQUATION

)

where

C i j = {S 1,j } ∪ {S t,j |x N t ∈ R(x N i )}

is the set of vectors in S representing the leaves and nodes in the branch that starts with x N i and ends with x L j . Note that we discard the leaves in Ŝ. As demonstrated in Figure 1 , each row i of Ŝ represents a nonterminal node x N i and each entry Ŝi,j represents its vector representation reflecting the tree branch from x N i to a leaf x L j . This gives |R(x N i ) ∩ L| different constituents of x N i that represent the branches rooted at x N i . The next task is to combine the branch-level accumulated representations of a nonterminal x N i into a single vector n i that encapsulates all the elements in the subtree rooted by x N i . Our method does so with a weighted aggregation operation. The aggregation function V takes Ŝ as input and a weighting vector w ∈ R n , and computes the final node representations N = (n 1 , ..., n m ) ∈ R m×d , where each row-vector n i in N is computed as:

EQUATION

where denotes the element-wise multiplication. Specifically, the aggregation function V computes a weighted average of the branch-level representations. In summary, the hierarchical accumulation process can be expressed as the following equation: While the above technique is able to model the states of nonterminal nodes as an encapsulation of their respective descendants, those descendants are equally treated since no biases are imposed on them. In other words, although each branch from a node comprises a distinctive set of descendants, the hierarchy of elements within a branch and the sibling relationship among branches are not explicitly represented. Thus, it may be beneficial to introduce biases that reflect such underlying subtreelevel hierarchical structures. We propose Hierarchical Embeddings to induce distinguishable tree structures into the tensor S before being accumulated by U and V. We also demonstrate the effectiveness of these embeddings with experiments in Section 5. Figure 2 illustrates the hierarchical embeddings for the nodes in Figure 1 . Given L, N and R as defined in Section 4.1, we construct a tensor of hierarchical embeddings E ∈ R (m+1)×n×d with entries defined as follows:

EQUATION

EQUATION

)

where

V i j = {x N t |x N t ∈ R(x N i ) and x L j ∈ R(x N t )

} is the set of x L j 's ancestors up to x N i , and

H i j = {x L t |t ≤ j and x L t ∈ L ∩ R(x N i )}

is the set of leaves from the leftmost leaf up to x L j of the x N i -rooted subtree; e v i and e h i are embedding row-vectors of the respective trainable vertical and horizontal embedding matrices

E v , E h ∈ R |E|× d 2 and [•;

•] denotes the concatenation operation in the hidden dimension. The vertical embeddings represent the path length of a node to a leaf which expresses the hierarchical order within a branch, whereas the horizontal embeddings exhibit the relationship among branch siblings in a subtree. The resulting node representations after hierarchical encoding are defined as:

EQUATION

Note that we share such embeddings across attention heads, making them account for only 0.1% of the total parameters (see Appendix 7.3 for more information).

4.3. SUBTREE MASKING:

Figure 3 : Subtree masking.

Given the query at position g, attentions are only included within the g-rooted subtree, while the remaining elements are masked out (shaded).

Masking attentions is a common practice to filter out irrelevant signals. For example, in the decoder self-attention layers of the Transformer, the affinity values between query q i and key k j are turned off for j > i to avoid future keys being attended since they are not available during inference. This can be done by adding to the affinity q T i k j an infinitely negative value (-∞) so that the resulting attention weight (after softmax) becomes zero.

In the context of tree-based attentions (to be described next), we promote the bottom-up structure by introducing subtree masking for encoder self-attention. 3 That is, if a node-query q N i ∈ N is attending to a set of node-keys k N j ∈ N and leaf-keys k L j ∈ L, attentions are turned on only for affinity pairs whose key belongs to the subtree rooted at q N i . In other words, each node-query has access only to its own subtree descendants, but not to its ancestors and siblings. On the other hand, if a leaf-query q L i ∈ L is attending, only leaf-keys are turned on, like in the Transformer. Figure 3 illustrates the subtree masking with an example. More formally, given a ij as the affinity value between a node/leaf-query q i ∈ N ∪L and a node/leaf-key k j ∈ N ∪L, the masking function µ is defined as:

µ(a ij ) = a ij if (q i ∈ N and k j ∈ R(q i )) or (q i , k j ∈ L) a ij -∞ otherwise.

(11)

4.4. INTEGRATING INTO TRANSFORMER FRAMEWORK:

In this section, we describe how the above proposed methods fit into self-and cross-attentions of the Transformer framework, which enable them to efficiently encode parse trees.

Encoder Self-attention. Figure 4a visualizes the encoder self-attention process. Without loss of generality, let L ∈ R n×d and N ∈ R m×d respectively denote the leaf and node representations that a Transformer encoder layer receives from its previous layer along with the parse tree represented as T (X) = (L, N , R). 4 The tree-based self-attention layer then computes the respective output representations L and N . Specifically, first, we compare the node and leaf representations against each other to produce query-key affinity matrices

A N L ∈ R m×n , A N N ∈ R m×m , A LL ∈ R n×n

and A LN ∈ R n×m for node-leaf (i.e., node representation as the query and leaf representation as the key), node-node, leaf-leaf, and leaf-node pairs, respectively, as follows:

EQUATION

)

EQUATION

Then, the value representation L of the leaves L is computed by a linear layer, while the value representation N of the nodes N is encoded with tree structure using the hierarchical accumulation process (Section 4.1-4.2) as:

EQUATION

where w = Lu s with u s ∈ R d being a trainable vector, while the weight matrices W Q , W K , W V , and W O are similarly defined as in Section 3. After this, the resulting affinity scores for leaves and nodes are concatenated and then masked by subtree masking (Section 4.3) to promote bottom-up encoding. The final attention for the nodes and leaves are then computed by taking the weighted averages of the value vectors in N and L:

Att N = softmax(µ([A N N ; A N L ]))[N ; L] (17) Att L = softmax(µ([A LN ; A LL ]))[N ; L] (18)

Both Att N and Att L are then passed through the Transformer's serial computations by function φ (Eq. 3 in Section 3), which results in the final output representations N and L as follows:

EQUATION

Decoder Cross-attention. For tasks involving generation (e.g., NMT), we also use tree-based encoder-decoder attention (or cross-attention) in the decoder so that the target-side queries can leverage the hierarchical structures in the source side (tree2seq). Figure 4b shows the cross-attention process. Specifically, given the target-side query matrix Q ∈ R t×d and the source-side leaf and node matrices L and N , the affinity scores A QN ∈ R t×m and A QL ∈ R t×n are computed as: 

EQUATION

Similar to encoder self-attention, the node representations N are encoded with the tree structure and the attention output Att Q of decoder cross-attention is computed as:

EQUATION

where w = Lu c with u c ∈ R d . Note that cross-attention does not adopt subtree masking because the queries are from another domain and are not elements of the source tree.

Remark on Speed. Our model runs competitively with the Transformer, thanks to its constant parallel time complexity. In terms of sequential (single-CPU) computations, the hierarchical accumulation process takes O(N log(N )) time and our entire model maintains a time complexity identical to the Transformer, which is O(N 2 ); see Appendix 7.2 for a proof.

5. EXPERIMENTS:

We conduct our experiments on two types of tasks: Machine Translation and Text Classification.

5.1. NEURAL MACHINE TRANSLATION:

Setup. We experiment with five translation tasks: IWSLT'14 English-German (En-De), German-English (De-En), IWSLT'13 English-French (En-Fr), French-English (Fr-En), and WMT'14 English-German. We replicate most of the training settings from Ott et al. (2018) for our models, to enable a fair comparison with the Transformer-based methods (Vaswani et al., 2017; Wu et al., 2019) . For IWSLT experiments, we trained the base models with d = 512 for 60K updates with a batch size of 4K tokens. For WMT, we used 200K updates and 32K tokens for the base models (d = 512), and 20K updates and 512K tokens for the big models with d = 1024. We parsed the texts with the Stanford CoreNLP parser (Manning et al., 2014) . We used Byte Pair Encoding (Sennrich et al., 2016) , where subwords of a word form a subtree. More details are provided in Appendix 7.4.

Results.:

Table 1 shows the BLEU scores for the translation tasks. Our models outperform the baselines consistently in all the tested tasks. The results demonstrate the impact of using parse trees as a prior and the effectiveness of our methods in incorporating such a structural prior. Specifically, our model surpasses the Transformer by more than 1 BLEU for all IWSLT tasks. Our big model also outdoes dynamic convolution (Wu et al., 2019 ) by 0.25 BLEU.

5.2. TEXT CLASSIFICATION:

Setup. We also compare our attention-based tree encoding method with Tree-LSTM ( 2013), IMDB Sentiment Analysis and Subject-Verb Agreement (SVA) (Linzen et al., 2016) tasks.

We adopt a tiny-sized version of our tree-based models and the Transformer baseline. The models have 2 Transformer layers, 4 heads in each layer, and dimensions d = 64. We trained the models for 15K updates, with a batch size of 2K tokens. Word embeddings are randomly initialized. We provide further details of the setup in Appendix 7.4. For the Stanford Sentiment Analysis task (SST), we tested on binary (SST-2) and fine-grained (SST-5) subtasks, following Tai et al. (2015) .

Results. Table 2 shows the results in accuracy on the classification tasks. Our Tree Transformer outperforms sequence-based Transformer and BiLSTM baselines in all tasks by a wide margin. This suggests that for small datasets, our models with a more appropriate structural bias can provide outstanding improvements compared to the vanilla Transformer. Furthermore, our models also surpass Tree-LSTM significantly in all the tested tasks, which also demonstrates our method's effectiveness compared to the best existing tree-encoding method. 

5.3. ANALYSIS:

Model Variations. In Table 3 , we examine the contributions of each component of our Tree Transformer on IWSLT'14 English-German translation task and Stanford Sentiment Analysis (finegrained) task. We see that removing either or both of hierarchical embeddings and subtree masking methods has a negative impact on the model performance.

Effectiveness on Small Datasets. Figure 5a shows how our model performs compared to the baselines on WMT'14 English-German translation task with varying amounts of training data. It is apparent that our model yields substantial improvements (3.3 to 1.6 BLEU) when the training data is less than 1 million pairs (< 20% of WMT'14). The margin of gains gradually decreases (1.0 to 1.1 BLEU) with increasing training data. We observe similar trend in the classification tasks (Table 2 ), where our model outperforms sequence-based methods by around 10% absolute in accuracy. This suggests that utilizing a hierarchical architectural bias can compensate for the shortage of labeled data in low-resource scenarios.

Training Time Analysis. Figure 5b shows the empirical training time and inference time for the Transformer, Tree-LSTM, and our Tree Transformer with respect to input sequence length. All the models are trained on a sentiment classification task on a single GPU for 1000 iterations with a batchsize of 1. We can see that the training time for Tree-LSTM grows linearly with the sequence length.

The training time for the vanilla and Tree Transformer are much less than that of the Tree-LSTM and remain relatively at a plateau with respect to the sequence length. This our model's speed efficiency compared to Tree-LSTM or other recurrent/recursive methods. For inference, we take into account the parsing time of the Stanford parser (O(N )), which substantially overwhelms the overall timing.

Phrase-vs. Token-level Attentions. Table 4 shows how frequently a target language token attends to phrases (nodes) vs. tokens (leaves) in the source tree. We see that although 60-66% of the source tree constituents are leaves, attentions over nodes overwhelm those over leaves (around 59% to 66%) consistently across all translation tasks, meaning that the model slightly favors phrasal attentions. The results also suggest that the attention concentrations are not correlated with the leaf/node ratio; rather, they depend on the language pairs. Leaf/node ratios might be a trivial explanation for the phenomenon, but the results indicate that certain language-dependent factors may be at play.

6. CONCLUSION:

We presented a novel approach to incorporate constituency parse trees as an architectural bias to the attention mechanism of the Transformer network. Our method encodes trees in a bottom-up manner with constant parallel time complexity. We have shown the effectiveness of our approach on various NLP tasks involving machine translation and text classification. On machine translation, our model yields significant improvements on IWSLT and WMT translation tasks. On text classification, it also shows improvements on Stanford and IMDB sentiment analysis and subject-verb agreement tasks.

7. APPENDIX:



7.1. PROOF FOR PROPOSITION 1:

In this section, we present a proof of Proposition 1. The main argument of this proposition is that in order for H to be a legitimate transformation of the parse tree G(X), it must preserve the uniqueness of the hierarchical structure encoded by the tree. Otherwise speaking, the result of such transformation must reflect the tree G(X) and only G(X), and not any other tree form. If does not have this property, it may transform two different tree structures into an identical representation, which will make the downstream tree-encoding process ambiguous. This property also means that in a parse tree (1) every node (either leaf or nonterminal node) has at most one parent, and (2) a nonterminal node which has multiple children can tell the sibling order between its children.

For requirement (1) specifically, except for the root node which has no parent, all other nodes have one and only one parent. Therefore, Proposition 1 implies that if there exists a inversetransformation I, it must be able to find the exact parent given any node in the tree. Our proposed transformation H satisfies this property. Formally, let x ∈ L∪N be a node in the tree and ρ(x) ∈ N be the parent of x. We define P(x) = {y ∈ N |x ∈ R(y)} to be the set of all ancestors of x. Thus, the parent of x should belong to P(x). From that, we derive the parent ρ(x) of x as: ρ(x) = y x ∈ P(x) such that R(y x ) ∩ P(x) = {y x } (25) As implied in Equation 25, the parent ρ(x) is one of the ancestors of x whose subtree does not encapsulate any of the ancestors in P(x) except itself. In other words, the parent is the immediate ancestor. In a parse tree, there is at most one node y x that satisfies this condition. We prove this by contradiction below.

Proof 1 Suppose there exists ρ (x) = y x = y x such that R(y x )∩P(x) = {y x }, i.e., x has 2 parents. Under this assumption, there will be two different paths from the root node to x -one via y x and the other via y x . This makes a closed cycle. However, a parse tree is an acyclic directed spanning tree, which does not have cycles. Thus, by contradiction, if G(x) is a spanning tree reflecting the true parse tree, then y x = y x .

For requirement (2), we can prove it by exploiting the fact that in the definition of T (X) ∆ = (L, N , R), L is ordered according to the original word order in the text. Generally speaking, if a nonterminal node x has t children (c 1 , ..., c t ), each child node c k heads (or bears) its own subtree R(c k ) which includes certain leaves R(c k ) ∩ L. Then, the order of leaves L indicates the order of different leaf sets R(c k ) ∩ L, which in turn indicates the sibling order of the children of node x.

Formally, let L = (l 1 , ..., l n ) where l i is the i-th word in the input text, and x is an arbitrary nonterminal node whose children are (c 1 , ..., c t ) (for t > 1) with any two of them being c k and c k (c kk ), then either:

EQUATION

We proceed to prove the first clause in Equation 26, while the second clause can be similarly inferred.

Specifically, the first clause in Equation 26 implies that if there exists a leaf l i ∈ R(c k ) ∩ L and a leaf l j ∈ R(c k ) ∩ L such that i < j , then i < j ∀l i ∈ R(c k ) ∩ L and ∀l j ∈ R(c k ) ∩ L, or in other words, subtree R(c k ) is to the left side of subtree R(c k ). We prove this by contradiction:

Proof 2 Suppose there exist l i , l i * ∈ R(c k ) ∩ L and l j , l j * ∈ R(c k ) ∩ L such that i < j but i * ≥ j * and not both i = i * and j = j * . If i * = j * , this creates a closed cycle, which is impossible as described in proof 1. If i * > j * , l j * lies between the leftmost and rightmost leaves of R(c k ) ∩ L. As a result, the subtree R(c k ) does not cover a full contiguous phrase but multiple segmented phrases, which is prohibited for a parse tree. Therefore, by contradiction, there can not exist

l i * ∈ R(c k ) ∩ L and l j * ∈ R(c k ) ∩ L such that i * ≥ j * .

In general, combing the satisfactions from the above requirements, the reverse-transformation I can convert T (X) = (L, N , R) back to the original graph G(X):

EQUATION

7.2. TIME COMPLEXITY ANALYSIS:

In this section, we prove that given single-thread sequential computation (single CPU), our method operates at O(N 2 ) time complexity. In short, the hierarchical accumulation process (Section 4.1) runs at O(N log N ) time, while the attention scores (QK T ) in standard attention are computed at O(N 2 ). Overall, the tree-based attention can performs at O(N 2 ) time complexity, same as the Transformer. We then proceed to analyze the time complexity of the hierarchical accumulation process. Formally, let X be a n-length sentence with T (X) = (L, N , R) as its balance binary constituency parse tree as defined in section 4, N ∈ R m×d and L ∈ R n×d be the hidden states of elements in N and L respectively. Therefore, there are m = n -1 non-terminal nodes in the tree, which is also the size of N . In the upward cumulative-average operation U, each branch from the root to a leaf has ≈ log(n) nodes, the cumulative operation of these nodes can be done at O(log(n)).

That is, because the result y i of each node x i can be computed as y i = y i-1 + x i , computations for all nodes in a branch take linear time using dynamic programming, yielding O(log(n)) time complexity. As we have n branches in the tree, the total complexity for U is O(n log(n)). Likewise, the weighted aggregation operation V is also computed at O(n log(n)) complexity. Specifically, at level i from the root of the tree, there i non-terminal nodes, which each has to aggregate n/i components Ŝi,j to calculate the final representation of the node. Thus, at each level, there are n computations. Because the total height of the tree is log(n), the time complexity of V is also O(n log(n)). Hence, the total complexity of hierarchical accumulation process is O(n log(n)). As such, the final sequential time complexity of the proposed attention layer is:

EQUATION

)

Having said that, in the era that powerful GPU-based hardware is ubiquitous, it is important to note that our models can achieve comparable parallelizability compared to the Transformer, while they can leverage the essence of hierarchical structures in natural languages. The purpose of the above time complexity analysis is only to show more insights about our models. That being said, even though we provide numerical analysis of training speed (figure 5b ) as objective as we could, training speed depends greatly on different subjective factors that may stray the actual timing away from its theoretical asymptotic time complexity. These factors are data preprocessing and batching, actual low-level and high-level programmatic implementation of the method, GPUs, CPUs, I/O hardwares, etc. For instance, a standard LSTM module in Tensorflow or Pytorch may performs 10 times slower than an LSTM with CUDA CuDNN kernels, even though no extra computations are theoretical required.

7.3. OVERALL ARCHITECTURE:

Figure 6 shows the overall Seq2Seq architecture of our model. In the encoder specifically, we parse the source sequence into constituency trees and then feed the leaf and node components into a stack of encoder layers. The leaf and node components are passed through the tree-based self-attention layer, where the value representation of node is incorporated with hierarchical accumulation. After that, the output representations of leaves and nodes are passed through a weight-shared series of layer normalizations and and feed-forward layer. In the decoder, the query representation of the target domain attends on the leaves and nodes representation of the source sequence as computed by the encoder. For more insights, apply hierarchical accumulation on the key components (instead on value components) causes dramatic performance because they are disrupted after being multiplied with the query components and they do not directly contribute to the representations of the outputs. Meanwhile, applying accumulation on attention scores does not yield performance benefits but increases computational burden.

Table 5 shows the exact number of parameters of the Transformer and our method. As it can be seen, the increase of parameters is almost unnoticeable because the hierarchical embedding modules share weights among different attention heads.

7.4. MORE DETAILED TRAINING CONFIGURATIONS:

Text Classification. We adopt the tiny size versions of our tree-based models as well as the transformer baseline. The models possess 2 transformer-layers, each has model dimension of 64, 4 heads. We trained the models for 15, 000 updates, with batch size of 2048 tokens. We Table 5 : Exact number of parameters for Transformer and our model, both used for WMT'14 English-German task.

used random initialized embeddings for all experiments. For the Stanford Sentiment Analysis task (SST), we tested on two subtasks: binary and fine-grained (5 classes) classification on the standard train/dev/test splits of 6920/872/1821 and 8544/1101/2210 respectively. We optimize every sentiment label provided in the dataset. We used a learning rate of 7 × 10 -4 , dropout 0.5 and 8000 warmup steps. For subject-verb agreement task, we trained on a set of 142, 000 sentences, validated on the set of ≈ 15, 700 sentences and tested on the set of ≈ 1, 000, 000 sentences. For IMDB sentiment analysis , we used a training set of 25, 000 documents and test set of 25, 000 documents.

As the documents are multi-sentence, they are added with a dummy root node which is used to predict the sentiment. For both subject-verb agreement and IMDB sentiment analysis, we trained models with 20 warmup steps, 0.01 learning rate and 0.2 dropout.

Machine Translation. We replicate most of the base training settings from Ott et al. (2018) for our models, to enable a fair comparison with transformer-based methods (Vaswani et al., 2017; Wu et al., 2019) . For IWSLT experiments, we trained the models with d = 512, feed-forward dimension d f f n = 1024, approximate batch size of 4000 tokens, 60, 000 updates, learning rate 5 × 10 -4 , 4000 warmup steps, dropout rate 0.3, L2 weight decay 10 -4 , beam size 5 and length penalty 1.0 for English-German and 0.7 for English-French. The hierarchical embedding size |E| is set to 100. We used BPE tokens pre-trained with 32, 000 iterations. Note that if a word is broken into multiple BPE subwords, it form a subtree with leaves as such subwords and root-node as the POS tag of the word. Figure 7 visualizes how this works. The IWSLT English-German training dataset contains ≈ 160, 000 sentence pairs, we used 5% of the data for validation and combined (IWSLT14.TED.dev2010,dev2012,tst2010-tst2012) for testing. Meanwhile, the IWSLT English-French task has ≈ 200, 000 training sentence pairs, we used IWSLT15.TED.tst2012 for validation and IWSLT15.TED.tst2013 for testing. We use the Stanford CoreNLP parser (v3.9.1)5 (Manning et al., 2014) to parse the datasets. For WMT experiments, we trained the models with d model = 512, feed-forward dimension d f f n = 2048, batch size of ≈ 32, 000 tokens, 200, 000 updates, learning rate 7 × 10 -4 , 4000 warmup steps, dropout rate 0.1, L2 weight decay 10 -4 , beam size 5 and length penalty 0.6. We take average of the last 5 checkpoints for evaluation. The WMT"14 English-German dataset contains ≈ 4.5M pairs. we tested the models on newstest2014 test set. We used tokenized-BLEU to evaluate the models.

:

We omit the part-of-speech tags of the words which constitute the preterminal nodes in a constituency tree.

It can only be done in the encoder self-attention.

For the first layer, L and N are token embeddings; L also has positional encodings.

http://nlp.stanford.edu/software/stanford-corenlp-full-2018-02-27.zip

Figures and Tables:

Figure 1: The hierarchical accumulation process of tree structures (best seen in colors). Given a parse tree, it is interpolated into a tensor S, which is then accumulated vertically from bottom to top to produce Ŝ. Next, the (branch-level) component representations of the nonterminal nodes are combined into one representation as N by weighted aggregation. Multi-colored blocks indicate accumulation of nodes of respective colors. The rows of S in Eq. 5 are counted from the bottom.

Figure 2: Hierarchical Embeddings. Each block E i,j is an embedding vector [e v x ; e h y ] with indices x, y following the syntax "x; y", where x = |V i j | and y = |H i j |. "0" indicates no embedding.

Figure 4: Illustration of the proposed Tree-based Attentions: (a) Encoder self-attention, (b) Decoder cross-attention. Circle-ended arrows indicate where hierarchical accumulations take place. The overall Transformer architecture is provided in Figure 6 (Appendix 7.3).

Figure 6: Overall architecture of Tree Transformer. (Dashed lines: sharing parameters)

BLEU scores for the base models on IWSLT'14 English↔German, IWSLT'13 English↔French, and the base and big models on WMT'14 English→German task. Refer to Table5in the Appendix for parameter comparisons.

Table content: <table><tr><td>Model</td><td/><td colspan="2">IWSLT</td><td/><td colspan="2">WMT En-De</td></tr><tr><td/><td colspan="5">En-De En-Fr De-En Fr-En Base</td><td>Big</td></tr><tr><td>Tree2Seq (Shi et al., 2018)</td><td>24.01</td><td>40.22</td><td>29.95</td><td>39.41</td><td/></tr><tr><td colspan="2">Conv-Seq2Seq (Gehring et al., 2017) 24.76</td><td>39.51</td><td>30.32</td><td>39.56</td><td>-</td><td>25.16</td></tr><tr><td>Transformer (Vaswani et al., 2017)</td><td>28.35</td><td>43.75</td><td>34.42</td><td colspan="3">42.84 27.30 29.30</td></tr><tr><td>Dynamic Conv (Wu et al., 2019)</td><td>28.43</td><td>43.72</td><td>34.72</td><td colspan="3">43.08 27.48 29.70</td></tr><tr><td>Ours</td><td>29.47</td><td>45.53</td><td>35.96</td><td colspan="3">44.34 28.40 29.95</td></tr></table>



Table content: <table><tr><td colspan="2">30 BLEU</td><td colspan="4">Training Corpus Size Analysis</td><td>sec</td><td>Training/Inference Time Analysis</td></tr><tr><td/><td/><td/><td/><td/><td/><td>TreeLSTM</td></tr><tr><td/><td/><td/><td/><td/><td/><td>1,500</td><td>TreeTransformer</td></tr><tr><td/><td/><td/><td/><td/><td/><td>Transformer</td></tr><tr><td>20</td><td/><td/><td/><td/><td/><td>1,000</td><td>TreeLSTM-Infer TreeTransformer-Infer</td></tr><tr><td/><td/><td/><td/><td colspan="2">TreeTransformer</td></tr><tr><td/><td/><td/><td/><td colspan="2">Transformer</td><td>500</td></tr><tr><td>10</td><td/><td/><td/><td colspan="2">DynamicConv</td></tr><tr><td/><td colspan="5">9 0 K 2 2 5 K 4 5 0 K 1 .1 M 2 .2 M 3 .4 M 4 .5 M</td><td>1 6</td><td>3 2</td><td>6 4</td><td>1 2 8</td><td>2 5 6</td></tr><tr><td>(a)</td><td colspan="2">WMT'14</td><td colspan="2">English-German</td><td>BLEU</td><td>on</td><td>(b) Elapse and inference time in seconds (y-</td></tr><tr><td colspan="6">newstest2014 with varying size of training data.</td><td>axis) w.r.t sequence length (x-axis).</td></tr><tr><td/><td/><td/><td colspan="4">Figure 5: Training data size and training/inference time analysis.</td></tr><tr><td/><td/><td colspan="2">Model</td><td colspan="2">En-De</td><td>En-Fr</td><td>De-En</td><td>Fr-En</td></tr><tr><td/><td/><td colspan="2">Leaves/Nodes</td><td colspan="2">59.2/40.8</td><td>59.3/40.7</td><td>66.4/33.6</td><td>64.7/35.3</td></tr><tr><td/><td/><td colspan="5">Target→Nodes 66.4±2e-4 61.9±6e-4 64.9±4e-4 59.3±2e-2</td></tr></table>

Peer review (iclr2020):
This paper proposes a novel mechanism to leverage additional tree-structure information into the transformer. The proposed method consist three main component: a hierarchical accumulation strategy to aggregate the leaf node embedding information to the non-terminal nodes; a hierarchical embedding which is akin to positional embedding, however encapsulating the leaf-to-node and relative position information; a sub-tree masking strategy to filter out irrelevant information. Although the formulations seem a little bit overcomplicated/cumbersome to me, I find the figures are really helpful to understand the gists, which are intuitive and straightforward. Strengths: * Intuitive and novel ideas. The tree structure information is incorporated into the transformer in a sophisticated and elegant manner, with only constant time-complexity overhead. * Strong empirical results and well-defined ablation study. Good analysis on the performance vs dataset size and time complexity Cons: * Heavy notations which could be more concise. * Implementing such an architecture without source code could be difficult. Questions: * Comparing with the naive transformer architecture (e.g. base model), how many additional parameters are there in your model? I see that for fair comparison, the authors use the same base transformer architecture, however it would still be very helpful if they can provide the statistics of the number of parameters for the proposed model and the compared baselines. * Are all the baselines using the same parser (CoreNLP)? If not, would the difference of parsing trees be a confounding factor?