Sequence-to-Sequence Learning with Latent Neural Grammars

Abstract
Sequence-to-sequence learning with neural networks has become the de facto standard for sequence prediction tasks. This approach typically models the local distribution over the next word with a powerful neural network that can condition on arbitrary context. While flexible and performant, these models often require large datasets for training and can fail spectacularly on benchmarks designed to test for compositional generalization. This work explores an alternative, hierarchical approach to sequence-to-sequence learning with quasi-synchronous grammars, where each node in the target tree is transduced by a node in the source tree. Both the source and target trees are treated as latent and induced during training. We develop a neural parameterization of the grammar which enables parameter sharing over the combinatorial space of derivation rules without the need for manual feature engineering. We apply this latent neural grammar to various domains—a diagnostic language navigation task designed to test for compositional generalization (SCAN), style transfer, and small-scale machine translation—and find that it performs respectably compared to standard baselines.

1 Introduction
Sequence-to-sequence learning with neural networks [62, 22, 106] encompasses a powerful and general class of methods for modeling the distribution over an output target sequence y given an input source sequence x. Key to its success is a factorization of the output distribution via the chain rule coupled with a richly-parameterized neural network that models the local conditional distribution over the next word given the previous words and the input. While architectural innovations such as attention [8], convolutional layers [39], and Transformers [110] have led to significant improvements, this word-by-word modeling remains core to the approach, and with good reason—since any distribution over the output can be factorized autoregressively via the chain rule, this approach should be able to well-approximate the true target distribution given large-enough data and model.1
However, despite their excellent performance across key benchmarks these models are often sample inefficient and can moreover fail spectacularly on diagnostic tasks designed to test for compositional generalization [68, 63]. This is partially attributable to the fact that standard sequence-to-sequence models have relatively weak inductive biases (e.g. for capturing hierarchical structure [79]), which can result in learners that over-rely on surface-level (as opposed to structural) correlations.
In this work, we explore an alternative, hierarchical approach to sequence-to-sequence learning with latent neural grammars. This work departs from previous approaches in three ways. First, we model the distribution over the target sequence with a quasi-synchronous grammar [103] which assumes a hierarchical generative process whereby each node in the target tree is transduced by
Much of the work was completed while the author was at MIT-IBM Watson AI. Code is available at https://github.com/yoonkim/neural-qcfg.
1There are, however, weighted languages whose next-word conditional distributions are hard to compute in a formal sense, and these distributions cannot be captured by locally normalized autogressive models unless one allows the number of parameters (or runtime) to grow superpolynomially in sequence length [72].
35th Conference on Neural Information Processing Systems (NeurIPS 2021).
nodes in the source tree. Such node-level alignments provide provenance and a causal mechanism for how each output part is generated, thereby making the generation process more interpretable. We additionally find that the explicit modeling of source- and target-side hierarchy improves compositional generalization compared to non-hierarchical models. Second, in contrast the existing line of work on incorporating (often observed) tree structures into sequence modeling with neural networks [35, 5, 89, 37, 126, 1, 97, 18, 34, inter alia], we treat the source and target trees as fully latent and induce them during training. Finally, whereas previous work on synchronous grammars typically utilized log-linear models over handcrafted/pipelined features [20, 56, 115, 103, 112, 27, 42, inter alia] we make use of neural features to parameterize the grammar’s rule probabilities, which enables efficient sharing of parameters over the combinatorial space of derivation rules without the need for any manual feature engineering. We also use the grammar directly for end-to-end generation instead of as part of a larger pipelined system (e.g. to extract alignments) [122, 41, 14].
We apply our approach to a variety of sequence-to-sequence learning tasks—SCAN language navigation task designed to test for compositional generalization [68], style transfer on the English Penn Treebank [78], and small-scale English-French machine translation—and find that it performs respectably compared to baseline approaches.

2 Neural Synchronous Grammars for Sequence-to-Sequence Learning
We use x = x1, . . . , xS , y = y1, . . . , yT to denote the source/target strings, and further use s, t to refer to source/target trees, represented as a set of nodes including the leaves (i.e. yield(s) = x and yield(t) = y).

2.1 Quasi-Synchronous Grammars
Quasi-synchronous grammars, introduced by Smith and Eisner [103], define a monolingual grammar over target strings conditioned on a source tree, where the grammar’s rule set depends dynamically on the source tree s. In this paper we work with probabilistic quasi-synchronous context-free grammars (QCFG), which can be represented as a tuple G[s] = (S,N ,P,Σ,R[s], θ) where S is the distinguished start symbol,N is the set of nonterminals which expand to other nonterminals, P is the set of nonterminals which expand to terminals (i.e. preterminals), Σ is the set of terminals, andR[s] is a set of context-free rules conditioned on s, where each rule is one of
S → A[αi], A ∈ N , αi ⊆ s A[αi]→ B[αj ]C[αk], A ∈ N , B,C ∈ N ∪ P , αi, αj , αk ⊆ s D[αi]→ w, D ∈ P, w ∈ Σ, αi ⊆ s.
We use θ to parameterize the rule probabilities pθ(r) for each r ∈ R[s]. In the above, αi’s are subsets of nodes in the source tree s, and thus a QCFG tranduces the output tree by aligning each target tree node to a subset of source tree nodes. This monolingual generation process differs from that of classic synchronous context-free grammars [118] which jointly generate source and target trees in tandem (and therefore require that source and target trees be isomorphic), making QCFGs appropriate tools for tasks such as machine translation where syntactic divergences are common.2 Since the αi’s are elements of the power set of s, the above formulation as presented is completely intractable. We follow prior work [103, 112] and restrict αi’s to be single nodes (i.e. αi, αj , αk ∈ s), which amounts to assuming that each target tree node is aligned to exactly one source tree node.
In contrast to standard, “flat” sequence-to-sequence models where any hierarchical structure necessary for the task must be captured implicitly within a neural network’s hidden layers, synchronous grammars explicitly model the hierarchical structure on both the source and target side, which acts as a strong source of inductive bias. This tree transduction process furthermore results in a more interpretable generation process as each span in the target aligned to a span in the source via nodelevel alignments.3 More generally, the grammar’s rules provide a symbolic interface to the model with which operationalize constraints and imbue inductive biases, and we show how this mechanism can be used to, for example, incorporate phrase-level copy mechanisms (section 2.4).
2It is also possible to model syntactic divergences with richer grammatical formalisms [101, 81]. However these approaches require more expensive algorithms for learning and inference.
3Similarly, latent variable attention [121, 7, 28, 96, 119] provides for more a interpretable generation process than standard soft attention via explicit word-level alignments.

