Understanding Transformers via N-Gram Statistics

Authors: timothy  nguyen
google  deepmind
Venue: NeurIPS_cc_2024_Conference
Published: 2024-05-15 12:30:06

Abstract: Transformer based large-language models (LLMs) display extreme proficiency with language yet a precise understanding of how they work remains elusive. One way of demystifying transformer predictions would be to describe how they depend on their context in terms of simple template functions. This paper takes a first step in this direction by considering families of functions (i.e. rules) formed out of simple N-gram based statistics of the training data. By studying how well these rulesets approximate transformer predictions, we obtain a variety of novel discoveries: a simple method to detect overfitting during training without using a holdout set, a quantitative measure of how transformers progress from learning simple to more complex statistical rules over the course of training, a model-variance criterion governing when transformer predictions tend to be described by N-gram rules, and insights into how well transformers can be approximated by N-gram rulesets in the limit where these rulesets become increasingly complex. In this latter direction, we find that for 79% and 68% of LLM next-token distributions on TinyStories and Wikipedia, respectively, their top-1 predictions agree with those provided by our N-gram rulesets.

Main paper: 
 introduction: 
 This paper is an attempt to answer the following Question: How does a transformer-based large language model (LLM) make use of its context when predicting the next token?Our approach proceeds via studying the statistical properties of training data. This is perhaps the most natural place to start even though it is not exhaustive (e.g. it does not include in-context learning [5]). The reasons to understand LLM behavior in terms of the statistics of their training data are plenty. First, the functional form of how LLMs use their training data is not well-understood (though there has been progress on understanding memorization [22, 6]). Second, the over-reliance of LLMs on training data statistics leads to brittleness (e.g. the "reversal curse" [3]) and the perpetuation of dataset biases [12]. Understanding the nature of this statistical dependence can lead to improved and more informed dataset curation and training methods. Finally, in various scenarios, the performance of LLMs on downstream tasks are found to be correlated with frequency of relevant training data [26, 10, 16, 17]. A better understanding of this phenomenon would allow better steering of models towards desired performance levels.We can think of the complexity of an LLM next token prediction (regarded as a probability distribution over tokens) along two axes: form and selection. Form refers to the functional form of the prediction as a function of the context, e.g. whether the prediction is some explicit function of associated training data statistics (see Figure 1 ). Selection refers to which functional form, chosen from a set of functional templates, suitably describes the transformer prediction (supposing the choice set is sufficiently rich). As a first nontrivial step, one might hope that an approximate model for an LLM is that each of its next token predictions can be roughly described by simple statistical rules from Figure 1 : Illustration of rule approximation. Given a context, different N -gram based rules formed out of the context will yield different next-token predictive distributions. In the above example, the context consists of three tokens. The first rule uses all three tokens of the context and makes a prediction based on the corresponding 4-gram rule derived from the training data; the second rule uses only the first and last tokens to form a corresponding 3-gram rule (and so the next token "slept" will be assigned less weight than the first rule since the "tired" token is ignored); and the third rule makes a prediction using the N -gram statistics obtained from aggregating over three token contexts from the training data where the second token is arbitrary (i.e. the second token is marginalized). Given a list of such rules, one can ask which rule's predictive distribution best matches that of the transformer.the context (simple form) even if the mechanism for its rule selection remains hidden (complex selection) 1 . This paper is an attempt to see how far this perspective can be pushed, and fortuitously we obtain additional insights for understanding LLM behavior along the way. The statistical rules we consider, which are based on N -grams, are defined in Section 4, with Figure 1 showing some examples.We perform our main investigations on the TinyStories [11] dataset, with supporting experiments on Wikipedia to confirm our results remain robust at larger scales. The use of TinyStories is for practical reasons: its small size makes training models and aggregating N -gram statistics computationally efficient, yet it is complex enough to capture basic natural language statistics (those occurring in simple children's stories).Below is a summary of our observations and contributions:1. (Approximation Criterion) We observe that next token LLM predictions tend to be wellapproximated by N -gram rules when the predictions have low variance across different training runs 2 . In particular, this includes predictions conditioned on contexts with sufficiently high count in the training data. (Section 5) 2. (Curriculum Learning Dynamics) By grouping our N -gram rulesets in terms of complexity (as measured by the amount of context they use), we discover the various ways in which the learning dynamics of LLMs implement a statistical type of curriculum learning, in which easier rules are eventually supplanted by more complex ones. (Section 6.1) 3. (Overfitting Criterion) Based on our analysis of approximating LLM predictions by N -gram rules, we propose a simple and novel procedure for detecting overfitting of LLMs during training. The procedure makes no use of holdout data and it makes quantatively precise the intuition that overfitting corresponds to a model memorizing long context at the expense being able to generalize through making use of subcontext. (Section 6.2) 4. (Approximation Strength) We study how well LLM predictions can be approximated by our N -gram rulesets, noting that significant gains in top1-accuracy occur as we increase ruleset over tokens t: R α (t) = #{αt} #{α * }where the numerator and denominator are the counts for the N -grams from the training data matching the concatenated regular expressions αt and α * , respectively, where * is wildcard (single) character match 6 . (Thus the N -grams in the numerator end with t while those in the denominator can end with any token.) Observe that the next-token predictions of a vanilla N -gram model are obtained by letting R α (t) vary over all ordinary token sequences α of length N -1.Given σ, a symbol from the the alphabet { * , -, +}, consider the following operation which maps a token t to a regular expression:EQUATIONwhere is the empty regular expression. Given now a sequenceσ = σ -N • • • σ -2 σ -1 , define S σ on a sequence of tokens C = C -N • • • C -2 C -1by tokenwise application of (2) and concatenation 7 :EQUATIONThus (3) defines a regular expression which we can think of as fuzzy matching for a subset of a context C (the fuzziness arising from the presence of wildcard matches). For notational convenience, we assume σ is left padded withsymbols, so that we can define S σ (C) for len(σ) < len(C).EQUATIONfor C with len(C) ≥ len(σ). The collection of (4) for various σ defines our N -gram rules under consideration 8 . Each such rule is a function which maps a context C to a next token distribution. We refer to S σ (C) as the rule context for R σ (t|C).As concrete examples, let σ = + - * +.EQUATIONEQUATIONis a rule which yields a next token distribution based on a particular combination of 4-gram model statistics: it retrieves all three token contexts in the training data whose first token is C -4 and last token is C -1 and marginalizes over the second token. Likewise, the rulesEQUATIONare respectively a trigram model with context C -4 C -3 (all other tokens receiving aare dropped) and a model which uses four tokens of context but marginalizes over the two most recent ones.When σ consists of all + symbols, we get vanilla N -gram rules derived from the suffix of C. When σ consists of ± symbols, we get vanilla N -gram rules derived from subsets of C. Varying the length and the entries of σ yields the following rulesets 9 :EQUATIONThe parameter M controls how much of the context is being used for the rules. 6 We use * (i.e. glob notation) instead of the standard . symbol for readability purposes. 7 The empty regular expression does nothing under concatenation and does not contribute to the length of the resulting sequence. 8 For σ = ∅, we define Rσ to be the unigram distribution. 9 There is some redundancy among the σ's in terms of the rules they determine: for instance, in between any two + consecutive symbols, permuting the order ofand * will determine the same rule. Also in practice, we can assume the first entry of σ is a + since marginalizing the first token is equivalent to reducing the context length. From this, it follows that the number of distinct rules in R all M is 2, 5, 13, 34, 89, 233, 378, for M = 1, . . . , 7, respectively.Table 1 : Terminology associated to a context C. Here R is some reference ruleset under consideration. The superscript on p (i) (t|C) is meant to denote the predictions of the ith model. In Section 5, we consider rules that are fixed across model runs (where we have five models) whereas elsewhere we will only have a single model (and thus optimal rules will be model specific).optimal rule distance: the minimum (possibly averaged over runs) distance between LLM predictions and rule predictionsmin r∈R avg i d(p (i) (t|C), p r (t|C))optimal rule: a rule achieving the optimal distance argmin r∈R avg i d(p (i) (t|C), p r (t|C)) model variance: the average of the pairwise distance between LLM predictive distributions over different runsavg i,j distinct runs d(p (i) (t|C), p (j) (t|C)) 
