Exploring the Long-Term Generalization of Counting Behavior in RNNs
Abstract
In this study, we investigate the generalization of LSTM, ReLU and GRU models on counting tasks over long sequences.
Previous theoretical work has established that RNNs with ReLU activation and LSTMs have the capacity for counting with suitable conﬁguration, while GRUs have limitations that prevent correct counting over longer sequences.
Despite this and some positive empirical results for LSTMs on Dyck-1 languages, our experimental results show that LSTMs fail to learn correct counting behavior for sequences that are signiﬁcantly longer than in the training data.
ReLUs show much larger variance in behavior and in most cases worse generalization.
The long sequence generalization is empirically related to validation loss, but reliable long sequence generalization seems not practically achievable through backpropagation with current techniques.
We demonstrate different failure modes for LSTMs, GRUs and ReLUs.
In particular, we observe that the saturation of activation functions in LSTMs and the correct weight setting for ReLUs to generalize counting behavior are not achieved in standard training regimens.
In summary, learning generalizable counting behavior is still an open problem and we discuss potential approaches for further research.
Introduction
Recurrent Neural Networks (RNNs) have been the go-to neural model for sequential tasks since the 1980s and have been popular in recent years for a variety of applications, (see e g., Karpathy, 2015), including Natural Language Processing (NLP).
RNNs are highly expressive, as they are theoretically
Turing complete (Siegelmann and Sontag, 1995) and inherit universal approximation capacity (Funahashi and Nakamura, 1992; Leshno et al., 1993) from multi-layer perceptrons.
Although RNNs have largely been superseded by Transformers (Vaswani et al., 2017) in NLP, there is recently a renewed interest in their theoretical properties and speciﬁcally the counting behavior (Merrill et al., 2020;
Srivastava et al., 2022).
Recent work by Suzgun et al.
and Weiss et al.
(2018) follows in the footsteps of Gers and
Schmidhuber (2001) to evaluate the ability of RNN models to learn formal languages in simpliﬁed scenarios.
Weiss et al. (2018) show that single-cell Long Short-Term Memory (LSTM) and Rectiﬁed Linear Unit (ReLU) networks have the capacity for unbounded counting and modeling a set of formal languages (using saturation of some activation functions in LSTMs), while Gated Recurrent Units (GRUs) and Elman RNNs do not.
Weiss et al.
(2018) also report that ReLUs are difﬁcult to train, which is consistent with the ﬁndings by Hochreiter (1991) and Bengio et al.
(1994) that RNNs suffer from vanishing and exploding gradients when trained on tasks with long term dependencies.
LSTM, introduced by Hochreiter and Schmidhuber (1997), remedies some of these problems.
Suzgun et al.
(2019) show empirically that single-cell LSTMs can learn counting behavior to recognize Dyck-1 languages with 100% accuracy in their experiments.
However, several open questions remain, It’s including whether the counting exhibited by LSTMs is sufﬁciently precise for long sequences and to what extent ReLUs and GRUs can learn counting on long sequences.
In this work, we investigate the limits of trained ReLU, LSTM and GRU models in generalizing Dyck-1 recognition to sequences that are substantially longer than those in the training set and analyze when, how and why they fail.
The speciﬁc contributions of this study are:
We observe that single-cell LSTM, ReLU and GRU models generally fail to accept Dycksequences of length 1000 when trained on lengths up to 50.
We further observe that validation loss is a good predictor for long sequence generalization, but reducing loss through longer training is not a practical method to achieve better generalization.
We illustrate and analyze the different failure modes of ReLU, LSTM, and GRU cells.
Our code is publicly available at https://github.com/nadineelnaggar/Long_Term_ Counting_RNNs .
Modeling Dyck-1 Sequences
We evaluate the limit of three different single-cell RNN models trained on Dyck-1 sequences in generalizing to longer sequences.
Dyck-1 sequences have a) one type of brackets, b) an equal number of opening and closing brackets, and c) no closing brackets before their corresponding opening brackets.
We use the same task setup as Suzgun et al.
(2019) to evaluate our models, which is to classify which tokens are valid to follow in a Dyck-1 sequence after each token.
This is equivalent to classifying complete vs incomplete Dyck-1 sequences.
This is limited as a Dyck-1 language acceptance task.
While the sequence is classiﬁed at every time step, sequences that violate condition c) do not occur.
Therefore, this setup does not allow for testing full language acceptance, as deﬁned, e.g., in Merrill (2020).
For training and initial testing, we use the same types of datasets as reported in Suzgun et al.
Our Training Set consists of 10000 sequences with lengths of 2 to 50 tokens.
We use a Validation Set with 5000 sequences of length 2 to 50 tokens.
We use a Long Test Set with 5000 sequences of lengths 52 to 100 tokens.
The disjoint Training, Validation and Long Test Sets are generated in the same way as in Suzgun et al.
We use single-layer single-cell LSTMs, ReLUs and GRUs in our experiments.
We include GRUs in these experiments, although they cannot perform unbounded counting, to compare how this limitation manifests itself empirically.
We train online with the Adam optimizer (Kingma and Ba, 2014), and learning rates of 0.01 for the ReLU and LSTM models, and 0.001 for the GRU models.
The training was run using PyTorch in a Linux environment.
We train 10 models of each type for 30 epochs and select the best model (out of the epochs) per run by validation loss.
We observe convergence typically within 20 epochs of training, often less.
We experimented with training for 100 epochs on a subset without observing any additional beneﬁt.
For ReLUs we train 30 models and select the 10 best runs, as many ReLUs do not learn to recognize Dyck-1 sequences at all.
Very Long Sequence Generalization
We present the prediction perfomance results of our experiments in Table 1.
We observe that all three models perform well on both Training and Validation Sets, but there is more variation on the Long Test Set.
We also observe in Table 1 that ReLUs tend to show very variable performance.
LSTMs perform best on average, and GRUs are on average between LSTMs and ReLUs.
We evaluate the generalization limits of our models that train well on short sequences and generalize well to some longer sequences up to 100 tokens.
We use a Very Long Test Set with 100 sequences of length 1000 tokens, which are generated using same methods as presented in Suzgun et al.
The results on the Very Long Test Set are presented in the last column of Table 1 and are shown as
First Point of Failure because all models but one fail on these sequences.
Only one ReLU model has an accuracy of 4.0% while all the other ReLUs, the LSTMs and the GRUs do not recognize a single [Table] Very Long sequence correctly.
Previous work from Weiss et al.
(2018) shows that it is not possible for GRUs to perform unbounded counting, so it is not surprising that their performance deteriorates sharply for the longer sequences.
ReLUs and LSTMs do have the capacity for unbounded counting, but we observe that training dynamics does not lead to models that count precisely enough in the long run.
Interestingly, the only model that recognizes at least some of the Very Long sequences correctly is a ReLU model, despite their lower average performance.
We will discuss the reasons for this behavior below.
This result does qualify the statement by Suzgun et al.
(2019) that LSTMs can perform dynamic counting, insofar as the counting does not generalize indeﬁnitely.
This is actually not surprising given the results by Weiss et al.
(2018), where LSTMs fail to generalize to very long sequences on a related task, which can be explained by counting not being precise enough, so that the errors accumulate.
Loss and Generalization
[Figure] In practice [Table] ﬁnite counting abilities may be sufﬁcient, hence it would be useful if it is possible during training (through either the training or validation dynamics) to gather sufﬁcient signals in order to understand how well a model will generalize.
This is because repeatedly testing on very long sequences can be expensive.
In this section [Table] we study the utility of training dynamics towards answering the above question.
We use the observation that lower loss values achieved by the models [Table] seems to be related to higher FPF values.
We quantify this in a linear regression between the negative log loss on Training, Validation and Long Test Sets and the FPF on the on the Very Long Test Set.
We use here a different set of models, to include different stages of training with different levels of validation loss.
We take from each of the 10 runs the models after epoch 1, 5, 10, 15, 20, and 25, so that we have 60 models for every type.
This is done in order to have a range of models including some where the loss values are relatively high because the training was still at the beginning.
The Rand p values are reported in Table 2.
We observe that the losses and FPF are well correlated for the LSTMs.
For the ReLUs, we see increased correlation for the losses on datasets with long sequences, but overall the correlation is low.
The GRUs show good correlation on the Training and Validation Sets, but lower correlation values for the Long Test Set, which is plausible given the lower performance on the Long Test Set.
Figure 1 shows scatter plots with the regression lines for the Validation Set loss.
For the LSTMs we see that the lower loss (higher negative log loss) does lead to higher FPF, but there are still many values that are 20-25% lower than the length of the sequences.
The ReLUs are much more variable, so that a low validation loss does not guarantee a high FPF.
The GRUs, are interesting, where we observe that there are a few models with good FPF but relatively high loss.
These models lead to a negative correlation overall and even for very low losses the FPF values are relatively low.
4.1 Effect of Training Duration on Loss
[Figure]
Given that low validation losses correlate with high FPF, a possible strategy for improving long term counting behavior could be to train for more epochs to reduce the loss and thus extend the duration of correct counting.
We show the progression of the validation loss during training for LSTM and ReLU models in Figure 2.
We do not include GRUs as they do not have the capacity for precise counting, so that this strategy does not apply in any case.
The LSTM training behaves normally, i.e. the loss value tends to decrease throughout training for the
LSTM, but the reduction becomes much slower as the training progresses.
For ReLUs, there is no clear trend, but strong variations throughout.
In any straightforward solution of exact counting with LSTMs, like the one proposed by Weiss et al.
(2018), it is necessary to saturate some of the activation functions.
In a cursory inspection we ﬁnd only a few networks where any saturation occurs. In all the experimentation we do in the context of this paper, we do not encounter a single LSTM model that actually recognizes any Very Long sequence, even with longer training.
Thus it seems unlikely that saturation is achievable when training within common ranges.
Overall, extensive training is not a practical approach to achieve long term counting behavior as it computationally expensive and not reliable.
[Figure]
When trying to understand why and how the RNN models fail to count correctly for long sequences, it is worth considering where the counting is represented within the RNN.
In the single-cell ReLU network, the activation h t of the ReLU is the only suitable variable.
For the LSTM, the variable c t (in the notation used by Weiss et al.
(2018)) is the only one that is not the result of a squashing function, and it has empirically been shown to perform counting in their experiments.
The only actual test needed of the counter is the comparison to zero to test whether the sequence is a complete Dyck-1 sequence (or a n b n in the experiments by Weiss et al.
In order to achieve zero activation at the appropriate points in the sequence, the increment when processing an opening bracket needs to be of the same absolute value but opposite sign as the decrement when processing a closing bracket.
The datasets used in these experiments contain only valid Dyck-1 sequences, so that the counter values should not become negative therefore the ReLU should behave linearly.
For a linear model, the order of the tokens plays no role.
In the solution provided by Weiss et al.
(2018) for the LSTM it is necessary that several variables saturate the activation functions to reach 1 orfor exact counting.
In particular, if f t (in their notation) does not saturate, the counter state will be reduced over time, independent of the opening or closing brackets.
For GRUs, it is not possible to consistently have the same increment and decrement as discussed in Weiss et al.
We expect these differences in the operation to result in different behaviors that will mainly occur around the points where counter should be 0, because the Dyck-1 sequence is complete.
For this purpose we create a dataset that consists of repetitions of j opening brackets followed by j closing brackets for j = { 10 , 20 , 25 , 50 , 100 , 125 , 200 , 250 , 500 , 1000 } .
All sequences in this dataset are 2000 tokens in length, and distinct.
We refer to this dataset as the Zigzag Set .
We test our 60 models for each RNN type at various stages of training, as in the previous section, on the Zigzag Set and record the FPF achieved for each model on each element of the dataset.
The results on the Zigzag Set are that LSTM and GRU models perform better on the sequences with smaller j , showing evidence of a non-linear inﬂuence of the counter value (which is proportional to the depth, i.e. the number of open brackets without a corresponding closing bracket).
To illustrate the different behaviors, we plot in Figure 3 the distribution of the FPF values for the
Zigzag sequence with j = 500 and show in detail graphs positions 500-1000.
At positionwe have a complete Dyck-1 sequence, so that the counter should be 0 and the RNN should predict the corresponding class.
The LSTM models fail mostly at a short distance before position(Figure 3 (a) and (d)), indicating that the decrements are consistently greater by absolute than the increments.
ReLUs fail mostly at position 1000, indicating that the decrement is less by absolute than the increment, but they also fail before (Figure 3 (b) and (e)), indicating that the position of failures is not dependent on the sequence depth.
The GRUs’ increment and decrement values vary throughout the sequence with the decrements relatively large when the counter value is greater.
This leads to a failure soon after closing bracket sequence starts (Figure 3 (c) and (e)).
The GRU behavior conﬁrms the known limitations.
The observations of the ReLUs conﬁrm that they can have decrements greater or smaller than increments and independent of the sequence depth, but that ﬁnding correct weights by backpropagation with gradient descent is difﬁcult.
LSTMs conﬁrm that exact counting does not occur in a normal training setup and saturation of the activation functions is rarely observed, preventing straightforward solutions.
This is a potential explanation for the fact that the best model in our experiments was a ReLU model.
In the ReLU, saturation of an activation function is not possible and not needed, so that it is possible for the learning process to occasionally reach a good weight conﬁguration even if the training process is not very effective on average.
Conclusions and Future Work
In this study, we investigate the generalization of RNNs trained to recognize Dyck-1 languages.
The counting behavior of the trained models is effective on sequences up to double the length of the training sequences, but almost always fails on sequences of 20 times the length (1000 tokens in this case).
While Training, Validation and Long Test Set losses are predictive for very long term generalization, the correlation is not perfect and training for longer to achieve better generalization is not a practical solution as long training is not efﬁcient on LSTMs and not reliable on ReLUs.
The different failure patterns of LSTMs, ReLUs and GRUs correspond to our hypotheses of their operation and shows that despite the theoretical capacity of LSTMs and ReLUs, the networks do not reach exact solutions even in the simple noiseless test cases we tried.
This study empirically extends and explains the theoretical ﬁndings by Weiss et al.
(2018) and the experiments by Suzgun et al.
In the future, there are many interesting research topics stemming form these results.
Understanding the training dynamics of LSTMs and ReLUs better is important, as it will help determine how to initialize and train LSTMs to reach saturation by backpropagation and for ReLUs how to learn the correct weight conﬁguration in a stable way.
Other interesting aspects are the behavior of more commonly used architectures (multi-cell and multi-layer networks), batch training and regularization, and different sequence lengths for training.
Many approaches have been developed to improve the learning of RNNs in general, and they may be helpful in this context.
E.g., for ReLUs, gradient clipping has been proposed by Pascanu et al.
(2013) and widely applied.
Speciﬁc weight initialization methods may help especially the ReLU networks to learn more effectively (Le et al., 2015).
Targeted discretization of model weights or saturating the activation functions may be effective with LSTMs.
Overall, the learning of discrete counting behavior for the long term with continuous neural networks is not yet solved and more work is needed to understand the theoretical foundations and design effective improvements.