2.2 Parameterization
Since each source tree node αi is likely to occur only a few times (or just once) in the training corpus, parameter sharing becomes crucial. Prior work on QCFGs typically utilized log-linear models over handcrafted features to share parameters across rules [103, 42]. In this work we instead use a neural parameterization which allows for easy parameter sharing without the need for manual feature engineering. Concretely, we represent each target nonterminal and source node combination A[αi] as an embedding,
eA[αi] = uA + hαi ,
where uA is the embedding for A, and hαi is the representation of node αi given by running a TreeLSTM over the source tree s [107, 134]. These embeddings are then combined to produce the probability of each rule,
pθ(S → A[αi]) ∝ exp ( u>S eA[αi] ) ,
pθ(A[αi]→ B[αj ]C[αk]) ∝ exp ( f1(eA[αi]) >(f2(eB[αj ]) + f3(eC[αk])) ) ,
pθ(D[αi]→ w) ∝ exp ( f4(eD[αi]) >uw + bw ) ,
where f1, f2, f3, f4 are feedforward networks with residual layers (see Appendix A.1 for the exact parameterization). Therefore the learnable parameters in this model are the nonterminal embeddings (i.e. uA for A ∈ {S} ∪ N ∪ P), terminal embeddings/biases (i.e. uw, bw for w ∈ Σ), and the parameters of the TreeLSTM and the feedforward networks.

2.3 Learning and Inference
The QCFG described above defines a distribution over target trees (and by marginalization, target strings) given a source tree. While prior work on QCFGs typically relied on an off-the-shelf parser over the source to obtain its parse tree, this limits the generality of the approach. In this work, we learn a probabilistic source-side parser along with the QCFG. This parser is a monolingual PCFG with parameters φ that defines a posterior distribution over binary parse trees given source strings, i.e. pφ(s |x). Our PCFG uses the neural parameterization from Kim et al. [64]. With the parser in hand, we are now ready to define the log marginal likelihood,
log pθ,φ(y |x) = log  ∑ s∈T (x) ∑ t∈T (y) pθ(t | s)pφ(s |x)  . Here T (x) and T (y) are the sets of trees whose yields are x and y respectively. Unlike in synchronous context-free grammars, it is not possible to efficiently marginalize over both T (y) and T (x) due to the non-isomorphic assumption. However, we observe that the inner summation ∑ t∈T (y) pθ(t | s) = pθ(y | s) can be computed with the usual inside algorithm [9] in O(|N |(|N |+ |P|)2S3T 3), where S is the source length and T is the target length. This motivates the following lower bound on the log marginal likelihood,
log pθ,φ(y |x) ≥ Es∼pφ(s |x) [log pθ(y | s)] ,
which is obtained by the usual application of Jensen’s inequality (see Appendix A.2).4
An unbiased Monte Carlo estimator for the gradient with respect to θ is straightforward to compute given a sample from pφ(s |x), since we can just backpropagate through the inside algorithm. For the gradient respect to φ, we use the score function estimator with a self-critical baseline [92],
∇φ Es∼pφ(s |x) [log pθ(y | s)] ≈ (log pθ(y | s ′)− log pθ(y | ŝ))∇φ log pφ(s′ |x),
4As is standard in variational approaches, one can tighten this bound with the use of a variational distribution qψ(s |x,y), which results in the following evidence lower bound,
log pθ,φ(y |x) ≥ Es∼qψ(s |x,y) [log pθ(y | s)]−KL[qψ(s |x,y) ‖ pφ(s |x)]. This is equivalent to our objective if we set qψ(s |x,y) = pφ(s |x). Rearranging some terms, we then have,
Es∼pφ(s |x) [log pθ(y | s)] = log pθ,φ(y |x)−KL[pφ(s |x) ‖ pθ,φ(s |x,y)]. Hence, our use of pφ(s |x) as the variational distribution is militating towards learning a model which achieves good likelihood but at the same time has a posterior distribution pθ,φ(s |x,y) that is close to the prior pφ(s |x) (i.e. learning a model where most of the uncertainty about s is captured by x alone). This is arguably reasonable for many language applications since parse trees are often assumed to be task-agnostic.
where s′ is a sample from pφ(s |x) and ŝ is the MAP tree from pφ(s |x). We also found it important to regularize the source parser by simultaneously training it as a monolingual PCFG, and therefore add ∇φ log pφ(x) to the gradient expression above.5 Obtaining the sample tree s′, the argmax tree ŝ, and scoring the sampled tree log pφ(s′ |x) all require O(S3) dynamic programs. Hence the runtime is still dominated by the O(S3T 3) dynamic program to compute log pθ(y | s′) and log pθ(y | ŝ).6 We found this to be manageable on modern GPUs with a vectorized implementation of the inside algorithm. Our implementation uses the Torch-Struct library [93].
Predictive inference For decoding, we first run MAP inference with the source parser to obtain ŝ = argmaxs pφ(s |x). Given ŝ, finding the most probable sequence argmaxy pθ(y | ŝ) (i.e. the consensus string of the grammarG[ŝ]) is still difficult, and in fact NP-hard [102, 16, 77]. We therefore resort to an approximate decoding scheme where we sample K target trees t(1), . . . t(K) from G[ŝ], rescore the yields of the sampled trees, and return the tree whose yield has the lowest perplexity.