approximating transformer predictions with rules: 
 Let p(t|C) denote the next-token distribution of an LLM conditioned on the context C and for notational similarly, write p r (t|C) for r(t|C), where r is one of the rules defined in Section 4. We wish to measure how similar these distributions are (higher similarity corresponds to a better rule description). To that end, we use the variational distance to measure the difference of two distributions (we discuss our choice and others in the Appendix):EQUATIONwhere the summation is over the vocabulary index (i.e. the components of the probability vectors).Since variational distance may be lacking in concrete interpretability, we will sometimes use top1accuracy to measure similarity, defined byEQUATION(in general, the argmax of a probability distribution is a set due to potential ties among maximal probabilities). When the argmaxes in (11) are singletons, top1-accuracy just measures agreement between greedy predictions.Given a context C, we want to understand how d(p(t|C), p r (t|C)) varies with different rules r and in particular if it can be made small. To that end, we introduce some terminology:We are interested in determining the optimal rule p r (t|C) (as defined in Table 1 ) and if it has small optimal rule distance then we regard the rule as being a good description of the corresponding transformer predictions. 10 As a first step, note there is a distinguished ruleEQUATIONwhose rule context is the full unmodified context C. 11 This is because (roughly) the languagemodeling objective aims to make p(t|C) similar to p full (t|C). 12 All other rules in our rulesets are "subleading" in that they drop or marginalize over tokens in the context C. Our goal is to quantify which rules, either (12) or subleading ones, are optimal rules and what their optimal rule distances are.One of our main findings is an approximation criterion: contexts that have low model-variance tend to have low optimal rule distance. In particular, this includes contexts with sufficiently high frequency in the training data. The latter situation is to be expected: the more often a context C occurs in the training data, the more the minimization of the cross entropy loss objective encourages the network to make predictions close to p full (t|C).The novel aspect of our approximation criterion is the sufficiency of low model-variance situation even in cases when the context is rare. 13 We present the case of 7-gram contexts in Figure 2 to corroborate the approximation criterion, with additional examples relegated to the Appendix. We sample around six-thousand 7-grams from the training data, sampling from logarithmically spaced buckets based on counts, and plot various relations between counts, model variances, and rule distances. For simplicitly, we consider the ruleset R = R suffix 7to limit the number of rules under consideration. Our analysis of Figure 2 can be summarized as follows:Plot (a) shows how with increasing count of the number occurrences of the context C in the training data, LLM predictions become nearer to p full (t|C), which in this case, is the vanilla 8-gram rule. Nevertheless, for all but the highest of counts, we have a large spread of distances: even for unique 7-gram contexts, some predictions are well-approximated by p full (t|C) while others are close to having disjoint-support (distance equal to 1). Plot (c) also shows that while model variance decreases with count of the context (as expected) we have a large spread of model variances for contexts with intermediate or low counts. Since the contexts whose predictions have high model variance can be regarded as "noise", one can ask whether those contexts with low model variance have some structure. Plots (b) and (c) address this question. While for (b), we see that the 8gram-rule has a large spread when plotted against model variance, there is a significant reduction in outliers in (d) when the y-axis is the optimal distance to rules in R suffix. Concretely, the transition from (b) to (d) is a way of visualizing LLMs performing back-off, whereby LLMs rely on statistics from subsets of the context. Moreover, the lower left portion of (d) is a manifestation of our approximation criterion: contexts that yield consistent predictions across model runs (i.e. sufficiently low model variance) are indicative of rule-like behavior (in this case, good approximation with a suffix N -gram rule formed out of the context).We believe our approximation criterion and its corresponding analyses have significance beyond the experiments carried out here since they (i) highlight that naive count-based statistics do not provide the strongest signal in terms of how LLMs leverage dataset statistics (since as Figure 2 (a) shows, high count can still have high model variance) (ii) suggest that LLM predictions that have low-variance are likely the ones that are amenable to description (or even explanation) by some underlying dataset statistic (with high-variance predictions being regarded as noise). We leave a more systematic exploration of (ii) to future work.6 Learning Dynamics 
