Can Recurrent Neural Networks Learn Nested Recursion?
Paper · 2018 · Jean-Phillipe Bernardy
Summary
A program that closes a pair of brackets has to know which opening bracket is still waiting for its partner. When several pairs are nested, the most recent unmatched opening determines the next possible closing. After that pair is complete, an earlier opening becomes relevant again. Bernardy uses this small, precisely defined task to ask whether a recurrent neural network can learn nested recursion from examples and carry what it learns to deeper nesting. The question matters for context-free grammar, a way of describing languages in which a construction can contain another construction of the same kind.
The paper trains networks to predict the next character in balanced strings and then tests what they do with strings that go beyond the training examples. A preliminary experiment uses a single bracket type. All tested configurations exceed 99% on its test, which checks what the network predicts after a complete balanced string. A count of unmatched openings is enough for that decision. The main experiments use 5 types, so the network also needs to recover the identity of the relevant opening. The evaluation focuses on positions where the actual next character is a closing bracket, because the grammar determines a unique closing type even when it also permits other continuations.
A long short-term memory network, or LSTM, handles the long-distance test well. Its closing-bracket accuracy stays at or above 88% across the positions reported for that test. Generalizing to new depths is harder. A single LSTM reaches around 60% at its weakest reported position, then recovers to close to 90% near the end of the string. The gated recurrent unit, or GRU, does comparatively well on some earlier positions but comes close to guessing on the hardest distant closures. Bernardy suggests that the LSTM may handle an outermost pair especially well by remembering the first opening and tracking when its partner is due.
The paper also introduces a recurrent unit whose memory is arranged as a stack. Its learned controller can move entries into or out of that memory, and a standalone unit with sufficient stack depth closes the brackets without errors on the reported test of deeper nesting. Results are more variable when another recurrent layer processes the input first. The experiments therefore give different answers depending on the architecture, the depth of the test examples, and the position being scored. They establish how these networks behave on a formal bracket language, where nesting is explicit and the correct closing type can be checked directly.
Deep dive: Can Recurrent Neural Networks Learn Nested Recursion?
Bernardy tests whether recurrent neural networks can match nested brackets at depths beyond training and how an explicit stack changes the result. · about 38 minutes to read
The problem and its context
What it means to learn a nested dependency
An opening bracket creates an obligation that may remain unresolved while other material arrives. In a string such as ([]), the round bracket opens first, but the square bracket closes first. At the inner closing, a reader may attend to the recent square opening. At the outer closing, that square pair has already been resolved and the older round opening matters again. A system that reads from left to right has to preserve the information needed for both decisions and make it available in the appropriate order.
Recursion enters because the contents of a pair can be another expression built by the same rules. A matched pair can surround an empty expression, a matched pair, or a sequence of expressions. Wrapping an already balanced expression adds a layer. Putting balanced expressions side by side makes a longer string while leaving their obligations independent. The grammar permits either operation repeatedly. This gives Bernardy a way to use a small alphabet to vary the kinds of structural demands that a string makes.
Distance and depth describe different aspects of those demands. Distance concerns how far apart the members of an individual pair are in the sequence. Depth concerns how many pairs are open at once. A long run of complete expressions can intervene between the members of an outer pair. An opening just inside several other openings can receive its closing soon after it appears. A test that varies distance can therefore reveal how a network retains an opening across intervening characters, while a test that varies simultaneous nesting asks how it handles multiple unresolved openings.
This distinction matters when the same bracket types recur. Remembering the most recently read opening works for some closings. Once that opening has been matched, its type may need to give way to an older one. A count tells the reader when some pair remains open. In the typed language, it leaves the identity of the relevant pair undetermined. The task asks whether a network can recover that identity from the sequence alone, including when the sequence contains deeper nesting than it encountered during training.
The framing comes from a broader question about syntax and grammar formalisms. Bernardy treats nested recursion as an important device for describing syntax and leaves open how central deep nesting is to natural language in practice. The benchmark isolates a structural operation that a context-free description can express. It sets aside the work of discovering which words or phrases mark the beginning and end of a construction. If a network struggles when all such boundaries are visible, that is evidence about a demanding part of learning richer grammars from examples.
Why plausible generation leaves the question open
A recurrent network processes a sequence by carrying information forward from one character to the next. The same kind of computation is repeated at every step, with an internal state connecting the steps. In next-character prediction, the state reached after reading a prefix helps determine the probability assigned to each possible continuation. The parameters can be adjusted to make observed continuations more probable. That setup lets the network learn useful regularities without being given an explicit grammar.
Bernardy takes earlier demonstrations of recurrent text generation as a reason to examine what that learning amounts to. The paper discusses samples with recognizable features of literary writing, reference prose, mathematical writing and source code. Such samples can resemble their training material at the scale of individual words and larger constructions. The networks can thus acquire some regularities that readers associate with grammatical organization. The displayed recursion is shallow, however, so the samples leave open how the networks handle a depth beyond the examples they have seen. Visualizing and Understanding Recurrent Networks
The bracket experiment turns that uncertainty into a prediction problem with an independently specified answer. A reader can identify the correct type of closing bracket by inspecting the unmatched openings in the prefix. It is also possible to construct examples with controls that ordinary generated passages lack. The experimenter can preserve a familiar balanced interior and put it inside new layers, or put familiar balanced pieces together to create a sequence longer than anything used for training.
Training on shallow strings is essential to the question. If deeper examples are already present in training, a successful test at those depths can show that the network handles new examples in a familiar structural range. Bernardy wants to know what happens when the range itself changes. The relevant evidence is success at closures whose matching demands exceed what the training strings exhibit. Accuracy at those closures is more informative for this purpose than a passage that looks syntactically plausible to a reader.
What earlier tests established
The paper traces earlier experiments with differentiable stacks to work by Das and colleagues. A differentiable stack lets a network learn how to control storage while retaining a continuous computation suitable for training. Some of the synthetic languages in that work used runs of symbols whose lengths had to correspond. Bernardy groups those examples with problems that a counting procedure can solve. Their value is in showing that a network can acquire particular numerical dependencies between stretches of a string. A sequence of different unresolved bracket types poses an additional memory requirement.
The paper also discusses work by Gers and Schmidhuber showing that an LSTM could learn simple synthetic languages of this kind. In Bernardy’s account, that result makes it important to distinguish what can be handled by a general-purpose recurrent unit with continuous state from what motivates a specialized memory architecture. The analysis of counting behavior by Weiss and colleagues gives the paper further context for treating a successful count as a plausible recurrent computation. On the Practical Computational Power of Finite Precision RNNs for Language Recognition
Elman’s work addressed a more structured artificial language with material embedded in the middle of a construction. In such cases, elements belonging to the larger construction must be related across material belonging to an inner one. Bernardy describes this experiment and Cartling’s follow-up as leaving open the step from shallow training to deeper test examples. The present study keeps that step central by deliberately constructing test strings that increase the amount of nesting the network has to handle.
Work on agreement supplied a related test in natural sentences. In an English sentence, intervening nouns can make it harder to predict the form of the verb that agrees with the subject. A noun whose features conflict with those of the subject is an attractor. Bernardy cites experiments by Linzen and colleagues and by Bernardy and Lappin that counted such intervening nouns. The paper reports near-perfect performance in their no-attractor condition and performance much closer to baseline with 5 or more attractors. Assessing the Ability of LSTMs to Learn Syntax-Sensitive Dependencies
The paper describes work by Gulordava and colleagues as corroborating good agreement performance with fewer than 5 attractors across other languages, including Italian, Hebrew and Russian. The paper’s methodological reservation concerns what an attractor count measures. It quantifies interference along a sequence. It does not directly specify how many syntactic constructions are open at the same time, and the paper argues that the two quantities can scale differently in natural data. A natural sentence can also admit competing analyses, and markers of embedded structure may be absent. Explicit brackets make those factors easier to control. Colorless Green Recurrent Networks Dream Hierarchically
Bernardy also discusses Yogatama and colleagues, who compared memory architectures on agreement with up to 5 attractors. In his account, their strongest architecture used a stack that could remove several entries in a single step. The comparison connects memory design to the treatment of long dependencies. Its agreement task supplies a different kind of evidence from a deliberately constructed shift in nesting depth.
For the explicit-stack architecture, Bernardy draws most directly on Grefenstette and colleagues, who used differentiable stacks for sequence transduction, the production of an output sequence from an input sequence. The paper simplifies that idea into a recurrent layer with the same general interface as the other layers in the experiment. It also contrasts the design with Joulin and Mikolov’s independently controlled stack units. Bernardy’s unit applies one control decision to whole vectors, so the values forming a stack entry move together. That choice is closely aligned with a task in which a complete representation of an opening bracket needs to be stored and recovered.
The method, step by step
Start with a grammar that fixes the closing type
Bernardy uses a generalized Dyck language, a family of formal languages made of correctly matched brackets. An expression can be empty. It can also consist of a balanced expression enclosed in a matched pair, or balanced expressions joined in sequence. The start rule adds # at the end. That marker is part of the prediction alphabet and distinguishes a finished string from a balanced prefix to which another expression could be appended.
Here is the start rule.
S ::= E#
S denotes a complete string, E denotes a balanced expression, and # is the termination character. The operator ::= introduces a grammar rule. Juxtaposition means that the symbols or expressions on its right appear in the order shown.
The wrapping rule is the source of recursive embedding.
E ::= oEc for every (o, c) ∈ P
E again stands for a balanced expression. P is the inventory of allowed opening and closing pairs. Within a pair (o, c), o is the opening character and c is its matching closing character. The sign ∈ indicates membership in the pair inventory. Because E occurs inside the pair on the right, any expression produced by the grammar can itself be enclosed.
The grammar also allows independent balanced expressions to follow one another.
E ::= EE
E on the left denotes the expression being formed, and the occurrences on the right denote consecutive balanced expressions. ::= again introduces a production. Joining expressions this way leaves each part internally complete. Any obligations established before those parts began still have to be resolved outside them.
The empty case ends the expansion.
E ::= ε
E is the expression on the left of the production sign ::=. The symbol ε represents an empty string. This rule lets a pair have nothing inside it and lets the complete output consist of the termination marker alone.
It is helpful to distinguish the bracket count from the complete character count because the training and test sets are specified by length. Bernardy writes the exact-length subset as follows.
Dᴾₙ = {x ∈ Dᴾ | length(x) = n + 1}
Dᴾ denotes the language for pair inventory P, and Dᴾₙ names its exact-length subset. The variable x is a complete string. The braces enclose a set, ∈ means membership, and the vertical bar introduces the condition for inclusion. length(x) counts the characters of x. The 1 in n + 1 accounts for the termination character, so n describes the bracket portion. Each equals sign specifies either the set being defined or the required length within that set.
A second subset collects strings through a length bound.
Dᴾ≤ₙ = {x ∈ Dᴾ | length(x) ≤ n + 1}
Dᴾ≤ₙ denotes the bounded subset of Dᴾ. The variable x, the membership sign ∈, the set braces and the condition divider | have the same roles as in the preceding definition. The function length includes # in the character count. The sign ≤ admits all lengths at or below the bound, and adding 1 again allows for the marker. The string-length use of n is separate from the use of that letter for the width of a recurrent layer.
Give every architecture the same prediction task
The input arrives character by character. The network receives each character as an embedding, a vector of numerical values associated with that character. In the reported experiments the vectors have size 12. A recurrent layer combines the current input with information carried forward from earlier steps. Where there is another layer, it receives the output of the first layer at the same step. A final dense layer with softmax activation converts the resulting values into probabilities over the possible next characters.
A prefix can contain both an opening whose partner is still due and complete expressions encountered since the opening. The recurrent state has to represent the distinction in whatever form its architecture allows. The training target is the actual next character throughout the sequence. The grammar supplies the examples, and the loss comes from predicted characters. Thus a stack controller can acquire a policy from the prediction objective without a separate target that tells it when to push or pop.
From balanced strings to closing-bracket scores
The steps in order.
The design keeps the embedding and readout in place across recurrent configurations. The comparison changes how the network stores history between steps and, in the layered configurations, how the stream reaching the final recurrent layer is produced. The main typed-bracket evaluation selects a subset of prediction positions after training. The resulting scores concern the decisions where the grammar fixes which bracket identity is relevant.
How the LSTM keeps and exposes information
The long short-term memory layer keeps a cell state and a hidden state. The cell state carries long-term information. The hidden state is the part exposed as the layer’s output and is also available when the next step is computed. The layer first joins the previous hidden state to the current input.
vₜ = hₜ₋₁ ⧺ xₜ
t denotes the current timestep, hₜ₋₁ the hidden state from the previous step, and xₜ the current input vector. The operator ⧺ concatenates the vectors. The result is vₜ, the input to the gate calculations.
The forget gate controls retention of the previous cell state.
fₜ = σ(W_f vₜ + b_f)
fₜ is the forget gate at step t. W_f is its learned weight matrix, and W_f vₜ is the matrix applied to the combined vector vₜ. b_f is the learned bias vector added to that result. The symbol σ denotes the elementwise gate activation.
The input gate controls how much newly proposed information enters the cell state.
iₜ = σ(W_i vₜ + b_i)
iₜ is the input gate at step t. The matrix W_i and bias vector b_i are trainable quantities used in its affine calculation. vₜ is the concatenated input and previous hidden state, and σ applies the gate activation to the resulting values.
There is also a gate for exposing the updated memory to the rest of the network.
oₜ = σ(W_o vₜ + b_i)
oₜ is the output gate at time t. W_o is the output gate’s weight matrix, vₜ is the same combined vector used by the other gates, and σ denotes the gate activation. Bernardy’s displayed equation uses the bias label b_i here as well as in the input gate. The parameter count is given separately in the paper.
The layer forms a candidate contribution to memory from the same input vector.
c̃ₜ = g(W_c vₜ + b_c)
c̃ₜ is the proposed cell contribution at step t, with the tilde distinguishing the proposal from the committed cell state. Here g denotes the elementwise transformation of that candidate calculation. W_c is the candidate’s learned weight matrix, b_c its learned bias vector, and vₜ the combination of current input and previous hidden state.
The old cell state and the candidate are then combined.
cₜ = fₜ ⊙ cₜ₋₁ + iₜ ⊙ c̃ₜ
cₜ is the updated cell state, and cₜ₋₁ is the previous cell state. The forget gate fₜ weights the old memory, while the input gate iₜ weights the candidate c̃ₜ. The symbol ⊙ denotes multiplication coordinate by coordinate, and + adds the resulting vectors. Each coordinate can therefore retain a different amount of its old value and incorporate a different amount of the candidate.
Finally, the output gate controls how the current cell state appears in the hidden state.
hₜ = oₜ ⊙ tanh(cₜ)
hₜ is the hidden state at step t, oₜ is the output gate, and cₜ is the current cell state. The function tanh is the hyperbolic tangent applied to each coordinate. The symbol ⊙ again means elementwise multiplication. The hidden state is passed to the next step as well as to the next layer or readout.
The paper emphasizes the path through the cell state. With appropriate gate values, the contribution from earlier memory can persist across many updates. The same path matters during training because the derivatives used to adjust parameters must travel backward through those updates. That gives the LSTM a mechanism for keeping information relevant to a later output. Which information it keeps, and how it uses it at a deeper closure, is the empirical question.
The paper gives the following parameter count for a plain LSTM layer.
4(n + m)n + 4n
n denotes the number of recurrent units and the width of the hidden and cell states. m is the width of the input vector. The first term counts scalar weights over the combined input and state, and the second counts scalar biases in the paper’s stated total. Adjacency indicates multiplication and + indicates addition. Increasing n changes both the state width and the size of the transformations applied to it, which is why the layer’s parameter count grows quadratically with that width.
How the GRU updates a shared state
The gated recurrent unit uses the hidden state for both memory and output. As in the LSTM, the current input is joined to the preceding hidden state. The paper uses a variant whose update and reset gate equations have no bias terms. The recurrent unit comes from Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation.
vₜ = hₜ₋₁ ⧺ xₜ
vₜ is the joint vector at time t. hₜ₋₁ is the previous hidden state, xₜ is the current input, and ⧺ denotes concatenation.
The update gate determines how strongly the proposed new state should contribute.
zₜ = σ(W_z vₜ)
zₜ is the update gate at step t. W_z is its trainable weight matrix, vₜ is the joint vector, and σ is the elementwise gate activation. Writing the matrix next to the vector denotes matrix–vector multiplication.
The reset gate controls the contribution of the previous hidden state to the candidate calculation.
rₜ = σ(W_r vₜ)
rₜ is the reset gate at step t. W_r is its trainable matrix, vₜ is the joint vector, and σ again acts coordinate by coordinate. The reset gate feeds the candidate calculation, while the update gate acts when the candidate and previous state are blended.
The candidate state is computed from that gated history and the current input.
h̃ₜ = tanh(W_h ((rₜ ⊙ hₜ₋₁) ⧺ xₜ))
h̃ₜ is the candidate at time t. rₜ is the reset gate and hₜ₋₁ is the preceding hidden state. Their product ⊙ is elementwise. The operator ⧺ joins the gated history to the current input xₜ, W_h is the learned matrix applied to the result, and tanh is applied elementwise.
The layer chooses a blend of old state and candidate.
hₜ = (1 − zₜ) ⊙ hₜ₋₁ + zₜ ⊙ h̃ₜ
hₜ is the current hidden state and output. 1 − zₜ denotes the elementwise complement of the update gate zₜ, so it weights the old hidden state hₜ₋₁. The gate zₜ weights the proposed state h̃ₜ directly. The sign − denotes subtraction, ⊙ denotes coordinatewise multiplication, and + adds the contributions.
The paper gives its GRU layer the following number of scalar parameters.
3(n + m)n
n is the width of the recurrent state, and m is the input width. The factor 3 accounts for the trainable matrices in this variant. The parentheses group the combined width n + m, and adjacency denotes multiplication. At the same unit count, this GRU uses fewer parameters than the LSTM described in the paper. Both counts grow quadratically with the recurrent width.
How the stack unit stores a sequence of entries
The special-purpose recurrent unit with a stack-like state is abbreviated RUSS. The basic idea follows the order of bracket matching. Putting the current input at the top of a stack makes it immediately available. Removing the top brings the preceding entry back into view. Leaving the stack alone preserves the current order. These operations let the architecture retain a sequence of values in the order needed for nested closures.
The unit carries a stack of fixed depth during a run. Each entry is a vector. The depth is denoted by d, and the entry width in the paper’s state description is denoted by n. The action decision looks at the previous top entry together with the current input.
vₜ = sₜ₋₁[0] ⧺ xₜ
vₜ is the controller input at time t. sₜ₋₁ is the previous stack state, and [0] selects its top entry. xₜ is the current input vector. The concatenation sign ⧺ joins these vectors before the action scores are calculated.
Those scores become a set of weights over the available updates.
aₜ = softmax(W_a vₜ + b_a)
aₜ is the action-weight vector at time t. W_a is the learned matrix for the controller and b_a is its learned bias vector. The controller applies the matrix to vₜ and adds the bias. softmax converts the scores into non-negative weights that sum to a whole, allowing the controller to favor an action to varying degrees.
The stack update combines the possible successor states.
sₜ = aₜ · [[xₜ] ⧺ sₜ₋₁[0..d−2], sₜ₋₁[1..d−1] ⧺ [0], sₜ₋₁]
sₜ is the current stack and sₜ₋₁ is the preceding stack. The dot · takes a weighted combination using the entries of aₜ. The outer brackets list the candidate states, in the order push, pop and no action. In the push candidate, [xₜ] makes the input into a stack entry and ⧺ places it above the retained slice sₜ₋₁[0..d−2]. In the pop candidate, sₜ₋₁[1..d−1] keeps the entries below the old top and [0] appends a zero entry at the bottom. In these slices, .. indicates an inclusive range of positions, − is subtraction, and d is the stack depth. The no-action candidate is the old stack itself.
The layer exposes its new top as output.
hₜ = sₜ[0]
hₜ is the output at step t, sₜ is the updated stack, and [0] selects its top entry. The full stack remains available to subsequent updates. Only its top goes through this output interface.
With a highly concentrated action weight, the update can operate much like a conventional stack instruction. With weight distributed among actions, the new state is a blend of the candidate stacks. The blend makes the update continuous for training. It also means that the contents of a learned stack need to be understood in terms of those mixtures. The definition gives the network a push and a pop operation, while learning still determines when each should be favored and how usable the resulting entries will be.
The scalar parameter count stated for the RUSS is the following.
6m + 3
m is the width of the input vector. The term 6m counts the controller weights, and 3 counts the action biases. The plus sign adds those contributions. The depth d is absent from this expression because the controller uses the top entry and current input rather than separate weights for each stack position. Changing the depth changes the amount of storage. Bernardy notes that the same controller parameters can be used with a different depth in another run.
Assemble and train the recurrent configurations
The study compares 11 configurations. The standalone LSTM and GRU are tested with 40 units and with 160 units, and there is a standalone RUSS. These cases establish how each kind of layer performs on its own. The width comparison also gives a way to ask whether simply enlarging the standard recurrent state changes the qualitative pattern of errors.
The remaining configurations place recurrent layers in sequence. Some repeat the same layer type, with 40 units in each layer. Others combine an LSTM and a GRU in both orders, again with 40 units per layer. The final pair of configurations puts the RUSS after an LSTM or a GRU, with 40 units in each layer. Layer order matters to the question being asked. Behind another layer, the RUSS observes the values produced by that preceding recurrent computation. Its controller therefore has to work with a representation that depends on a prefix as well as on the current bracket.
During training, the paper applies 10% dropout to the input and hidden state of the LSTM and GRU. Dropout makes some values unavailable during an update. The long-term LSTM cell state is exempt, and the RUSS receives no dropout. The paper uses characterwise cross-entropy, which penalizes assigning low probability to the observed character. It describes the loss calculation as a sum over characters in the test examples and separately describes fitting the parameters with Adam. The test accuracy used to choose among saved epochs is specified in the typed-bracket experiment. Adam: A Method for Stochastic Optimization
10⁻⁴
This is the stated learning rate for Adam. The base 10 and exponent −4 express the scale of the parameter updates. The optimizer adjusts the trainable weights and biases associated with the next-character objective. Once trained, each network is evaluated on the closing decisions defined for the relevant test.
Experiments and results
The single-type preliminary experiment
The preliminary experiment samples 512 training strings from the language with one bracket pair, with up to 14 brackets before the termination marker. There are 625 possible strings in that bounded language. The test covers all 6917 strings with up to 18 brackets before the marker. The test thus includes strings from the range used for training as well as longer ones. Bernardy uses exhaustive coverage within the test bound because the language is small enough to permit it.
With a single bracket type, a closing character is structurally possible whenever an unmatched opening is present. The informative constraint comes when the balance has returned to empty. A closing bracket would then be invalid. The test feeds a complete balanced expression to the network and checks that it rules out a closing continuation there. This probes whether the network distinguishes a prefix that can still be closed from a prefix that has no pending opening.
Every tested configuration exceeds 99% accuracy on this criterion in fewer than 5 epochs. Bernardy presents the figures as conservative because runs vary. The experiment gives a quick check that all the architectures can acquire the relevant balance behavior on the small language. A counter that increases when a pair opens and decreases when it closes provides a sufficient solution. The main experiments therefore introduce closing identities that can differ at the same balance.
How the typed-bracket score works
The main experiments use 5 distinct matching pairs. Every opener has its own closer, and the characters in the pair inventory are unique. With the end marker, the prediction layer has 11 possible characters. The paper illustrates the ambiguity of ordinary next-character scoring with the prefix (([(). The inner round pair has just been completed. If the next action is a closing, the corresponding square bracket is due. The sequence could also continue with an opening of any available type.
The paper gives about 17% as a reference for guessing among the 6 grammatically available continuations and about 9% for a random choice among the 11 characters. When no pair is pending, termination takes the place of the closing option in this description. These figures motivate the evaluation by illustrating the ambiguity of the generation task. A prediction can respect the grammar and still differ from the character actually sampled for an example.
Closing-bracket accuracy concentrates on less ambiguous positions. For a test string, the experiment selects indices where the observed character is a closer. It counts a success when the network assigns the highest probability to the expected closing type. The reference for a perfect predictor on those decisions is 100%, and uniform guessing among the closing types gives about 20%, assuming the termination character causes no confusion. The random reference is a probability calculation in the paper, not an independently trained baseline.
The score is reported separately by character position. Each point consequently concerns the test examples that have a closing bracket at that position. The sets of examples contributing to positions can differ. At some indices, a closing bracket may belong to the interior of a balanced block. At others, the test construction ensures that the closer belongs to a deliberately added outer layer. A single average would combine those different demands.
Both typed experiments train on 512 × 200 strings drawn from the bounded set with up to 10 brackets before termination. The paper gives 131,250 as the size of the exact-length set at 10. Training runs for 100 epochs and retains the parameter version with the highest accuracy on the test data. The two subtasks then use different constructions for their test strings while keeping the same training setup.
Subtask A asks how long an opening can remain available
The long-distance test brings balanced chunks together to make longer inputs. In the prose description, two balanced chunks of size 8 may occur in sequence or be wrapped together inside a matched pair. The paper’s formal sampling expression writes the wrapped form.
X = Sample(512 × 20, {o s₁ s₂ c | (o, c) ∈ P, s₁ ∈ Sample(1000, Dᴾ₈), s₂ ∈ Sample(1000, Dᴾ₈)})
X is the test set and Sample denotes random selection of the stated number of strings from the indicated set. The multiplication sign × belongs to the sample count 512 × 20. The braces describe the candidates, and the vertical bar separates their form from the membership conditions. P is the set of bracket pairs, o and c are a matching opening and closing, and ∈ means membership. s₁ and s₂ are balanced chunks, each drawn from a sample of 1000 strings of the exact-length subset Dᴾ₈. The subscripts distinguish the chunks. Juxtaposition joins the bracket material from the selected pieces in the indicated order.
1 + 8 + 8 + 1 = 18
The two occurrences of 1 are the added opening and closing characters, and the two occurrences of 8 are the lengths of the balanced chunks between them. The plus signs concatenate those contributions to length, and the equals sign gives the bracket length of the wrapped construction as 18. This is the count used for the bracket portion that the test analyzes.
Bernardy explains the last closing as matching the first character in the wrapped form or the character at position 9 in the two-chunk form. A system optimized specifically for the final character could use a specialized strategy for such known positions. Here the network has been trained on every next-character prediction and is scored at every closing index. The paper presents that broader profile as a way to check whether strong performance extends beyond the endpoint.
The reported graph shows one run, with the paper saying that the other runs exhibit the same qualitative behavior. The RUSS makes no errors. The LSTM is close to perfect at positions through 10, the length range covered in training. Its accuracy declines for later positions but stays at or above 88% on the reported long-distance test. The GRU exceeds the LSTM through position 14 in that run and then falls sharply. At the last closing, the GRU is only slightly above the random reference.
The last prediction is diagnostic here because it can require recovering an opener across the intervening balanced material. The GRU’s earlier strength shows why an aggregate score would give an incomplete account of the comparison. Earlier positions can supply evidence about successful prediction on much of the sequence. The endpoint probes whether a dependency is still available by the time the longest intervening material has passed.
Subtask B adds obligations outside a familiar interior
In the depth experiment, an interior is sampled from the exact-length subset at 10. A sequence of 5 openings precedes it. The matching closings follow the interior in reverse order, beginning with the partner of the most recent of those openings. The interior could have occurred in training, but the complete wrapped string is outside the training range. The construction demands that the network preserve information about the initial openings while it reads and resolves the interior.
X = Sample(512 × 20, {o* s₁ c* | (o*, c*) ∈ (P⁵)ᵀ, s₁ ∈ Sample(1000, Dᴾ₁₀)})
X denotes the test set, and Sample denotes random selection. The expression 512 × 20 is the test sample count as given by the paper. Within the braces, o* is the sequence of outer openings, s₁ is the balanced interior, and c* is the corresponding closing sequence. The asterisks are part of the names for these sequences. The notation (P⁵)ᵀ expresses the paired opening and closing sequences built from choices of 5 matching pairs from P, with the closing sequence ordered to unwind the openings. The vertical bar introduces the membership conditions, ∈ means membership, and Dᴾ₁₀ is the exact-length subset from which the sample of 1000 possible interiors is drawn.
The paper uses the beginning, middle and end of these test strings to explain the position profiles. It reports no closing scores below index 6 because the initial stretch consists of openings. It describes positions 6 to 10 as corresponding to depths encountered in the input set. For positions 10 to 13, it describes unfamiliar prefixes whose closing decision can still be made using an opening at position 6 or later, within the interior. It uses positions 14 and above to discuss the closing phase that depends on the outer openings. These are the paper’s reporting ranges. The important distinction is between resolving a pair inside the inserted block and recovering a pending opening from before that block.
A new test sample is generated for every run. For configurations other than the standalone stack experiment, the paper reports results from five runs to show how much the curves vary. The best epoch for a run is chosen with its test set, so the position curves describe the selected network for that sample.
An explicit stack and a standard LSTM behave differently at new depths
The standalone RUSS closes the brackets perfectly on the reported new-depth test when its stack is large enough. Bernardy varies the maximum stack depth and reports that a depth of 10 is sufficient for the test set. The unit’s strongest result thus comes from a controller whose storage layout preserves multiple pending entries in order and whose available depth covers the demands of the examples. Capacity checks with smaller stacks help explain where that result stops holding.
The 40-unit GRU stays well above the random strategy at some positions and declines quickly as the opening it needs recedes into the prefix. Its performance for the longest matching distance is only slightly better than guessing. It frequently reaches its best performance in fewer than 20 epochs in this test. Fast convergence and success on the deepest long-range decisions are separate properties in the reported runs.
The 40-unit LSTM has a different curve. It remains above the guessing reference even at its weak points. Its reported accuracy is around 60% at index 15, where it performs worst. Near the end of the test string the accuracy approaches 90%. That recovery matters because the openings associated with those last closings are among the earliest ones. The curve raises the possibility that the LSTM handles particular early openings especially well, even when some other outer openings are recovered less reliably.
Closing-bracket accuracy at index 15 in the typed Dyck new-depth test
The sufficiently deep stack closes brackets reliably at a position where the single LSTM makes frequent errors.
The numbers
| System or setting | accuracy % |
|---|---|
| Uniform closing-type guess, about | 20 |
| Single LSTM with 40 units, around | 60 |
| Standalone RUSS with sufficient stack depth (this paper) | 100 |
The random row is the paper’s approximate closing-type reference. The LSTM row uses the paper’s approximate result at index 15, and the stack row reflects the reported perfect performance at sufficient depth. A figure of this kind compares the choices on the same closing decision. It leaves the full position profile to the surrounding discussion, where the LSTM’s recovery and the GRU’s late decline can be distinguished.
Larger and layered recurrent networks
Increasing the standard layers to 160 units leaves the main patterns recognizable. The larger LSTM has a smoother position profile and still has a dip around position 15. The larger GRU loses some early-position strength, and the LSTM is ahead across the reported profile for the wider layers. Standalone layers take roughly the same time to reach peak performance whether they are larger or smaller. These results connect a substantial change in width to a modest change in the form of the curves.
Pairing 40-unit layers of the same kind gives another view of capacity. The two-layer LSTM reaches convergence at around 70 epochs and has broadly similar accuracy to the smaller single-layer LSTM. Its improvement near the end of the string is more pronounced. The two-layer GRU converges at around 50 epochs. It improves on some of the single-layer GRU’s results and displays a sharper decline around position 14. The same recurrent component therefore retains a recognizable pattern of strengths and weaknesses when it is used twice in sequence.
The mixed LSTM and GRU configurations tend to resemble whichever component appears first. The curves are somewhat smoother than those of the leading component by itself. This result holds as a general tendency in the paper’s description of both layer orders. It makes the sequence of layers part of the comparison, even when the two configurations contain the same kinds of components.
The stack combinations are more variable. An LSTM followed by a RUSS improves predictions for short prefixes and for positions near the end of the depth-test strings. Around positions 14 to 15, it can slightly reduce accuracy. A GRU followed by a RUSS ranges from perfect prediction in some runs to performance only modestly above that of the standalone GRU in others. The paper also observes that configurations with a recurrent layer feeding the RUSS are often still improving at 100 epochs. Their scores show what the combinations achieved during the reported training run.
What the ablations show
The scoring position changes the answer
The experiment includes controlled comparisons in language structure, width, layer order and stack depth. It also examines accuracy at individual points in a sequence. That last choice supplies much of the evidence about what each architecture learns. The paper says that compound measures such as accuracy or perplexity can look similar for the LSTM and GRU. Perplexity summarizes how much probability a predictor gives to the observed sequence. An aggregate can absorb failures at a few structurally important positions among successful predictions at easier ones.
The long-distance experiment illustrates the problem directly. The GRU’s stronger performance at earlier positions coexists with failure near the endpoint. The LSTM gives up some accuracy relative to the GRU early in the reported run and retains much more at the end. A closing character deep into a long string therefore answers a different question from the average prediction across the string. The comparison is especially informative because the test design supplies a reason to expect that the final closure needs information retained across complete intervening chunks.
The change from the single-type language to the typed language has a similar role at the level of the task. Successful balance tracking is nearly universal in the preliminary experiment. With typed brackets, a network must recover the correct opener among several possibilities. The comparison identifies the point at which maintaining a count is insufficient to supply the answer. Each architecture’s later profile then shows how reliably it deals with the extra demand.
The LSTM may give special treatment to the outer pair
A simple loss-of-memory account would predict that harder closures arise steadily as the distance to the opener grows. The GRU’s late deterioration broadly follows that expectation. The LSTM’s accuracy dips and then rises as the final positions approach. Bernardy interprets the rise as possible evidence of a specialized strategy for the outermost pair.
The proposed strategy combines two kinds of information. A counting mechanism could indicate when the final outer closing is due. A separate part of the state could preserve the type of the first character. In a wrapped string, those pieces of information together would support an accurate last closing even if the network’s record of intervening unmatched openings were incomplete. This fits the architecture’s ability to keep multiple continuous values and the preliminary evidence that recurrent networks can solve a balance test.
The paper’s evidence for that account is behavioral. The position profile is consistent with the proposed strategy and makes it reasonable to examine. The experiment does not inspect a learned counter or intervene on a state variable carrying the first character’s identity. Other computations could produce a similar profile. What the test demonstrates directly is the unevenness of the LSTM’s retrieval across positions, including surprisingly good performance on the longest outer dependency.
Width and repeated layers leave the basic patterns visible
Bernardy tests the explanation that LSTM performance comes from having more scalar parameters than the GRU. At matched unit widths, the LSTM cell does have a larger parameter count. Widening the recurrent layers from 40 to 160 units changes the amount of state and the number of parameters available to both architectures. It fails to erase the distinctive LSTM dip and recovery or the GRU’s late deterioration. Bernardy takes that result as evidence against raw parameter count as the explanation for the qualitative difference.
The remaining architectural explanation suggested by the paper concerns the LSTM’s separate cell memory and hidden output. That arrangement allows something to persist in the cell while the exposed output changes with the demands of the current character. It is compatible with successful retention across an intervening block. The width comparison leaves this explanation open. A control that changed only the separation of memory and output would be needed to attribute the observed difference to that feature specifically.
Repeating a layer offers a different way to add recurrent computation. The stacked LSTM reinforces the good results on the later positions, and the stacked GRU can improve the early part of the curve while sharpening its late drop. The within-family comparisons indicate incremental benefits and preserve the features that distinguish the two kinds of recurrent unit. The evidence therefore concerns what layering did to the existing behavior under this training procedure.
Putting different standard layers together makes the input to the second layer a learned stream shaped by the first. The reported resemblance to the first layer suggests that features preserved or emphasized early continue to matter for subsequent decisions. Because the study scores the output of the whole network, the source of that resemblance remains an interpretation. A second layer might be making limited corrections, smoothing the stream or redistributing information in ways that happen to yield a similar position curve.
The stack-depth control tests the memory the design makes available
Changing the RUSS depth alters how many entries the architecture can retain while leaving the number of trainable controller parameters fixed. This is a more specific manipulation than widening an LSTM or GRU, which changes state size and parameter count together. It gives the paper a way to check whether sufficient storage for pending openings is associated with correct closure of deeply nested strings.
Bernardy reports that limiting the stack can prevent a correct final prediction for strings deeper than that stack can accommodate. In a conventional push operation at capacity, the bottom entry is dropped as new material arrives at the top. In the bracket task, the bottom entry may carry exactly the opening required at the final closure. This connects the position of the error to the role of the memory being varied. With depth 10, the standalone unit has enough capacity for the reported test set and predicts its closings correctly.
The mixed networks test how this advantage carries through a preprocessing layer. A standalone RUSS sees an embedding associated with the current character. In a combination, the vector it sees depends on the preceding recurrent network’s state. A successful stack controller has to identify useful operations from that stream and store vectors that remain informative when recovered later. The variable GRU–RUSS runs show the importance of learning a workable combination. The improvement at some positions and deterioration at others for LSTM–RUSS show that the same component can have different effects within a single test sequence.
Limitations
Limits Bernardy states
Bernardy frames the typed bracket task as a simplification of learning context-free languages. It supplies known pairs, visible opening and closing markers, and a clear criterion for the next admissible closer. A richer grammar can require the learner to discover which constructions are present and how their boundaries are expressed. In this sense, the paper calls the experiment an upper-bound test of the networks’ ability to learn nested recursion. That is a claim about the relative simplicity of the challenge. The measured percentages describe the experimental strings and scoring rule.
The author regards the LSTM’s generalization as substantial but too error-prone to treat it as reliable context-free performance. In the conclusion, the reported error rate nears 40% for nesting depths that were never encountered during training. That number describes the difficult new-depth behavior, alongside much better performance at some other positions. The paper’s recommendation of a specialized component is tied to applications that need greater reliability on closures at unfamiliar depths.
The paper also limits its architectural explanation. The LSTM and GRU differ in the way they maintain and expose state, and their behavior differs in the tests. The results on width weaken one simple explanation based on parameter count. Separate long-term memory and output remain a plausible explanation, for which Bernardy calls for corroborating evidence. The experiments establish a difference in observed behavior for the variants used here.
For natural language, Bernardy cites Karlsson’s observation that deep recursion is uncommon in actual input. This makes it plausible that an LSTM could see the range of depths it typically needs during training. The paper discusses a possible connection between finite memory and the limited depth ordinarily found in human production. Its claim stays at that level of compatibility. The bracket experiments supply no anatomical evidence about human language processing.
The paper mentions contexts where greater depth could matter in spite of its rarity in ordinary input. An argumentative exchange can embed earlier quoted material. Formally constrained work, such as source code or logical expressions, can be produced with external memory aids. Legal writing and some musical work are also mentioned as possibilities. These are examples of why a designer might care about new depths. The measurements themselves come from the generated bracket strings.
Limits apparent from the design
The reported depth generalization is finite. Training uses a bounded distribution, testing uses carefully constructed longer strings, and the successful standalone RUSS has a chosen finite stack capacity. The controller can be reused at another stack depth because its weights have no depth-specific coordinates. That makes larger storage possible. The experiment establishes the behavior of the tested controller on the sampled depth challenge, leaving its reliability over arbitrary strings and much larger depths open.
The typed score covers the identity of the expected closing bracket at selected positions. It says little by itself about the probabilities assigned to all grammatical alternatives at other positions. In particular, openings, termination and the decision to close at a given point contribute to the training objective but are outside the focus of this accuracy measure. A network that is good at identifying closers under the test conditions would need separate evaluation for complete string generation or for accepting and rejecting strings by itself.
Both extrapolation tests have deliberately regular constructions. The long-distance test builds out of balanced chunks. The new-depth test uses a block of openings before a balanced interior, then their matching closings. This structure makes it possible to target particular dependencies. It can also make some positions predictable through a shortcut tailored to the construction, as Bernardy’s explanation for the LSTM’s treatment of the first opening illustrates. More varied arrangements of unfamiliar depths would probe whether a learned procedure transfers across different orders of openings and closings.
The depth test increases overall length while increasing the amount of pending outer structure. Its late closures can require both recovery across a long intervening block and maintenance at unfamiliar depth. The long-distance subtask supplies related evidence about those demands because the interiors are constructed differently. Together the experiments distinguish useful patterns of behavior, while leaving room for a design that varies distance and depth independently at every diagnostic position.
There is also a limit to what can be inferred from the treatment of the test set. Fresh test samples reduce the chance that decisions developed across runs are tailored to one fixed set of strings. Within a run, the sample still determines which of the 100 saved epochs is reported. Its accuracy is therefore also the criterion for choosing the final parameters. An independent sample scored after that selection would assess how well the selected epoch generalizes beyond the data used to choose it. The paper’s curves are evidence about performance under its stated selection procedure.
Finally, the per-position curves describe the closing cases available at each character index. Their composition changes as the test moves from interior closings to the outer closing sequence. A decline across positions can therefore reflect a change in the kind of dependency being evaluated as well as the distance measured in characters. The design deliberately uses that change to reveal failures hidden by aggregate scores. It supports the clearest conclusions when the curve is read alongside the opening that each closing is meant to recover.
What came after
Later citing work returns to the bracket problem from several directions. The closest continuation in subject is Skachkova and colleagues’ study of bracket closure with recurrent neural networks. It keeps the research question tied to the behavior Bernardy makes observable: after the network has read a prefix, the choice of closer tests which unfinished opening is still accessible. That shared task connects studies of recurrent memory through a decision whose correct answer is fixed by the input structure. Closing Brackets with Recurrent Neural Networks
Belinkov and colleagues cite the paper in a survey of neural language analysis. That setting gives the bracket experiment a different role. A synthetic language with controlled examples belongs to a broader set of ways to investigate what neural systems have learned. Bernardy’s case illustrates the kinds of distinctions such an analysis can make by comparing character positions, widening a layer and altering the available stack depth. The later work is a survey, so its connection is through the analysis of neural behavior. Analysis Methods in Neural Language Processing: A Survey
Ebrahimi and colleagues carry the Dyck recognition question to self-attention. That moves the focus from a recurrent state updated as each character arrives to a different way of drawing on information in a sequence. The formal-language question remains recognizable. A typed Dyck string requires both balance and the proper ordering of matching types. The later title asks how recognition of this family can be achieved with self-attention, whereas Bernardy’s experimental score directly tracks the closing predictions of recurrent architectures. The shared language links the studies even where their stated tasks differ. How Can Self-Attention Networks Recognize Dyck-n Languages?
Yao and colleagues also study self-attention, focusing on bounded hierarchical languages. The bounded condition gives the connection to Bernardy’s experiment particular precision. A hierarchy with a stated bound raises the question of what an architecture can do within that range. Bernardy varies the depth seen during training and then checks predictions on deeper samples, while also varying the capacity of the explicit stack. The later work’s focus carries forward the question of which hierarchical structures a particular architecture can process when the extent of the hierarchy is part of the problem. Self-Attention Networks Can Process Bounded Hierarchical Languages
Cite
Cite as Jean-Phillipe Bernardy. 2018. Can Recurrent Neural Networks Learn Nested Recursion?.
@misc{jeanphillipe2018can,
title = {{Can Recurrent Neural Networks Learn Nested Recursion?}},
author = {Jean-Phillipe Bernardy},
year = {2018},
url = {https://aclanthology.org/2018.lilt-16.1/}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bernardy-2018-can-recurrent-neural-networks-learn/