2.4 Extensions
Here we show that the formalism of synchronous grammars provides a flexible interface with which to interact with the model.
Phrase-level copying Incorporating copy mechanisms into sequence-to-sequence models has led to significant improvements for tasks where there is overlap between the source and target sequences [58, 83, 48, 73, 47, 95]. These models typically define a latent variable at each time step that learns to decide to either copy from the source or generate from the target vocabulary. While useful, most existing copy mechanisms can only copy singletons due to the word-level encoder/decoder.7 In contrast, the hierarchical generative process of QCFGs makes it convenient to incorporate phrase-level copy mechanisms by using a special-purpose nonterminal/preterminal that always copies the yield of the source subtree that it is combined with. Concretely, letting ACOPY ∈ N be a COPY nonterminal, we can expand the rule setR[s] to include rules of the form ACOPY[αi]→ v for v ∈ Σ+, and define the probabilities to be,
pθ(ACOPY[αi]→ v) def = 1{v = yield(αi)}.
(The preterminal copy mechanism is similarly defined.) Computing pθ(y | s) in this modified grammar requires a straightforward modification of the inside algorithm.8 In our style transfer experiments in section 3.2 we show that this phrase-level copying is important for obtaining good performance. While not explored in the present work, such a mechanism can readily be employed to incorporate external transformations rules (e.g. from bilingual lexicons or transliteration tables) into the modeling process, which has been previously investigated at the singleton-level [88, 3].
Adding constraints on rules For some applications we may want to place additional restrictions on the rule set to operationalize domain-specific constraints and inductive biases. For example, setting αj , αk ∈ descendant(αi) for rules of the form A[αi] → B[αj ]C[αk] would constrain the target tree hierarchy to respect the source tree hierarchy, while restricting αi to source terminals (i.e. αi ∈ yield(s)) for rules of the form D[αi]→ w would enforce that each target terminal be aligned to a source terminal. We indeed make use of such restrictions in our experiments.
Incorporating autoregressive language models Finally, we remark that simple extensions of the QCFG can incorporate standard autoregressive language models. Let pLM(w | γ) be a distribution over the next word given by a (potentially conditional) language model given arbitrary context γ (e.g. γ = y<t for a monolingual language model and γ = x,y<t for a sequence-to-sequence model). One way to embed this language model into a QCFG would be to use a special LM preterminal DLM ∈ P that is not combined with any source node, and define the emission probability to be,
pθ(DLM → w) def = pLM(w | γ).
(The nonterminal probabilities pθ(A[αi]→ DLMC[αk]) and pθ(A[αi]→ B[αj ]DLM) are computed with the associated symbol embedding uDLM .) Both the QCFG and the language model can then be trained jointly.
5This motivates our use of a generative rather than a discriminative parser on the source side. 6This runtime is incidentally is the same as that of the bitext inside algorithm for marginalizing over both
source and target trees in rank-two synchronous context-free grammars. 7However see Zhou et al. [132], Panthaplackel et al. [87], and Wiseman et al. [114]. 8Letting β[s, t,N ] = pθ(N
∗→ ys:t) be the inside variable for N ’s being the root of the subtree over ys:t, we can simply set β[s, t, ACOPY[αi]] = 1{ys:t = yield(αi)}.
Approach Simple Jump A. Right Length
RNN [68] 99.7 1.7 2.5 13.8 CNN [29] 100.0 69.2 56.7 0.0 Transformer [38] − 1.0 53.3 0.0 T5-base [38] − 99.5 33.2 14.4 Syntactic Attn [94] 100.0 91.0 28.9 15.2 Meta Seq2Seq [67] − 99.9 99.9 16.6 CGPS [70] 99.9 98.8 83.2 20.3 Equivar. Seq2Seq [44] 100.0 99.1 92.0 15.9 Span-based SP [54] 100.0 − 100.0 − LANE [76] 100.0 100.0 100.0 100.0 Program Synth. [85] 100.0 100.0 100.0 100.0 NeSS [19] 100.0 100.0 100.0 100.0 NQG-T5 [98] 100.0 100.0 − 100.0 GECA [6] − 87.0 82.0 − R&R Data Aug. [4] − 88.0 82.0 − Neural QCFG (ours) 96.9 96.8 98.7 95.7
Table 1: Accuracy on the SCAN dataset splits compared to previous work.
P0[run]→ RUN P0[look]→ LOOK P0[walk]→ WALK P0[jump]→ JUMP P0[right]→ TURN-RIGHT P0[left]→ TURN-LEFT N4[look left]→ P0[left] P0[look] N4[look right]→ P0[right] P0[look] N4[walk left]→ P0[left] P0[walk] N4[walk right]→ P0[right] P0[walk] N1[look right twice]→ N4[look right] N4[look right] N1[walk left twice]→ N4[walk left] N4[walk left] N1[look thrice]→ N8[look thrice] P0[look] N1[look right thrice]→ N8[look right thrice] N4[look right] N8[look right thrice]→ N4[look right] N4[look right] N1[walk left thrice]→ N8[walk left thrice] N4[walk left] N8[walk left thrice]→ N4[walk left] N4[walk left]
Table 2: Frequently-occurring rules from MAP target trees on the add primitive (jump) train set.
For some cases we may want to make use of a conditional language model that condition on subparts of the source sentence. This may be appropriate for learning to translate non-compositional phrases whose translations cannot be obtained by stitching together independent translations of subparts (e.g. idioms such as “kicked the bucket”). In this case we can make use of a special nonterminal ALM ∈ N which is combined with source tree nodes to produce rules of the form ALM[αi] → v for v ∈ Σ+. The associated probabilities are then defined to be,
pθ(ALM[αi]→ v) def = pLM(v | yield(αi)).
While these extensions can embed flexible autoregressive models within a QCFG,9 they also inherit many of the issues attendant with such models (e.g. over-reliance on surface form). In preliminary experiments with these variants, we found the combined model to quickly degenerate into the uninteresting case of always using the conditional language model, and hence did not pursue this further. However it is possible that modifications to the approach (e.g. posterior regularization to penalize overuse of the conditional language model) could lead to improvements.