curriculum learning: 
 We can track how well LLM predictions are described by our N -gram rules over the course of training by tracking optimal rule distance as a function of train step. Here optimal rule distance is defined as in Table 1 with R any of the rulesets ( 7)-( 9), and we will measure how optimal rule distances vary with maximum context length M (the resulting analyses are similar for "all", "subgram", and "suffix" rules so we show our analysis for "all"). Figure 3 summarizes our results. Early in training, LLM predictions acquire structure and thus become approximable by rule predictors. However, with further training, LLM predictions eventually diverge from simpler rules (small context length) while continuing to increase in similarity with more complex rules (larger context length). Moreover, the rightmost plot of Figure 3 shows that top1-acc(p gt (t|C), p r (t|C)) increases over the course of training for optimal r ∈ R all M (for M > 1), where p gt is the ground-truth distribution regarded as a one-hot distribution, showing that the rule selection improves with time. Altogether, this shows that LLMs undergo a curriculum style learning, in which their predictions gradually move away from simpler rules to more complex and effective rules. . Model size: 160M.Our investigations of approximating LLMs with rules given by limited contexts naturally lead us to consider LLMs with limited context. The latter have predictive distributions given byEQUATION)where n is the maximum context length. In Figure 4 , we plot the loss of an LLM trained to overfit (train loss decreases while validation loss increases) along with its limited context versions for 1 ≤ n ≤ 7. For the limited context models with n > 1, we see that on both the train and validation set, the two respective loss curves track each other closely and both eventually go up. This suggests the following picture: an overfitting LLM is spending capacity to minimize train loss by memorizing the full context at the expense of using capacity to learn statistics of subcontext, i.e. the reduced context in (13). This manifests itself both during training (where subcontext arises from a subset of a larger memorized context) and during validation (where subcontext arises from the partial overlap between novel context and the train set).Our discovery suggests a simple and computationally inexpensive early stopping criterion: during training, evaluate the transformer on train data consisting of short contexts and when this quantity begins increasing, stop training. Significantly, this method involves no holdout set and is a training dataset intrinsic criterion. Left: Models reach their lowest distance to more complex rules later in training. For rules with four tokens of context or less, the variational distance eventually starts increasing later in training. For six and seven tokens of context, the variational distance continues to decrease. Center & Right: The optimal rule selected always has nonincreasing distance and nondecreasing top1-accuracy relative to the ground truth (interpreted as a one-hot distribution p gt ), despite distances to model predictions eventually increasing or plateauing for rules with less than six tokens of context. This shows that the optimal rule selection is improving with additional training even if the optimal rule distance with respect to model predictions is not improving. (One can imagine the rule predictions as a mesh in probability space, with LLM predictions navigating this space through training. The distance to the mesh may plateau but which rule is closest can continue to change.) Model size: 160M. We plot both train loss (solid lines) and validation loss (dashed lines) for the full transformer and limited context length transformers (the latter are marked with an "x" for emphasis) on TinyStories. Unlike the full transformer which overfits, those with limited context length have train and validation loss curves closely following each other. Model size: 1.4B.Question: Does the paper specify all the training and test details (e.g., data splits, hyperparameters, how they were chosen, type of optimizer, etc.) necessary to understand the results?Answer: [Yes]Justification: Yes, experimental settings are explained by dedicated sections in the main paper and appendix.Guidelines:• The answer NA means that the paper does not include experiments.• The experimental setting should be presented in the core of the paper to a level of detail that is necessary to appreciate the results and make sense of them. • The full details can be provided either with the code, in appendix, or as supplemental material. 