3 Experiments
We apply the neural QCFG described above to a variety of sequence-to-sequence learning tasks. These experiments are not intended to push the state-of-the-art on these tasks but rather intended to assess whether our approach performs respectably against standard baselines while simulatenously learning interesting and interpretable structures.

3.1 SCAN
We first experiment on SCAN [68], a diagnostic dataset where a model has to learn to translate simple English commands to actions (e.g. jump twice after walk → WALK JUMP JUMP). While conceptually simple, standard sequence-to-sequence models have been shown to fail on splits of the data designed to test for compositional generalization. We focus on four commonly-used splits: (1) simple, where train/test split is random, (2) add primitive (jump), where the primitive command jump is seen in isolation in training and must combine with other commands during testing,10 (3) add template (around right), where the template around right is not seen during training, and (4) length, where the model is trained on action sequences of length at most 22 and tested on action sequences of length between 24 and 48.
9Alternatively, we can also embed a QCFG within an autoregressive language model with a binary latent variable zt (with distribution pLM(zt |x,y<t)) at each time step. This variable—marginalized over during training—selects between pLM(yt |x,y<t) and pθ(yt | s,y<t), where the latter next-word probability distribution in the QCFG can be computed with a probabilistic Earley parser [105]. The difference between the approaches stems from whether the switch decision is made by the QCFG or by the language model.
10The QCFG defined in this paper places zero probability on length-one target strings, which presents an issue for this split of SCAN where jump → JUMP is the only context in which “JUMP” occurs in the training set. To address this, in cases where the target string is a singleton we simply replicate the source and target, i.e. jump→ JUMP becomes jump jump→ JUMP JUMP.
α12
α11
α9
α6
twice
α7
α5
right
α4
jump
α3
after
α10
α2
twice
α8
α1
left
α0
run
N0[α12]
N1[α10]
N4[α8]
P0[α1]
RUN
P0[α1]
TURN-LEFT
N4[α8]
P0[α1]
RUN
P0[α1]
TURN-LEFT
N2[α11]
N4[α7]
P0[α4]
JUMP
P0[α5]
TURN-RIGHT
N4[α7]
P0[α4]
JUMP
P0[α5]
TURN-RIGHT
Figure 1: Generation from the neural QCFG on a test example from the add primitive (jump) split of SCAN. The induced tree from the learned source parser is shown on the left, and the target tree derivation is shown on the right. We do not show the initial root-level node (i.e. S → N0[α12]). While the model does not distinguish between preterminals and terminals on the source tree, we have shown them separately for additional clarity. We also show some of the node-level alignments with dashed lines.
In these experiments, the nonterminals A ∈ N are only combined with source nodes that govern at least two nodes, and the preterminals P ∈ P are only combined with source terminals. We set |N | = 10 and |P| = 1, and place two additional restrictions on the rule set. First, for rules of the form S → A[αi] we restrict αi to always be the root of the source tree. Second, for rules of the form A[αi] → B[αj ]C[αk] we restrict αj , αk either be a descendant of αi, or αi itself (i.e. αj , αk ∈ descendant(αi) ∪ {αi}). These restrictions operationalize the constraint that the target tree hierarchy respects the source tree hierarchy, though still in a much looser sense than in an isomorphism. We found these constraints to be crucial in learning models that perform well on the compositional splits of the dataset. See Appendix A.3.1 for the full experimental setup and hyperparameters.
Results Table 1 shows our results against various baselines on SCAN. While many approaches are able to solve this dataset almost perfectly, they often make use of SCAN-specific knowledge, which precludes their straightforward application to non-synthetic domains. The neural QCFG performs respectably while remaining domain-agnostic. In Table 2 we show some examples of frequentlyoccurring rules based on their MAP target tree counts on the training set of the add primitive (jump) split. Many of the rules are sensible, and they furthermore illustrate the need for multiple nonterminal symbols. For example, in order to deal with source phrases of form “x thrice” in a grammar that only has unary and binary rules, the model uses the nonterminals N1 and N8 in different ways when combined with the same phrase. Figure 1 shows an example generation from the test set of the add primitive (jump) split, where we find that node-level alignments provide explicit provenance for each target span and thus makes the generation process more interpretable than standard attention mechanisms. These alignments can also be used to diagnose and rectify systematic errors. For example, we sometimes found the model to incorrectly split “x {and,after} y” to “xx” (or “y y”) at the root node. When we manually disallowed such splits during decoding, performance increased by 1%-2% across the board, showcasing a benefit of grammar-based models which makes it possible to directly manipulate model generations by intervening on the set of derivation rules.

3.2 Style Transfer
We next apply our approach on style transfer on English utilizing the StylePTB dataset from Lyu et al. [78]. We focus on the three hard transfer tasks identified by the original paper: (1) active to passive, where a sentence has to be changed from active to passive voice (2808 examples), (2) adjective emphasis, where a sentence has to be rewritten to emphasize a particular adjective (696 examples) (3) verb/action emphasis, where a sentence has to be rewritten to emphasize a particular verb/action (1201 examples).11 The main difficulty with these tasks stems from the small training set combined with the relative complexity of these tasks.
For these experiments we set |N | = |P| = 8 and use the same restrictions on the rule set as in the SCAN experiments. We also found it helpful to contextualize the source embedding with a bidirectional LSTM before feeding to the TreeLSTM encoder.12 We further experiment with the
11To encode information about which word to be emphasized in the adjective/verb emphasis tasks, we use a binary variable whose embedding is added to the word embedding on the encoder side.
12A drawback of using contextualized word embeddings as input to the TreeLSTM is that since the representations hαi for each node αi are now a function of the entire sentence (and not just the leaves), we can no
phrase-level copy mechanism as described in section 2.4. The original paper provides several strong baselines: finetuned GPT2, a standard sequence-to-sequence model, and the retrieve-and-edit model from Hashimoto et al. [53]. We also train our own baseline sequence-to-sequence model with a word-level copy mechanism. See Appendix A.3.2 for more details.
Results Table 3 shows the results where we observe that the neural QCFG performs well compared to the various baselines.13 We further find that incorporating the copy mechanism improves results substantially for both the baseline LSTM and the neural QCFG.14 Figure 2 shows a test example from the active-to-passive task, which shows the word- and phrase-level copying mechanism in action. In this example the source tree is linguistically incorrect, but the grammar is nonetheless able to appropriately transduce the output. Given that linguistic phrases are generally more likely to remain unchanged in these types tasks, incorporating this knowledge into the learning process could potentially improve results.15 For example in Figure 2 the ideal case would be to copy the phrase “a 2-for-1 stock split” but this is not possible due to the incorrectly predicted source tree. Finally, although our approach ostensibly improves upon the baselines according to many of the n-gram-based metrics, we observed the generated sentences to be often ungrammatical, highlighting the limitations of automatic metrics for these tasks while at the same time indicating opportunities for further work in this area.
longer guarantee that target derivations such as A[αi] ∗→ ys:t only depend on αi. This somewhat hinders the interpretability of the node-level alignments. 13As in the original paper we calculate the automatic metrics using the nlg-eval library, available at https://github.com/Maluuba/nlg-eval. 14Even for models that do not explicitly use the copy mechanism, we indirectly allow for copying by replacing the 〈unk〉 token with the source token that the preterminal is combined with in the neural QCFG case, or the source token that had the maximum attention weight in the LSTM case. This explains the outperformance of our baseline sequence-to-sequence models compared to the baselines from Lyu et al. [78], which roughly uses the same architecture.
15There are many ways to do this. For example, one could identify the longest overlap between the source and target, and use posterior regularization on the source PCFG to encourage it to be a valid constituent.