rule peformance: 
 Finally, addressing our main question from the introduction, we track how well our rulesets describe LLM predictions (in the sense of Section 5) as a whole at inference time. Here, the utility of our N -gram rules defined in Section 4 becomes apparent, since on a holdout set, there will be novel contexts and being able to drop or marginalize context tokens aid in being able to retrieve or aggregate corresponding training dataset statistics. In Table 2 , we show the average top1-accuracy between the optimal rule from our various rulesets and LLM predictions on 100 random stories from the validation set. Here, we include as baseline backoff M , the single rule given by the predictive model which performs "stupid backoff" [4] using M tokens of context. 14 We see significant gains in accuracy at large M when adding additional types of rules. In the end, we are able to obtain 78% top1-accuracy between the per-prediction optimal rule and the LLM predictions, averaged over all tokens. This is perhaps a remarkably high figure, considering that the top1 accuracy of the model with respect to the ground truth on the validation set is 69.6%. At minimum, we have provided a precise quantification of structure in LLM next-token predictions: they are often matched (as measured by top token prediction) by some simple N -gram rule derived from The above is a sequence from a heldout story. In the second and third columns are the ground truth, token by token, along with the rule context (as defined in Section 4) associated to the optimal rule from R all 7 . The heatmap indicates the variational distance between optimal rule and LLM next token distributions at the given token. The first column shows at most two tokens, which are chosen as follows: If the LLM top-1 prediction disagrees with the ground truth, the LLM prediction is shown. If in addition, the rule selected makes a different top-1 prediction from the transformer, that token is shown as the second token and the corresponding ground truth token is colored red. Thus red tokens are precisely the locations of disagreement between LLM and optimal rule greedy predictions. The last column shows the number of contexts supporting the optimal rule. Model size: 160M.the training data. See Section D.1 for some supplementary analysis. Using the L ∞ distance instead of the variational distance gives us a slightly higher result of 79%, see Table 5 .To ground our rule optimization procedure, we provide Figure 5 which shows side-by-side how LLM predictions compare with ground truth and optimal rule predictions in an example heldout story.Table 2 : Top-1 accuracy of optimal rule. We look at the average top1-accuracy of the optimal rule versus LLM predictions for rules of varying strength and maximum rule context length M . We compute this average over each token prediction from 100 random validation stories ( For instance, for the target token "climb" in "... Roxy loved to climb", both the LLM and optimal rule R α predict "play", where α = ". * loved to". For target token "climb" in "... She climbed", the LLM predicts "would" whereas the ground truth and R α predict "climb", where α = "loved to climb * She". In general, optimal rules provide the closest statistical match from the training data to the given LLM predictive distributions (from amongst our rulesets), and their top1-predictions can agree or disagree agree (as indicated by target token color). Additional examples, including those from Wikipedia, are shown in Section D. For interpretability purposes, we re-emphasize that our optimal rules currently only provide descriptions, not explanations. We leave the possibility of the latter for future work.Question: Does the paper report error bars suitably and correctly defined or other appropriate information about the statistical significance of the experiments? Guidelines:• The answer NA means that the paper does not include experiments.• The authors should answer "Yes" if the results are accompanied by error bars, confidence intervals, or statistical significance tests, at least for the experiments that support the main claims of the paper. • The factors of variability that the error bars are capturing should be clearly stated (for example, train/test split, initialization, random drawing of some parameter, or overall run with given experimental conditions).• The method for calculating the error bars should be explained (closed form formula, call to a library function, bootstrap, etc.) • The assumptions made should be given (e.g., Normally distributed errors).• It should be clear whether the error bar is the standard deviation or the standard error of the mean. • It is OK to report 1-sigma error bars, but one should state it. The authors should preferably report a 2-sigma error bar than state that they have a 96% CI, if the hypothesis of Normality of errors is not verified. • For asymmetric distributions, the authors should be careful not to show in tables or figures symmetric error bars that would yield results that are out of range (e.g. negative error rates). • If error bars are reported in tables or plots, The authors should explain in the text how they were calculated and reference the corresponding figures or tables in the text. 
conclusions and limitations: 
 Our work provides quantitative measures of how well the predictions of transformer-based LLMs are described (i.e. approximated) by simple N -gram rules. Such rules were motivated by the simplest token-level operations applied to the context (keep, ignore, or marginalize). The results we obtained in Section 7 imply that, at least on simple datasets like TinyStories and Wikipedia, LLM predictions contain much quantifiable structure insofar that they often can be described in terms of our simple statistical rules. Along the way, we also obtained novel discoveries into the statistical nature of overfitting, the occurrence of curriculum learning, and the relation between model-variance and approximability by N -gram rules. Altogether then, our work provides various avenues of progress in understanding how simple dataset statistics are reflected in LLM behavior.On the other hand, it is intuitively clear that current state-of-the-art LLMs go well beyond invoking N -gram rules. A typical request to perform a nontrivial task (e.g. "Write a thirty line poem about mathematics that rhymes") requires a high-level conceptual understanding of language that goes beyond simple literal token-level associations between the context and the training data that we consider here. Nevertheless, one can speculate that an analogue of our work could still apply: in general, an LLM might be performing some high-level rule application, whereby statistics formed out of distributional categories [24] instead of individual tokens are leveraged from the context. Formulating a correct and parsimonious set of rules, if it is at all possible, would be a nontrivial challenge to overcome and one which we leave to future work. Addressing such a challenge and being able to promote the descriptive approximations provided here to explanatory ones would provide a next step towards understanding how LLMs work.Question: For each experiment, does the paper provide sufficient information on the computer resources (type of compute workers, memory, time of execution) needed to reproduce the experiments?Answer: [Yes] Justification: Explained in Appendix.Guidelines:• The answer NA means that the paper does not include experiments.• The paper should indicate the type of compute workers CPU or GPU, internal cluster, or cloud provider, including relevant memory and storage. • The paper should provide the amount of compute required for each of the individual experimental runs as well as estimate the total compute. • The paper should disclose whether the full research project required more compute than the experiments reported in the paper (e.g., preliminary or failed experiments that didn't make it into the paper). 
code of ethics: 
 Question: Does the research conducted in the paper conform, in every respect, with the NeurIPS Code of Ethics https://neurips.cc/public/EthicsGuidelines?Answer: [Yes] Justification: Our experiments use small, public datasets and involve no sensitive material or topics.Guidelines:• The answer NA means that the authors have not reviewed the NeurIPS Code of Ethics.• If the authors answer No, they should explain the special circumstances that require a deviation from the Code of Ethics. • The authors should make sure to preserve anonymity (e.g., if there is a special consideration due to laws or regulations in their jurisdiction). 
broader impacts: 
 Question: Does the paper discuss both potential positive societal impacts and negative societal impacts of the work performed?Answer: [Yes]Justification: We include a brief discussion in the Appendix of how our work contains no direct societal impacts.Guidelines:• The answer NA means that there is no societal impact of the work performed.• If the authors answer NA or No, they should explain why their work has no societal impact or why the paper does not address societal impact.• Examples of negative societal impacts include potential malicious or unintended uses (e.g., disinformation, generating fake profiles, surveillance), fairness considerations (e.g., deployment of technologies that could make decisions that unfairly impact specific groups), privacy considerations, and security considerations. • The conference expects that many papers will be foundational research and not tied to particular applications, let alone deployments. However, if there is a direct path to any negative applications, the authors should point it out. For example, it is legitimate to point out that an improvement in the quality of generative models could be used to generate deepfakes for disinformation. On the other hand, it is not needed to point out that a generic algorithm for optimizing neural networks could enable people to train models that generate Deepfakes faster. • The authors should consider possible harms that could arise when the technology is being used as intended and functioning correctly, harms that could arise when the technology is being used as intended but gives incorrect results, and harms following from (intentional or unintentional) misuse of the technology. • If there are negative societal impacts, the authors could also discuss possible mitigation strategies (e.g., gated release of models, providing defenses in addition to attacks, mechanisms for monitoring misuse, mechanisms to monitor how a system learns from feedback over time, improving the efficiency and accessibility of ML). 
safeguards: 
 Question: Does the paper describe safeguards that have been put in place for responsible release of data or models that have a high risk for misuse (e.g., pretrained language models, image generators, or scraped datasets)? Answer: [NA] Justification: This paper poses no risks. Guidelines:• The answer NA means that the paper poses no such risks.• Released models that have a high risk for misuse or dual-use should be released with necessary safeguards to allow for controlled use of the model, for example by requiring that users adhere to usage guidelines or restrictions to access the model or implementing safety filters. • Datasets that have been scraped from the Internet could pose safety risks. The authors should describe how they avoided releasing unsafe images. • We recognize that providing effective safeguards is challenging, and many papers do not require this, but we encourage authors to take this into account and make a best faith effort. 12. Licenses for existing assets Question: Are the creators or original owners of assets (e.g., code, data, models), used in the paper, properly credited and are the license and terms of use explicitly mentioned and properly respected? Answer: [Yes] Justification: Yes, datasets used are referenced. Guidelines:• The answer NA means that the paper does not use existing assets.• The authors should cite the original paper that produced the code package or dataset.• The authors should state which version of the asset is used and, if possible, include a URL. • The name of the license (e.g., CC-BY 4.0) should be included for each asset.• For scraped data from a particular source (e.g., website), the copyright and terms of service of that source should be provided. • If assets are released, the license, copyright information, and terms of use in the package should be provided. For popular datasets, paperswithcode.com/datasets has curated licenses for some datasets. Their licensing guide can help determine the license of a dataset. 
 
 Appendix: We choose variational distance since it is a symmetric and bounded distance function (unlike the KL divergence). Symmetry means we do not have to make a choice between computing the distance between model predictions and rule predictions or vice versa. Boundedness ensures that when we measure average distance across tokens, large outliers do not dominate the average. In fact, for the KL divergence, since KL(p||q) is infinite when p > 0 whenever q = 0, were we to use KL divergence, we would have to set p equal to rule predictions and q equal to model predictions (since rule predictions are typically sparse). To avoid such constraints and potential pathologies, we choose the variational distance. Another possible choice is the Jensen-Shannon distance, but we found it gives similar results to variational distance.It is worth noting that while theEQUATIONoften gives slightly better results for the rule-approximation analysis of Section 7, it has a failure mode when comparing two very high entropy distributions. If p and q are two distributions such that p α and q α are all small, then their L ∞ distance will be small even though their variational distance can be large. Thus, the L ∞ distance is not suitable for the curriculum learning analysis analysis in Section 6.1, since at initialization when the model makes uniform predictions on tokens, it will have low L ∞ distance with many bad N -gram rules that are high entropy. Hence, for the sake of using a consistent metric in the main body of the paper, we use the variational distance when comparing probability distributions, although as the numbers of Section D show, for well-trained models the L ∞ distance often yields better rule approximation.Our transformer architecture and training procedure is based on that of Chinchilla [14]. The architecture hyperparameters are as follows: We use a linear learning rate warmup of 1000 steps up to a maximum value of 2 × 10 -4 and then use a cosine learning rate decay. We use weighted Adam optimizer [20] with weight decay 10 -4 . Our models are trained using TPU accelerators. The 160M and 420M models use 16 TPU accelerators while the 1.4B models use 64 TPU accelerators per run. We use a batch size of 128 sequences with each sequence consisting of 2048 tokens.Our training datasets (TinyStories and MassiveText Wikipedia) are prepared as follows. After tokenizing the individual documents (stories for TinyStories and articles for Wikipedia), we concatenate them all into one long sequence, with each document separated by the BOS token 15 . The full sequence is then subdivided into contiguous sequences of length 2048 (with padding as needed) and then shuffled to form a static dataset of shuffled sequences. We refer to the previous procedure as "chunking". Crucially, observe that chunking results in most sequences not starting with the BOS token (hence a model will be trained to predict the next token conditioned on incomplete contexts, as desired).For TinyStories experiments, we train 160M models for 4 epochs except for the overfitting experiments in Section 6.2 where we train 1.4B models for 10 epochs. We use the train and validation splits provided by HuggingFace 16 . For Wikipedia experiments, we train a 1.4B model for a single epoch.We have train and validation splits based on using choosing random sets of disjoint documents. Our Wikipedia train set has 4.4B tokens. In places where we perform several training runs (Section 5), the only source of variance (randomness) among the runs are different dataset shuffles. The only exception to the above is in Section D. 3, where all model sizes are trained for 1 epoch (for TinyStories, we observed overfitting of the 1.4B model around 4 epochs so we switch to 1 epoch for all model sizes for a fair comparison).Our tokenizer 17 uses byte-pair encoding trained on MassiveText with a vocabulary size of 32,678.The computation of N -gram statistics of the training data is formed after chunking (as described above), so that they correspond to the N -gram statistics seen by models during training. In particular, tokens which are contiguous in a story but separated by the chunking will not contribute to the N -gram statistics. We used a distributed map-reduce system to tabulate N -gram counts in the most naive manner. Using sliding windows of size N and aggregating across train documents, we are able to compute N -gram counts for all occurring N -grams and store them in SQL databases. (We ignore those invalid N -grams where BOS occurs not as the first token). Note that the number of rows of such N -gram databases is bounded by at most the size of the training corpus times N .As an aside, we note that for the analysis in Section 6.1, we used our static N -gram rules computed from the entire training data. We do not compute statistics based on the training dataset seen up to the point in training. However, for the purposes of our analysis, this distinction is immaterial (and in practice, the distinction between two sets of statistics will, for the dominant N -grams, be small with sufficiently large batch size).We provide additional commentary and experimental settings for our analysis in Section 5.As noted in footnote 12, there is usually a mismatch between the contexts that N -gram rules and LLMs receive during training: the latter can receive very long contexts (up to one less than the number of tokens in a document) while the former typically receives very short contexts (in our case, up to 7 tokens). Concretely, while a bigram model is trained on consecutive pairs of tokens (c, t), an LLM is rarely trained so as to optimize p(t|c). Indeed, given a training sequence x, only the target for the first token of x has context consisting of a single token; the other targets will have more tokens of context accordingly. Thus, it is unclear how well LLM predictions p(t|c) should match bigram rule predictions as c varies over the vocabulary set, since LLMs almost always receive c within a much larger context. More generally, it is unclear how well p(t|C) matches p full (t|C). Nevertheless, because in practice LLMs learn how to use context effectively, LLMs manage to learn p(t|C) despite being optimized for p(t| C) with C a context containing C as a suffix.As a measure of how much training context "dilutes" the LLM ability to learn the bigram distribution, in Figure 6 we plot the distance between LLM predictions and the bigram rule for two LLMs: one trained in the usual fashion with full context and one trained with only one token of context (concretely, a token can only attend to itself in attention layers). In both cases, we have the same pattern of increased count leads to lower rule distance. However, the transformer trained with context length equal to one has much lower distances since it cannot learn anything else other than the bigram rule. The difference between the variational differences of the two models is thus a measure of the dilution an LLM has in learning a bigram rule owing to receiving surrounding context.As an aside, we note how for both models, a context with low count has difficulty being learned. In this way, one can regard the inability to learn rules for low count contexts as being due to a failure of optimization, something that could be addressed in the future by improved optimization methods. We repeat Figure 2 for the simplest case of unigram context. In this case, there is only one rule (the bigram rule) and so there are only three plots to consider. Next, consider the case when there are two tokens of context. To get a more fine-grained analysis, we consider the case of full-context bigrams, i.e. those starting with the BOS token. This is because such bigrams do not appear within a larger context and so a transformer's corresponding predictions are more fair to compare with those of N -gram models (both are trained using equal contexts). Conveniently, there are only 691 full-context bigrams in this case and so we do not have to randomly sample a subset.We will consider the ruleset R all 2 for which there are three relevant N -gram rules of interest: one which uses the entire bigram of context (a trigram model), one which uses only the last token (a bigram model), and one which uses only the first token (the next token distribution of BOS ). 18 We will refer to these as the trigram, bigram, and BOS rule respectively.We plot an analog of Figure 2 for full-context bigrams in Figure 8 . As with the analysis for Figure 2 (a), a large count leads to good approximation with p full (t|C), which is the vanilla trigram rule at present. However lower counts lead to a spread in approximability (some low counts have high error while others have low ones). In (c), we plot a variation in which the x-axis is the maximum of the count of C and the unigram C -1 . What the poor fit in (c) indicates is that whether a prediction is well-described by a rule is not a simply determined by whether a subcontext of C occurs often. Given the small number of rules, we now color code the optimal rule of each full-context bigram (as indicated by the legend in (b)). In passing from (b) to (d), we see how the outliers in the upper left of (b) move towards the bottom once the large distance from the trigram model is replaced with the optimal rule distance. These are bigrams whose rules are well approximated by bigram or BOS rules and are misspecified when trying to be approximated by the trigram rule. In accord with our Approximation Criterion, contexts with low model variance are well approximated by N -gram rules (the lower left of (d)).We plot the analog of Figure 2 in Figure 9 but for contexts consisting of 6-grams from Wikipedia. We also subsample as before, from logarithmically spaced buckets, for a total of around 6.8K total contexts. We get nearly identical behavior as with TinyStories. Our Approximation Criterion is thus not specific to small datasets like TinyStories. We supplement Table 2 with Table 4 to show how optimal rule distances decrease with increasing rule strength. This is to preclude a trivial situation in which by having sufficiently many rules (say a one-hot distribution for every vocabulary token), one can have a ruleset that for any model prediction always returns an optimal rule with 100% top-1 accuracy! Such coarse rules will not in general yield small optimal distances however 19 and our variational distances decreasing in Table 4 shows that our rulesets are truly better approximating the predictions with increasing strength.We also include the analog of Tables 2 and (4 but with the variational distance replaced with the L ∞ distance in Tables 5 and 6 . We see that in fact the top-1 accuracy numbers are slightly better in this case.We present analogous results for Section 7 using a 1.4B model trained on Wikipedia. In Table 7 we present the analogue of Table 2 on ten holdout Wikipedia chunks (a total of 10 × 2048 tokens). The top-1 accuracy when using optimal rules from R all 7 and the L ∞ distance for rule selection is 67.7%. As with TinyStories, we see significant gains in accuracy when we increase rule strength. Achieving the number 67.7% (versus the corresponding 78.9% number for TinyStories from Table 5 ), perhaps a surprisingly a high score, is the result of two competing factors: on the one-hand, Wikipedia is a more complex dataset (which makes prediction harder), while on the other hand, the training data has more N -grams and thus more rules. Our model achieves 54.9% top-1 accuracy on the 10 holdout Wikipedia chunks (Table 12 ) which is substantially lower than the top-1 accuracy of the optimal rule. Table 5 : Top-1 accuracy of optimal rule (TinyStories, L ∞ distance). The analogue of Table 2 but with L ∞ distance instead of variational distance for selecting the optimal rule. Model size: 160M. In this section, we present results about how our rule approximation changes with model size. For both TinyStories and Wikipedia, we train models of size 160M, 420M, and 1.4B for one epoch 20 .In Tables 11 and 12 , there is a clear trend towards improved model performance with scale: we obtain lower cross entropy loss, higher top-1 accuracy, and lower model distance to the ground truth distribution regarded as a one-hot distribution 21 . Note that for the latter, distance from model predictions to the ground truth distribution is the same with respect to the variational or L ∞ distance and is given by 1 -p where p is the probability assigned by the model to the ground truth.On the other hand, entries in Tables 13-20 measuring the changes in rule approximation with scale are much more modest (i.e. are more stable) by comparison. They also show mixed results, with L ∞ results worsening but some variational distance results slightly improving with scale (for large context length rules). We leave a more thorough investigation of how model scale affects approximability by N -gram rules to future work.Table 7 : Top-1 accuracy of optimal rule (Wikipedia, L ∞ distance). We look at the average top-1 accuracy between optimal rule and LLM predictions for rules of varying strength and maximum context length. We compute this average over each token prediction from 10 holdout Wikipedia sequences each consisting of 2048 tokens. Model size: 1.4B. We also ground our rule approximation on Wikipedia by providing two concrete examples in Figures 12 and 13 .ruleset / contextLarge language-models are having significant impacts on society, due to their use as question-answer tools and natural language generators. A better understanding of such language models will only serve to improve their capabilities. Our work here presents steps towards a fundamental understanding of language models, albeit in a small-scale regime far removed from those relevant for production systems. Given how far removed our work is from realistic datasets and use cases, we do not anticipate any direct negative broader impacts of our work.Justification: We do not release the code used to run our experiments (though there is nothing proprietary or novel about the model or the training procedure, and both are described in detail). The datasets we use are publicly available.Guidelines:• The answer NA means that paper does not include experiments requiring code. • Providing as much information as possible in supplemental material (appended to the paper) is recommended, but including URLs to data and code is permitted.38th Conference on Neural Information Processing Systems (NeurIPS 2024).It is important to emphasize that we seek a descriptive approximation of a transformer, rather than an explanatory one. A description merely requires that we can provide a post-hoc, per-instance approximation of transformer predictions in terms of an available rule; an explanation means we provide reasons for and thus can predict in advance why and when a particular rule approximates transformer predictions. Hence, we make the distinction between form (description) and selection (explanation).Different runs have different dataset shuffles.https://github.com/google-deepmind/transformer_ngramsFor instance, the next token distribution for the context "... the tired dog" may be insensitive to replacing "tired" with "brown" or "furry". Statistics which thus marginalize over all extant substitutions for "tired" yield a crude but generally applicable way of capturing semantic invariance. One can imagine an attention mechanism for which there is a many-to-one mapping of keys to a particular value that might implement semantic invariance.Our regular expressions operate on tokens not string characters, since our contexts are formed out of sequences of tokens.In practice, we will only have one model available and our optimal rules are computed per-context and per-model. In this section, we have available five models from five runs for use in computing optimal quantities.That is, pfull(t|C) is the invokation of the rule corresponding to σ = + • • • + ∈ R suffix |C| applied to C.See Section C for additional discussion.Necessity is a given. Predictions which have high variance cannot be well approximated by a single model-independent rule. We use five runs in our analysis here since approximation by a rule that remains fixed across models yields a fortiori approximation by a per-model rule.That is, pbackoff M (t|C) = pfull(t|C -k • • • C-1)where k ≤ M is the largest value for which C -k • • • C-1 occurs in the training data.Attention masks are used so that tokens only attend to those from the same documentAvailable at https://huggingface.co/datasets/roneneldan/TinyStoriesTrained using https://github.com/google/sentencepieceIt turns out that the BOS * rule (given by R+ * ) in R all 2 never occurs as an optimal rule for full-context bigrams and so can be ignored in this example.Both the variational and L ∞ distances between a one-hot distribution and a distribution which is uniform on n tokens are at least n-1 n . Thus, whenever an LLM has at least two roughly valid options, we expect a one-hot distribution to be at least of distance 0.5 from the LLM prediction.Since the 1.4B starts showing signs of overfitting around 4 epochs on TinyStories, we train models for 1 epoch in this section unlike 4 epochs elsewhere.It would be more proper to aggregate statistics over the holdout set to compute a ground truth distribution that takes into the account the relative frequencies of the next token given the context. However, since most contexts will be unique, this more refined computation will not affect the corresponding result much. 


Decision: SUMMARY

How well do n-gram rules from statistical language models approximate the predictions of transformer-based neural language models when they are built/trained off the same dataset? The paper shows that high-confidence LLM predictions tend to be well-approximated by n-gram rules and that LLMs learn simple n-gram rules before they learn more complex ones. They further use their methods to detect when an LLM has overfitted to the training data.

REASONS TO ACCEPT

Reviewers really like how the authors use classical methods from NLP  to try and understand modern LLMs' behaviours. The results are intriguing, and there are natural extensions for impactful future work. 

REASONS TO REJECT

The "LLM" used by the paper is actually tiny: 160M parameters. It is unclear whether the results will be the same/different if the methods were evaluated on a much larger language model trained on a much larger dataset. It is also unclear how the methods in the paper could be efficiently scaled up to this more realistic "large" setting.

CONCLUSION

Overall, the ideas in this paper are worth sharing at NeurIPS, and I look forward to future work which addresses the scaling challenge.

Reviews: review: paper_summary: paper_summary: The authors use 160M parameter models trained on the TinyStories dataset (artificially generated short stories, 480M tokens, made up of "vocabulary consisting of about 1500 basic words") to study transformers by comparing their predictions to the predictions of n-gram models. 

This leads to a few observations [quoted from the paper here]: 
1. (Approximation-Variance Tradeoff) We observe an “approximation-variance tradeoff",
which roughly states that next token LLM predictions that have low variance (across
different training runs) tend to be well-approximated by N-gram rules. (Section 5)
2. (Curriculum Learning Dynamics) By grouping our N-gram rulesets in terms of complexity
(as measured by the amount of context they use), we discover the various ways in which the
learning dynamics of LLMs implement a statistical type of curriculum learning, in which
easier rules are eventually supplanted by more complex ones. (Section 6.1)
3. (Overfitting Criterion) Based on our analysis of approximating LLM predictions by N-gram
rules, we propose a simple and novel procedure for detecting overfitting of LLMs during
training. The procedure makes no use of holdout data and it makes quantatively precise the
intuition that overfitting corresponds to a model memorizing long context at the expense
being able to generalize through making use of subcontext. (Section 6.2)
4. (Approximation Strength) We study how well LLM predictions can be approximated by our
N-gram rulesets, noting that significant gains in top1-accuracy occur as we increase ruleset
complexity and diversity. We also visually ground these approximations with concrete
examples (Figure 5), which may form the basis for dataset attribution methods in future
work. (Section 7)
strength_weakness: strength_weakness: There's a huge weakness in this paper- they analyze extremely small (160M param) models trained on a total toy dataset (TinyStories). TinyStories is a very small dataset made up of short stories that were generated by an LM. The vocabulary in this dataset is limited to 1.5k basic words. 

All of these things together mean that none of these results might transfer towards bigger, realistic LMs like LLaMA 3 70B. If this paper would have been written with LLaMA 3 70B as the model being used I would have argued for a strong accept, but because the models used here are so tiny I'm less excited about this contribution. 

Second thing- the authors put out a lot of what seems like 'intermediate analysis'- observations they noticed, but they don't explain what the conclusion from that observation is or why it's interesting. For example fig 2. 

Third- why is the 'Overfitting Criterion' interesting? Is anyone overfitting their LMs? Would anyone need this in practice?
questions: questions: 1. is the Approximation-Variance Tradeoff true also for predictions that have low entropy?
limitations: limitations: n/a
paper_summary: paper_summary: The authors use n-gram statistics and regular expression templates to study how well they describe the predictions of Transformers-based models. They craft rules that vary in context length and/or the number of marginalised context variables to predict the next word. They use their framework to study overfitting (and memorisation) of increasingly complex template rules. They discover a counter-intuitive phenomenon: longer n-gram rules can be less predictive of a model's behaviour than shorter; an insight they name model-variance trade-off.
strength_weakness: strength_weakness: I am concerned about the evaluation, in particular Eq. 10. You measure how closely the dataset adheres to the template rules and compare it to your model’s behaviour. With such a small dataset, the fact 7-gram rules better approximate the distribution of data may be caused by a considerable drop in the overall frequency (and thus, variance) of 8-grams (vs. 7-grams). See a question about that.
In summary, my biggest concern is whether the best-rule is identified by the model-variance trade-off or the intrinsic larger variance of 8- vs. 7-gram rules (i.e., 8-grams are more difficult to predict because you don't have enough data, so the 7-gram is optimal). With larger datasets and different models, results can vary.

In fact, another major concern is that you only have two datasets and one model to prove your hypothesis.
Furthermore, it is not clear if you take inspiration from Chinchilla's architecture (it seems to me you do not use a pre-trained model). Otherwise, it would be nice to test this hypothesis with smaller, purely next-word-prediction trained models (even gpt-2 or Pythia would be good).

Other concerns (in descending order of importance):
Figure 2: low R-squared may mean the regression failed and not lack of "correlation". Furthermore, you mention 7-grams but some plots are for 8grams (see y-axis of figs (a,b)). While I understand why, the plot is named 7-grams, so I was a bit confused at the beginning. It's better to show less in this case or make it clear also in the caption that the top-plots refer to 8grams.

(minor) Equation 10 seems to me wrong: p and q are distributions, you can’t subtract them (unless i stands for p(t=v_i |C), but that has to be clarified).
If not, probably you want to say something like Divergence(p || q). On a side note, I think this is one of the cases where an asymmetric rule makes sense. You want to measure the amount of “information” a model lacks to turn p (its prediction) into q (the ground truth).

(minor) I am a bit confused by the notation in Section 4 (see questions, though the general idea is clear enough).
questions: questions: In order of importance:
(major) Can you give a clear definition of model-variance in terms of predictive capabilities of the model and when compared to an n-gram rule?

(major) Have you checked if there is a large drop in the variance of 7 vs. 8 grams in your dataset? I suspect that causes the 7-gram rules to be optimal and not the model-variance trade-off. In other words, the variance of 8-grams in your dataset is so large (because you don't have enough data), that the architecture you use cannot approximate it.

(minor) What if the optimal rule you find only correlates with a model's behaviour (e.g., due to the size of the dataset)? Can you give some evidence that a model is actually using n-gram rules to predict the next token?

(minor) Eq. 10: what is i? Is p(t=v_i | C), with v_i the i-th token in the vocabulary, or the i-th run of the model?

(minor) Line 111, the expression +-*+ should produce C_{-5}*C_{-1} and not C_{-4}*C_{-1}, or am I missing something in your notation? Is it for the left padding you mention earlier?

(minor) Eq. 6 (left hand side): why don’t you have C_{-4} at the denominator?
limitations: limitations: See previous points.
paper_summary: paper_summary: The paper studies how transformer-based large language models (LLMs) use context when predicting the next token by approximating these predictions with N-gram-based statistical rules. The authors propose a method to describe transformer predictions using simple N-gram rules and study how well these rules approximate the predictions. They claim their key findings include a new method to detect overfitting without a holdout set, insights into the progression from simple to complex statistical rules during training, a criterion for when transformer predictions align with N-gram rules, and an understanding of how well transformers can be approximated by increasingly complex N-gram rulesets. The experiments (primarily carried out on the TinyStories dataset and validated on Wikipedia data) seem provide possible insights into the statistical nature of LLM behavior.
strength_weakness: strength_weakness: - The study provides descriptive approximations without offering explanations into why certain rules work, not going deep enough in understanding the transformer behavior.
- The paper doesn't properly explore how fine-tuning on different datasets might affect the effectiveness of the proposed methods.
- The study mainly considers context lengths of up to seven tokens, which may not fully capture the long-range dependencies that transformers are capable of handling.
questions: questions: - How do you plan to address the computational complexity associated with selecting the optimal N-gram rule for each context?
- Do you have any plans to transition from descriptive approximations to more explanatory models that can predict why certain rules work?
- Have you considered additional evaluation metrics that might capture other aspects of model performance and approximation quality?
limitations: limitations: - The computational overhead required to apply and test the N-gram rule sets at inference time could be significant.
- The proposed methods might not easily adapt to new or evolving datasets without substantial re-calibration or re-training, limiting their long-term applicability in dynamic environments
- While N-gram rules provide a way to approximate transformer behavior, the results might not always be easily interpretable by humans.

Comments: title: Reviewer, please respond to authors' rebuttal
Reviewer, please respond to authors' rebuttal
Thank you for your response.
comment: changed my score to 7.

regarding the comment about llama 3.1: you're right, i understand now why you cant show results on that (you don't have the train set).

regarding the 2 tables with experiments on 420M and 1B param models:  that looks great, please add it to the paper.
Hello Reviewer,

Please take a moment to read and acknowledge the authors' rebuttal. Especially considering you gave a "borderline" review score, it would be helpful if you could weigh in on whether their response pushes you one direction or the other. 

Thanks,

AC
Hello reviewer,

Please take a moment to read and acknowledge the authors' response.

Thanks,

AC
I agree that N-gram models are inherently simple and interpretable due to their reliance on frequency-based statistics; however, my concern is that while individual N-grams are indeed easy to understand, the challenge arises when these N-grams are aggregated and interact within a complex model like a transformer. 
Anyway, I appreciate the time you spent writing this respose.