3.3 Machine Translation
Our final experiment is on a small-scale English-French machine translation dataset from Lake and Baroni [68]. Here we are interested in evaluating the model in two ways: first, to see if it can perform well as a standard machine translation system on a randomly held out test set, and second, to see if it can systematically generalize to unseen combinations. To assess the latter, Lake and Baroni [68] add 1000 repetitions of i am daxy → je suis daxiste to the training set and test on 8 new sentences that use daxy in novel combinations (e.g. he is daxy → il est daxiste and i am not daxy→ je ne suis pas daxiste). As the original dataset does not provide official splits, we randomly split the dataset into 6073 examples for training (1000 of which is the “i am daxy” example), 631 examples for validation, and 583 for test.16
For these experiments, we set |N | = |P| = 14 and combine all source tree nodes with all nonterminals/preterminals. We place two restrictions on the rule set: for rules of the form S → A[αi] we restrict αi to be the root of the source tree (as in previous experiments), and for rules of the form A[αi]→ B[αj ]C[αk] we restrict αj , αk to be the direct children of αi such that αj 6= αk (or αi itself if αi has no children).17 As in the style transfer experiments, we also experiment with a bidirectional LSTM encoder which contextualizes the source word embeddings before the TreeLSTM layer. Our baselines here include standard LSTM/Transformer models as well as approaches that explicitly target compositional generalization [70, 19].
Approach BLEU daxy acc.
LSTM 25.1 12.5% Transformer 30.4 100% CGPS [70] 19.2 100% NeSS [19] − 100% Neural QCFG 23.5 100% + BiLSTM 26.8 75.0%
Results Table 4 shows BLEU on the regular test set of 583 sentences and accuracy on the 8 daxy sentences.18 While the neural QCFG performs nontrivially, it is soundly outperformed by a welltuned Transformer model, which performs impressively well even on the daxy test set.19 We thus consider our results on machine translation to be largely negative. Interestingly, the use of contextualized word embeddings (via the bidirectional LSTM) improves BLEU but hurts compositional generalization, highlighting the potential pitfalls of using flexible models which can sometimes entangle representations in undesirable ways.20 Figure 3 shows several ex-
16The original dataset has 10000 examples (not including the daxy examples), but many of them involve duplicate source sentences. We removed such duplicates in our split of the data.
17These restrictions are closer to the strict isormorphic requirement in synchronous context-free grammars than in previous experiments. However they still allow for non-isormorphic trees since αi can be inherited if it has no children.
18For CGPS and NeSS, the original papers only assess accuracy on the daxy test set, and furthermore do not provide the training/validation/test splits. To obtain BLEU for CGPS, we run the publicly available code (https://github.com/yli1/CGPS) on our split of the data. For NeSS, the code is not publicly available but the authors provided a version of their implementation. However, the provided code/hyperparameters were tailored for the SCAN dataset, and despite our best efforts to adapt the code/hyperparameters to our setup we were unable obtain sensible results on the machine translation dataset.
19The Transformer did, however, require some hyperparameter tuning given the small size of our dataset. Similar findings have been reported by Wu et al. [120] in the context of applying Transformers to moderately sized character-level transduction datasets.
20This variant of the neural QCFG also does poorly on the compositional splits of SCAN.
not use contextualized word embeddings. The induced source trees are sometimes linguistically incorrect (e.g. in the top left example “as tall as” would not be considered a valid linguistic phrase), but the QCFG is still able to correctly transduce the output by also learning unconventional trees on the target side as well. This is reminiscent of classic hierarchical phrase-based approaches to machine translation where the extracted phrases often do not correspond to linguistic phrases [20]. Finally, although the model does well on the daxy test set, it still incorrectly translates simple but unusual made-up examples such as “i m not a cat” (Figure 3, top right). This is despite the fact that examples of the form i {am,m} not a x→ je ne suis pas {un,une} y occur multiple times in the training set.21 We speculate that while the probabilistic nature of the grammar and the use of distributed representations enables easier training, they contribute to the model’s being (still) vulnerable to spurious correlations.

4 Discussion
While we have shown that neural quasi-synchronous grammars can perform well for some sequenceto-sequence learning tasks, there are several serious limitations. For one, the O(|N |(|N | + |P|)2S3T 3) dynamic program will likely pose challenges in scaling this approach to larger datasets with longer sequences.22 Predictive inference was also much more expensive since we found it necessary to sample and score a large number of target trees to perform well on the non-synthetic datasets (see Appendix A.3). The conditional independence assumptions made by the QCFG may also be too strong for some tasks that involve complex dependencies, and the approach may furthermore be inappropriate for domains where the input and output are not naturally tree-structured. The models were quite sensitive to hyperparameters and some datasets needed training over multiple random seeds to perform well. These factors make our approach much less “off-the-shelf” than standard sequence-to-sequence models, although this may be partially attributable to the availability of a robust set of hyperparameters for existing approaches.
21The other models were also unable to correctly translate this sentence. 22Indeed, on realistic machine translation datasets with longer sequences we quickly ran into memory issues when running the model on just a single example, even with a multi-GPU implementation of the inside algorithm distributed over four 32GB GPUs. To apply the model on longer sentences, an interesting future direction might involve working with a “soft” version of the grammar, where the nonterminals embeddings are contexualized against source elements via soft attention. The runtime and memory for marginalizing over target trees in this soft QCFG would have a linear (instead of cubic) dependence source length.
At the start of this project, our initial hope was to show that classic, grammar-based approaches to sequence transduction had been unfairly overlooked in the current deep learning era, and that revisiting these methods with contemporary parameterizations would prove to be more than just an academic exercise. Disappointingly, this seems not to be the case. While we did observe decent performance on niche datasets such as SCAN and StylePTB where inductive biases from grammars were favorably aligned to the task at hand, for tasks like machine translation our approach was thoroughly steamrolled by a well-tuned Transformer.
What role, then, can such models play in building practical NLP systems (if any)? It remains to be seen, but we venture some guesses. Insofar as grammars and other models with symbolic components are able to better surface model decisions than standard approaches, they may have a role in developing more controllable and interpretable models, particularly in the context of collaborative human-machine systems [40]. Alternatively, inflexible models with strong inductive biases have in the past been used to guide (overly) flexible neural models in various ways, for example by helping to generate additional data [58, 75] or inducing structures with which to regularize/augment models [24, 74, 3, 127]. In this vein, it may be interesting to explore how induced structures from grammars (such as the tranduction rules in Table 2) can be used in conjunction with flexible neural models.

5 Related Work
Synchronous grammars Synchronous grammars and tree transducers have a long and rich history in natural language processing [2, 101, 118, 80, 36, 32, 84, 56, 115, 45, 12, 23, inter alia]. In this work we focus on the formalism of quasi-synchronous grammars, which relaxes the requirement that source trees be isomorphic to target trees. Quasi-synchronous grammars have enjoyed applications across a wide range of domains including in machine translation [103, 42, 43], question answering [112], paraphrase detection [27], sentence simplification [117, 116], and parser projection [104]. Prior work on quasi-synchronous grammars generally relied on pipelined parse trees for the source and only marginalized out the target tree, in contrast to the present work which treats both source and target trees as latent.
Compositional sequence-to-sequence learning Lake and Baroni [68] proposed the influential SCAN dataset for assessing the compositional generalization capabilities of neural sequence-tosequence models. There has since been a large body of work on compositional sequence-to-sequence learning through various approaches including modifications to existing architectures [70, 94, 44, 17, 26], grammars and neuro-symbolic models [86, 98, 85, 19, 76], meta-learning [67, 25], and data augmentation [6, 49, 50, 4]. Our approach is closely related to NQG-T5 [98] which uses a rules-based approach to induce a non-probabilistic QCFG and then backs off to a flexible sequence-to-sequence model during prediction if the grammar cannot parse the input sequence.
Deep latent variable models There has much work on neural parameterizations of classic probabilistic latent variable models including hidden Markov models, [109, 113, 21], finite state transducers [91, 71] topic models [82, 30, 31], dependency models [59, 51, 15, 52, 123], and context-free grammars [64, 61, 133, 131, 125, 124]. These works essentially extend feature-based unsupervised learning [10] to the neural case with the use of neural networks over embedding parameterizations, which makes it easy to share parameters and additionally condition the generative model on side information such as auxiliary latent variables [52, 64], images [130, 60, 55], video and audio [129], and source-side context [113, 99]. Since we marginalize over unobserved trees during learning, our work is also related to the line of work on marginalizing out latent variables/structures for sequence transduction tasks [46, 33, 11, 66, 128, 90, 57, 69, 108, 111, inter alia].

6 Conclusion
In this paper we have studied sequence-to-sequence learning with latent neural grammars. We have shown that the formalism quasi-synchronous grammars provides a flexible tool with which to imbue inductive biases, operationalize constraints, and interface with the model. Future work in this area could consider: (1) revisiting richer grammatical formalisms (e.g. synchronous tree-adjoining grammars [101]) with contemporary parameterizations, (2) conditioning on other modalities such as images/audio for grounded grammar induction [100, 130, 60, 129], (3) adapting these methods to other structured domains such as programs and graphs, and (4) investigating how grammars and symbolic models can be integrated with pretrained language models to solve practical tasks.

Reviewer Comments (OpenReview)
Reviewer_1: This work proposes a promising approach for improving the generalization. Although the scalability could be an issue due to the high time complexity, compared to prior work on grammar learning, modeling the tree structures as latent could improve the flexibility.
However, this work lacks a thorough discussion of the failure mode of the approach, which makes it hard to qualitatively understand the scenarios when learning latent alignment is better than explicitly modeling the grammar. First, both SCAN and the machine translation tasks evaluated in this work have validation/test sets with examples generated by pre-defined templates, thus if a model accurately learns the grammar, it should achieve 100% accuracy on both tasks. This is reflected by prior work. However, although neural QCFG achieves much better results than baselines that do not explicitly learn the grammar, the accuracies are not perfect. Could you provide a discussion on the failure cases? Note that in Table 1, without T5, NQG baseline itself can achieve 100% accuracy on SCAN, which shows the feasibility of learning a concrete quasi-synchronous grammar for SCAN benchmark. Is there any fundamental limitation that prevents neural QCFG from achieving the same performance as a deterministic grammar parser?
Meanwhile, I want to note that the proposed neural QCFG might not be completely domain-agnostic. The paper shows that the authors set different hyper-parameters for the number of nonterminals and the number of preterminal. From my understanding of these benchmarks, these hyper-parameters seem to be well-tuned for the underlying grammars of these datasets. Does changing these hyper-parameters affect the performance, and is it possible to set the same hyper-parameters for all datasets?
About the hard style transfer tasks in Table 2, I wonder if the authors have also evaluated on the easy and medium tasks in StylePTB dataset. Does neural QCFG still outperform other baselines?
To understand the effectiveness of latent grammar learning, I feel that the authors should provide a more detailed discussion and comparison of NQG work, given that both of them are based on quasi-synchronous grammars. From the current experiments, it is a bit hard to understand whether this work is more capable of learning grammar rules than NQG. If the authors have also tried other datasets in NQG paper, e.g., the template split of GeoQuery for evaluating compositional generalization, it is helpful to include related discussion as well.
Limitations And Societal Impact:
The authors adequately addressed the limitations and potential negative societal impact.
Needs Ethics Review: No
Time Spent Reviewing: 2

Reviewer_2: I think the overall goal of using latent grammar trees and marginalization to improve sequence-to-sequence learning is promising. Although the complexity of this method might limit its application to a larger scale scenario. However, I am not an expert in this direction and my judgement might not be accurate.
Questions:
--- In Line 70, you restrict all
α
i
to be nodes of the source tree. Why is this restriction important and can we think of it as the “attention” from the target nodes to source nodes?
--- Moreover, continuing from the last question, is it possible to directly treat source as sequence and work on sequence-to-tree grammars? In this way we don’t need to marginalize
p
(
s
|
x
)
with a Monte Carlo estimator. Is it possible? Or the grammar is restricted to be tree-to-tree?
--- What is the training cost (time) and inference speed compared to standard sequence-to-sequence models?
--- What will be the performance for the proposed method without using the autoregressive LM?
--- I wonder how the proposed method works on very long sequences, or a larger but noisier dataset, for example machine translation WMT En-Fr with over 30M sentence pairs. Will the performance degrade a lot because of the nature of the dataset?
Limitations And Societal Impact:
This paper discussed the limitations and future works. But it would be nice to have a separate section with more discussion and societal impacts.
Needs Ethics Review: No
Time Spent Reviewing: 4-5 hours

Reviewer_3: This is very interesting, off-the-beaten-path work (at least for 2021). The technical contribution is substantial, going well beyond a neural adaptation of QCFG, and the authors have expertly picked the right tasks to showcase their model - the experiments are quite convincing. The inclusion of example tree transductions for each task is very nice. This feels like exactly the sort of paper we should be encouraging - it may catch on, it may not, but the ideas here are likely to inspire more than a few people to do something interesting. The brief limitations discussion at the end is quite honest, emphasizing and owning the very real problem of scaling up in the face of an expensive dynamic program. The paper is very well written and very easy to follow.
I like this paper a lot, but I do have some concerns:
The joint CFG + QCFG training algorithm in Section 2.3 is a big part of this paper’s technical weight, using a score function estimator with a self-critical baseline. However, its contribution to the method’s success is never tested directly! Since the source parser is simultaneously trained as a monolingual PCFG, you have access to all of the pieces necessary for a traditional pipelined approach: train the PCFG parser first, and then use the fixed parser to train a standard QCFG transducer for your sequence-to-sequence task. This baseline should be evaluated for all three tasks, so we can better understand the impact (if any) of joint training. Were this a thesis or journal review, I would insist on this experiment.
Also, the number of non-terminals and pre-terminals (|N| and |P|) jump around for each task. How were these tuned? How necessary is this tuning for your method’s success? I could ask the same question again for the various constraints placed on target tree structure based on the source tree. Ideally, all of this should be determined during development. I checked the appendix, but I wasn’t able to find anything explicit - there’s some chance the development sets were just used for early stopping.
Less importantly, it was never clear to me why predictive inference needed to be so complex, involving sampling k target trees and then rescoring their yields. In fact, it was never clear what model or heuristic was used to rescore the yields given the trees. I’m sure it makes sense, but it needs to be spelled out. Again, an ablation that compares to the obvious yield-of-max-tree baseline would be helpful.
Limitations And Societal Impact:
Handled well.
Ethical Concerns:
None.
Needs Ethics Review: No
Time Spent Reviewing: 4

Reviewer_4: The paper proposes an end-to-end neural parametrization for QCFG (a constrained version which is still more flexible than SCFG). Compared to more common seq2seq learning, the papers have demonstrated two advantages to learn a neural parametrized QCFG:
The copy operation can be performed in logical chunks and this has been shown particularly important to perform well on hard section of StylePBT
Add domain specific constraints, for example, descendant restrictions are applied for all the experiments on datasets from (Lake and Baroni, 2018). As the QCFG is much more flexible than SCFG, the formalism offers the above advantages while modelling many interesting seq2seq tasks as shown in the experiments. However, these advantages come with the price of having computational difficulties. Facing these difficulties, the authors have made an excellent job in introducing clearly and succinctly the difficulties and their proposed solutions in section 2.3.
The experiments are carried over three datasets, the SCAN one and Toy machine translation one suggests that proposed methods can perform reasonably well on compositionality demanding tasks. The StylePBT dataset results show more benefits of such methods compared to seq2seq baseline and even previously proposed methods, although I would strongly suggest the authors take care of the formatting for table 2 (highlighting best performance, e.g).
There are two questions that I want to clarify with the authors:
In line 113: It is said that empirically, it is important to train the source as a PCFG. In this case, it would be natural to perform the prior work which first trains a source side PCFG and then learn the synchronous grammar. I don’t see such experiments in the paper, do authors also consider this as a natural and maybe strong baseline compared to the proposed approach please? Related to the this point, the paper's main contribution is to propose learning a neural QCFG end to end. What is the end to end performance without relying on the monolingual PCFG please?
Why is there no baseline to learn non-neural QCFG in the paper please? One such baseline can be found in the description of NQG-T5 and I am sure there are other approaches and works on this. Another minor related question, why do the authors say that NQG-T5 uses SCAN-specific knowledge please? From my reading of that paper, they seem to deduce from scratch a QCFG pomn SCAN (at least the NQG part)?
＃ After reading authors' response: Thanks for the authors having answered my questions (and other reviewers' questions) in great detail. Both reviewer 3 and me found PCFG + QCFG to be a natural baseline and I hope the results communicated here can be added to the final paper. The table for constraints are as well informative. The cost of these approaches and why it can't be applied to general MT are important details to explain and should be improved as well. With the response, I think the authors have sufficient material to address above concerns to better communicate the paper's idea. I have increased my score from 5 to 6.
Limitations And Societal Impact:
On domain specific constraints, when applying to toy examples in (lake and Baroni, 2018) this seems beneficial. However, what kind of constraints do authors think can be applied to real life scenarios please (e.g. machine translation, natural language generation.)
Needs Ethics Review: No
Time Spent Reviewing: 3

Reviewer Summary
Reviewer_1: This work proposes neural QCFG (quasi-synchronous context-free grammars) for sequence-to-sequence learning. By explicitly modeling the alignment between source and target trees, they aim to improve the generalization and interpretability of the model. Different from prior works that learn a parser to construct source and target trees, this work learns latent trees, i.e., a distribution of source and target trees. On SCAN and "daxy" machine translation, which are two benchmarks specifically designed for compositional generalization, neural QCFG achieves good but not perfect results. On hard style transfer tasks from StylePTB, neural QCFG largely outperforms the baselines.

Reviewer_2: This paper proposes a hierarchical approach to sequence-to-sequence (seq2seq) learning with latent synchronous grammars where each node in the target tree is transduced by a subset of nodes in the source tree, and the grammar trees are marginalized out during training. The proposed latent neural grammar is validated in various tasks including diagnostic language navigation, style transfer and machine translation, and shows better compositional generalization.

Reviewer_3: This paper presents a neural extension to quasi-synchronous grammar (QCFG) for sequence-to-sequence modeling. In addition to the neural extension, QCFG is also extended (for the first time to my knowledge) to be jointly trained alongside the source parser that the QCFG transduces (this requires a dual objective: the sequence-to-sequence objective, and a traditional monolingual CFG objective from a treebank). Extensions for phrase-to-phrase copying, various constraints, and a (theoretical) addition of an arbitrary-context autoregressive LM are also provided. Strong experimental results are presented for 3 small-scale tasks that emphasize compositional generalization: SCAN, Style Transfer and MT.

Reviewer_4: QCFG (Quasi synchronous Context Free Grammar) is a relaxation of the SCFG and is an interesting and important tool to consider for structured transduction applications such as machine translation, semantic parsing, etc. This paper proposes to learn this grammar through latent variable learning; alongside, it proposes a neural parametrization for learning this grammar through terminal embeddings using TreeLSTM. Due to the flexibility of QCFG, there are technical choices that need to be made to run the training/inference efficiently as shown by the paper.
The proposed approach can deal with operations that go beyond token manipulation, and the authors empirically show that it allows for better compositionality handling and long range copying (2.4).