1. Two-Layer Transformer Formulation with Residuals

A two-layer Transformer (encoder) can be defined with two self-attention sublayers and one feed-forward network (FFN) sublayer, including residual skip-connections around each. Let be the input sequence embeddings (length , hidden size ). The computations are as follows:

The final output is the two-layer Transformer’s output. Each attention layer allows tokens to incorporate information from other positions, while the FFN injects non-linear feature transformations at each position (One Wide Feedforward is All You Need - Apple Machine Learning Research). Residual skips ensure the input information is preserved and ease optimization (Transformer (deep learning architecture) - Wikipedia).

2. Mapping to the Matrix Earley Algorithm Steps

We can interpret each Transformer component as performing an analogous operation to one of the Earley parsing steps (Predict, Scan, Complete) in matrix form. In Earley’s algorithm (matrix view), chart states are organized by positions, and the parser repeatedly predicts new expectations, scans terminals, and completes constituents by combining states () (). The two attention layers and one FFN naturally align with these steps:

  • Predict: The FFN sublayer at each position can generate predicted grammar rule states at that same position. This corresponds to Earley’s Predict step, where for any state expecting a nonterminal at position , the parser adds new states for each production of beginning at (). The FFN can be seen as a learned rule-expansion function: given a context indicating “expecting ”, it outputs a representation of ’s possible expansion(s). (Notably, feed-forward layers can learn to encode a static key→value map from a symbol to a template of its expansion (A Mechanism for Solving Relational Tasks in Transformer Language Models | OpenReview), analogous to retrieving all rules of and adding them at .) After the first layer’s FFN, each position ’s state now includes any predicted sub-structures that should start at (with the “dot” at beginning of those rules), implementing Earley’s predict operation.
  • Scan: The first layer’s self-attention can handle Earley’s Scan step, which advances states when the next expected token matches the input. In Earley parsing, if a state at position expects terminal and the input at position (current token) is , then that state moves to the next position (). Self-attention allows each position to attend to position , effectively copying forward any state that was expecting the token at (if the content matches). A specific attention head can learn to focus on the immediately preceding token position (relative position ) and carry over the relevant portion of the state representation. Concretely, the query at can encode the observed token type, and keys at encode expected token types; a high attention weight results if they match, so the value from (the state to advance) is passed to . This way, an incomplete state is transferred vertically down to the next position (), exactly as the Earley chart does in the Scan step (advancing the “dot” over a terminal). After the first attention layer, states that consumed a token at position will have been moved into position ’s representation.
  • Complete: The second layer’s self-attention can implement the Earley Complete step, which connects a finished constituent back to any waiting states that predicted it. In Earley’s algorithm, when a rule that began at position is fully parsed ending at position (i.e. is complete at with start ), the parser finds any earlier state in that was expecting and advances it, adding a new state in (). The transformer’s second attention layer can perform this by allowing position to attend to some earlier position (for all ) to retrieve any state that had pending. Specifically, the representation at (which now contains an encoded complete signal from layer 1) serves as a query, and positions (potential start positions) serve as keys that indicate “expecting ”. If and correspond to a matching prediction/completion (i.e. had a state expecting and has completed, with positional encodings indicating the span ), the attention mechanism will produce a large weight, pulling the value from position into position . That value could be (or include) the partial state from (e.g. X → α • A β at ) which, when added to ’s representation (via the residual connection), effectively creates the advanced state X → α A • β at . This completes the constituent and incorporates it into any larger rule that needed it, exactly as Earley completion adds new states ending at that originated from . In essence, multi-head attention performs a join operation between the set of completed constituents at and the set of awaiting nonterminals at earlier positions, fulfilling the Complete step (). After the second attention layer, each position ’s output should include all states that end at (including those completed via distant dependencies).

Summary: The transformer’s computations mirror the Earley algorithm’s chart updates: the FFN injects predicted grammar expansions in place (like Earley Predict), the first-layer attention shifts states along the sequence in sync with the input (like Scan from to ), and the second-layer attention integrates information across positions to handle dependencies (like Complete linking start to end ). All these operations occur in parallel across the sequence with learned weight matrices, effectively performing the parser’s dynamic programming in two forward passes of the network.

3. Role of the Second-Layer FFN (Is it Necessary?)

We consider whether the second layer needs its own feed-forward network or if attention alone suffices for the Earley-style computation. In general, multi-head attention and FFN play complementary roles in Transformers: attention links information across positions, while the FFN applies a non-linear transformation at each position (One Wide Feedforward is All You Need - Apple Machine Learning Research). Removing the second-layer FFN means the model’s final combining step (Complete) would rely purely on linear mixing of signals from the first layer. This has important implications:

  • Potential Sufficiency: The Complete step may be accomplished by attention alone because it primarily requires matching and summing two pieces of information (a predicted expectation from position i and a completed constituent at j). The dot-product attention is a content-addressable lookup that can selectively combine those pieces when the keys/queries align. In theory, a well-trained attention head can perform the necessary AND-like condition (both “expecting A at ” and “ completed at ” must be true) by giving a high weight only in that case, thereby bringing the correct value. The residual addition then linearly combines the retrieved value with ’s existing state, potentially encoding the newly completed item. If this linear combination is sufficient to represent the new state, the FFN in layer 2 might not be strictly needed for correctness. In fact, recent research has shown that many FFN layers can be removed or shared with minimal performance loss in sequence models; a single large FFN can often carry out the necessary transformations for multiple layers (One Wide Feedforward is All You Need - Apple Machine Learning Research). This suggests that a second FFN is somewhat redundant if the first-layer FFN already computed robust features and the attention can do the rest. Empirically, Pires et al. were able to remove decoder-layer FFNs and share one FFN across all encoder layers with only a modest drop in accuracy (One Wide Feedforward is All You Need - Apple Machine Learning Research), indicating that multi-layer attention can leverage a common feature-transformer. By analogy, our second layer could function with only attention, assuming the first layer’s FFN has introduced the essential nonlinear encodings (e.g. marking which symbol is expected or completed).
  • Potential Need for FFN: On the other hand, the FFN provides a nonlinear mixing and gating of signals that might be crucial for complex grammar logic. The Complete step effectively requires creating a new state representation (X → ... •) from two pieces of input (the previous incomplete state and the completed symbol). This might involve a transformation that is more than just a sum of the parts. Without an FFN, the combination produced by attention + residual is a linear combination of first-layer outputs. If the relationship is more complex (e.g. needing to recompute embeddings to mark the dot has advanced, or to merge features of and in the example above), a feed-forward layer with a nonlinearity (like ReLU) could be necessary to reconfigure features after the attention. The FFN can synthesize new features that weren’t present in either input alone, implementing the kind of conditional update (“if A completed and X was expecting A, produce new state”) that a purely linear operation might struggle with. In algorithmic terms, the FFN can act like a logic gate or transition function that solidifies the newly formed state. If the grammar or parsing task demands such complexity (e.g. distinguishing different ways a nonterminal could be completed or performing additional checks), the second-layer FFN would be important for the model to faithfully emulate the Earley algorithm.

Conclusion: It’s plausible that a second-layer FFN is not strictly necessary for a basic simulation of Earley parsing, given a powerful first layer and attention that correctly routes information. The attention can do the heavy lifting of combining states across time steps, and a single FFN (first layer) can inject all required rule information. This minimal design might still execute the algorithm, as supported by evidence that Transformers can compress much of their computation into one large FFN and use attention layers mainly for communication (One Wide Feedforward is All You Need - Apple Machine Learning Research). However, the second FFN likely helps the model handle more complex or non-linear aspects of the computation reliably. It can refine and separate merged information, ensuring that the final representations distinctly encode the completed parse states. Without it, the model might be more prone to errors or require more heads/hidden size to compensate. Thus, while the second layer can function with only attention, including an FFN provides extra capacity for implementing the algorithm’s conditional logic and may improve accuracy and generalization of the learned parser.

4. Empirical Verification Plan (Probing & Sparse Autoencoders)

To validate that our two-layer transformer indeed learns an Earley-like parsing process internally, we propose a series of interpretability experiments. The goal is to probe the model’s attention patterns and activations for evidence of the Predict/Scan/Complete mechanism, and to extract structured representations from its hidden states that correspond to Earley parser states. The plan consists of two complementary approaches:

4.1 Probing Attention and Activations

Design of Probes: We will use probing methods to test whether the transformer’s hidden states encode interpretable parse-state information. This involves generating a dataset of input sentences (along with their parse charts from a traditional Earley parser for ground-truth). For each position in each sentence, we know the set of Earley states (grammar rules with dots) that should be present in the correct parse. We can then train simple classifiers (probes) on the model’s internal representations to predict properties of these states. For example:

  • A symbol probe that predicts which nonterminal(s) are being predicted or completed at a given position from the vector or .
  • A state probe that tries to identify specific Earley items (like “rule started at i”) in the hidden vector. This could be framed as a multi-label classification: for each possible grammar rule and dot position, does the hidden state encode that item as present or not?

We would train such probes on a held-out set of sentences, keeping the transformer’s weights fixed. High accuracy of these probes would indicate the model’s activations are aligned with actual parser states. Prior work demonstrates this approach: for instance, Shain et al. (2022) probed GPT-2’s activations and found evidence of “stack-like” incremental syntactic states being encoded, which could even be manipulated to affect generation (). Similarly, if our model truly implements Earley parsing, a probe should be able to read off the incremental parse configuration from its layer outputs.

Attention Pattern Analysis: In parallel, we will examine the learned attention weights to see if specific heads correspond to the predicted algorithmic roles:

  • We expect to find a “Scan head” in the first-layer attention: one that predominantly attends from position to (previous token) when a terminal is expected and matches. We can verify this by measuring attention probabilities: does some head consistently put nearly all its weight on the immediately preceding position? Does that only happen when the preceding token actually is the one needed? By correlating attention spikes with known scan actions (from the ground-truth parse), we can identify if a head is implementing the scan step.
  • We expect possibly another first-layer head for Predict (though predict is local, an attention head might not be strictly necessary for it). If the grammar rules are encoded in the weights, prediction might largely happen in the FFN. However, the model might still use an attention head to retrieve rule information from a global rule embedding or a special token. If the training setup included, say, a dedicated token with grammar context, a head might attend to it. Barring that, predict may not have a clear attention signature (since it’s a local transformation), so we focus on scan and complete.
  • We expect one or more second-layer heads to serve as “Complete heads.” These should connect positions that correspond to start and end of constituents. For example, whenever a constituent spanning to is completed, we anticipate a head at position attending strongly to the position (or vice versa) where that constituent began. We can verify this by identifying attention links that align with gold parse span start indices. If, for a given , a certain head often picks out an that is exactly the start of some rule completed at , this is a strong indicator that the head is realizing the complete step. We will quantitatively measure how often the highest-attended token for head at position corresponds to the correct for a completed nonterminal, according to the known parse. A significantly above-chance alignment means the model has learned to direct attention in a way that mirrors the Earley complete logic.

Activations and Neuron Analysis: Beyond attention matrices, we can inspect the activations in and directly. Individual neurons or dimensions might correspond to specific grammar flags. For instance, one dimension might activate strongly when a certain nonterminal is currently expected at this position, another might indicate a completion. We can plot or examine activation values conditioned on particular parse events (e.g., average activations when a position has a completed vs when it doesn’t). If we find neurons with clear one-to-one correspondence to such conditions, that’s an interpretable feature. This kind of finding would parallel known results in interpretability: e.g., certain neurons in language models correspond to syntax or semantic features. Our probes could also be introspected — e.g., a linear probe essentially finds a direction in hidden space that correlates with a parse feature. We can inspect the weights to see which hidden dimensions contribute most, potentially revealing latent structure.

Notably, causal testing can strengthen our confidence. If we use the probe to intervene on the model (as done by Shain et al. or in the work on Othello-GPT’s internal state (Actually, Othello-GPT Has A Linear Emergent World Representation — Neel Nanda)), we could edit the model’s hidden state in a way that toggles a predicted parse feature and see if the model’s output (e.g. next token prediction or parse decision) changes accordingly. For instance, using the probe we could try setting the “completed nonterminal X” feature on or off in and check if the model’s subsequent behavior reflects that change (does it still think a certain parse is valid?). In Othello-GPT, such interventions proved the model causally relies on its inferred state (Actually, Othello-GPT Has A Linear Emergent World Representation — Neel Nanda). In our case, a successful causal intervention (e.g., forcing a hidden state to encode a different parse) that predictably alters the model’s output would be strong evidence that the model truly has internally implemented the Earley-like state and not just learned superficial correlations.

4.2 Sparse Autoencoders for Latent Structure

While probing provides supervised insight (using known parse labels), we also employ an unsupervised approach to discover latent structure: training a sparse autoencoder on the model’s hidden states. Sparse autoencoders (SAEs) can compress high-dimensional activations into a lower-dimensional, sparsely-activated code, which often reveals disentangled features. Recent research shows that SAEs can uncover interpretable, monosemantic features in language model representations, addressing the superposition of multiple features in the same neurons (Sparse Autoencoders Find Highly Interpretable Features in Language Models | OpenReview). We aim to leverage this to see if the transformer’s hidden state naturally decomposes into components resembling Earley parser states.

Method: We will collect the hidden representations and for many sentences (the same data used for probing). Then we train an autoencoder where:

  • is an encoder mapping the -dim hidden state to a smaller latent vector of dimension (we expect to relate to the number of independent features in a parse state).
  • is a decoder that reconstructs the original hidden state from the code.

We impose a sparsity penalty (e.g. L1 regularization or a target for few active units in ) so that each latent dimension tends to be either inactive (zero) or active for only a small subset of states. The intuition is that the autoencoder will be incentivized to represent each input using a combination of a few basis features, ideally aligning with distinct parse elements. For example, it might find one neuron to represent “nonterminal is predicted here”, another to represent “we have a state that started at position 0”, etc., if those help it compress and reconstruct the hidden vectors.

After training, we will examine the learned latent features . Key analysis steps include:

  • Alignment with Parse Variables: For each latent dimension , check its correlation with known parse state features. Does activate (e.g. ) exactly when a particular grammar symbol or state is present at that position? For instance, we might find one that is almost always 0 except when the position is in the middle of parsing a noun phrase, etc. If such a one-to-one correspondence is found, we have effectively discovered that the model’s hidden representation contained that information, just not on a single raw neuron but in a rotated space that the autoencoder uncovered.
  • Interpreting Decoded Directions: We can also inspect the decoder . Each latent unit corresponds to a direction in the original -dimensional space (given by the th column of the decoder’s weight matrix). By looking at which original features (or probe-identified parse features) this direction emphasizes, we can interpret what concept it represents. For example, if decoding latent produces a vector that strongly overlaps with the probe direction for “Expecting ”, then effectively encodes that Earley item.
  • Monosemantic Feature Detection: We anticipate that, thanks to sparsity, each latent will be monosemantic (Sparse Autoencoders Find Highly Interpretable Features in Language Models | OpenReview), meaning it captures one coherent aspect of the parse. To verify this, we might use automated interpretability metrics (as in the cited work) or simply manual inspection against many known features. Ideally, we’d see a few latent units corresponding to things like “Nonterminal predicted at this position”, “Span from i to j is complete”, “Dot is at end of rule”, etc., mirroring the components of an Earley state (which is a triple: rule, dot position, start index).
  • Reconstruction Quality: We will ensure the autoencoder can accurately reconstruct hidden states. High fidelity means the latent code is a sufficient summary of the hidden state. If, in addition, the latents align with parse concepts, it implies the model efficiently encoded the parse chart. Low reconstruction error combined with interpretable features would strongly support that the transformer’s internal representations are isomorphic to a chart parser’s state.

Validating Causal Relevance: Just as with probing, we can use the autoencoder in interventions. Since yields an interpretable code, we could edit the code and then decode it to get a perturbed hidden state, then feed that into the remainder of the model to see effects. For instance, toggle the latent corresponding to “complete a certain nonterminal” and see if the model’s next-layer output or final prediction changes consistently. This is similar in spirit to the causal experiments done with Othello-GPT’s board state, where altering the internal state in the model caused it to follow the new state legally (Actually, Othello-GPT Has A Linear Emergent World Representation — Neel Nanda). In our parsing scenario, if we intervene to remove a latent feature representing some predicted rule, the model’s output should act as if that rule was never predicted (perhaps leading to parse failure on that path). Such results would confirm not just correlation but actual use of these latent parse features by the model.

Summary of Steps: To concretely execute this plan:

  1. Train/Select Model: Use a two-layer transformer trained on a parsing task (e.g., it could be trained to predict if a string is in the language or to produce a parse). Ensure we have a known grammar so we can get ground-truth Earley states for analysis.
  2. Data Collection: Run a corpus of sentences through the model, recording and for each token position. Simultaneously, run a classical Earley parser to get the set of states at each position (for supervision in probes).
  3. Probing Analysis: Train simple probes to predict various parse-state properties from and . Evaluate their accuracy. Look for specific heads with attention patterns corresponding to Scan/Complete by analyzing attention weight matrices against parse charts.
  4. Sparse Autoencoder Training: Train a sparse autoencoder on the collection of hidden states (possibly separately for and layers to see differences). Validate that it reconstructs well.
  5. Interpret Latent Features: For each latent dimension of the autoencoder, correlate with parse features and inspect decoder weights. Document which latent corresponds to which aspect of parsing. (E.g., might align with “dot at end of some rule”, etc.)
  6. Intervention Tests: Pick a few critical latent features and manually intervene (set them to 0 or 1, etc.) in the autoencoder code for some test cases, decode to modified hidden state, and run the model forward. Observe changes in model output (e.g., does it now accept a string it previously rejected, corresponding to an added parse path?). This tests if those features are causally connected to the model’s decisions.
  7. Attention-Feature Linking: Finally, link the findings: check if the heads identified in step 3 correspond to operations identified in step 5. For example, if we found a head that does completion by linking to position , does the latent feature analysis show a feature “start-index = i” being activated at that same time? This would paint a consistent picture that head outputs feed into specific feature neurons representing parse state info.

By conducting these probing and autoencoding experiments, we expect to empirically verify the hypothesized algorithmic behavior of the transformer. If successful, we will see that the model’s attention heads and latent dimensions map onto the Earley algorithm’s mechanics (as hypothesized in section 2). Prior results give us optimism: even large black-box LMs have shown emergent interpretable structure for tasks like syntax and even game states () (Actually, Othello-GPT Has A Linear Emergent World Representation — Neel Nanda). With our targeted training and analysis, we anticipate uncovering a clear alignment between the transformer’s internal representations and Earley-style parsing states. This would demonstrate that the model not only produces correct outputs, but internally simulates a structured parsing process much like the classical Earley algorithm. Each component – attention heads and hidden features – would then have a meaningful interpretation in terms of parser operations, greatly enhancing the transparency of how the model is performing context-free parsing.

Self-Attention as Incremental Chart Storage and Propagation

Encoding the Earley Chart in Hidden States: We assume the Transformer is tasked with recognizing or parsing a sentence according to some context-free grammar, so it must simulate something like an Earley chart. We can imagine that each position in the input has an associated hidden vector that encodes the set of Earley states (a “chart column”) for that position. An Earley state can be denoted meaning nonterminal with input from position to current yields (already recognized) and expects next (the bullet marks current position in the rule). The challenge is to store a set of such states in a fixed-dimension vector . In principle, a high-dimensional can represent a superposition of many states by embedding symbols and positions as features. For example, could be a sum of basis vectors for each state in :

for some learned embedding of Earley items. The Transformer’s training will encourage to organize such information so that necessary operations (predict, scan, complete) can be done by attention/FFN. Indeed, recent interpretability research has found that Transformers learned on CFG-generated data encode precise chart information in their latent space – hidden vectors can be decoded to recover parse states and constituents ([2305.13673] Physics of Language Models: Part 1, Learning Hierarchical Language Structures). This means the self-attention layers have the capacity to carry the incremental parse similar to an Earley chart.

Information Flow Across Layers: Self-attention provides a mechanism to propagate and combine chart information between positions, analogous to how the Earley algorithm moves states between sets. We can model one layer of attention as an update:

where is the attention weight from position to . Think of as a soft indicator of a dependency between position and ’s states. The network can learn to make large if and only if contains a state that needs, or vice versa. In Earley terms, there are two primary dependencies:

  • Scan dependency: needs information from if a token at was expected and matches.
  • Complete dependency: (later position) needs info from some (earlier position) if a nonterminal spanning to just completed and had been waiting for that nonterminal.

Self-attention can realize both types of dependency passing in parallel. For scanning, position attends to (or vice versa) to get states that advanced by consuming the token at . For completion, position attends to some (the start of a completed constituent) to acquire the higher-level state that can now be completed. Because attention is all-pairs, each position can potentially look at all earlier positions to find any constituent that started at and ended at . This is exactly the information needed to complete a nonterminal spanning to . Thus, self-attention layers propagate partial parse states akin to how the Earley chart is filled in: they broadcast the fact “nonterminal is complete at with start ” to the waiting site , and conversely broadcast “position expects ” to the completion site . Each layer can add more such links or strengthen existing ones, gradually building up the full parse chart. By layer , even long-range dependencies (large spans) can be resolved through a chain of attentions across layers. Empirically, attention heads indeed learn such patterns: in hierarchical CFG tasks, attention maps show clear banded patterns corresponding to matching parentheses or constituents, effectively performing the dynamic programming for parsing ([2305.13673] Physics of Language Models: Part 1, Learning Hierarchical Language Structures).

Maintaining Incremental Consistency: The Transformer’s parallel updates might suggest it could propagate information out of order, but the learned attention weights enforce the correct sequencing of dependencies. For instance, a completion link from to (i.e. expects a nonterminal that completes) will only receive high weight after the network has evidence that the nonterminal from to is recognized. If the necessary constituent isn’t yet recognized (i.e. the sub-parse between and isn’t complete), then will not contain the “ is complete” signal, so the key/query match with will be weak. In this way, the model’s attention mechanism stores partial results and only allows them to propagate when appropriate – mimicking Earley’s rule that you only complete when a constituent is finished (you wouldn’t erroneously connect an incomplete constituent). The residual connections help preserve these partial results until they can be used. An incomplete state (e.g. “expecting at position ”) will reside in across layers; once some later position finishes , a head can finally make the connection. This dynamic is akin to the Earley chart where an item waits in until a matching completion in enables a new item in . Each Transformer layer thus performs a parallel update of the chart: all possible scans and completions (that are licensed by the current states) are attempted, and new states are added to the representation. Over many layers, this process can simulate multiple rounds of Earley inference, gradually pushing the parse to completion. Recent theoretical work confirms that Transformers (even of moderate size) can emulate context-free parsing algorithms in this layered manner () (). In particular, Zhao et al. (2023) show a Transformer can learn to execute the Inside-Outside algorithm (a chart parsing method) for a PCFG, with information about parse constituents flowing through attention weights exactly as needed for the DP algorithm (). Moreover, Transformers inherently handle “stack-like” information better than sequential models – they can simulate pushdown automata state transitions with less difficulty than RNNs ([2112.09174] Learning Bounded Context-Free-Grammar via LSTM and the Transformer:Difference and Explanations) – which explains why they naturally excel at representing the nested structures in a parse. The bottom line is that self-attention serves as the vehicle to store intermediate parse states in the residual stream and propagate those states across positions, layer by layer, effectively building the Earley parse chart in a distributed fashion.

Transformer’s Attention/FFN Approximating Earley Parsing (Equations & Justification)

We now detail how each Earley step can be approximated by Transformer sub-layers, with explicit equations:

  • (a) Prediction via Feed-Forward Layers: Earley’s Predict step adds new states at position whenever some state in expects a nonterminal next (Using Grammar Masking to Ensure Syntactic Validity in LLM-based Modeling Tasks). The Transformer can learn to do this in the position-wise FFN. Let encode the states at . We assume there is a learned subspace or features in that indicate “expecting nonterminal ”. The FFN can be viewed as a function applied to (same for each position). A two-layer ReLU network, for example, can implement a logical implication: if contains feature (“expect ”), then output features for each rule (the initial expectations). Schematically, we can write:
    where is a learned weight vector detecting an expectation of , is an activation (like ReLU or sigmoid), and is a learned output vector representing the new Earley state with dot at the beginning of ’s production. In essence, adds basis vectors for all productions of into ’s representation. Thanks to the residual add, the post-FFN state is
    This means now includes any newly predicted states in addition to the ones it already had. Crucially, this happens locally at position , without needing interaction between positions (just as Earley’s predict operates on one chart column at a time). The FFN thereby plays the role of expanding nonterminals into their possible productions. Mathematically, if we use an indicator basis for states, we can say before FFN represents set , and after FFN it represents – exactly the closure under predictions. The ability of a neural network to encode such rule-based additions comes from its nonlinearities and learned weights that encode grammar rules. (For example, it’s known that Transformers are Turing-complete and can in principle implement context-free grammars and pushdown stacks ([2112.09174] Learning Bounded Context-Free-Grammar via LSTM and the Transformer:Difference and Explanations) ([2112.09174] Learning Bounded Context-Free-Grammar via LSTM and the Transformer:Difference and Explanations).) Thus, the Predict step is approximated by the FFN’s nonlinearity, which injects grammar-derived expectations into the residual stream.
  • (b) Scanning via Self-Attention (Local Dependency): Earley’s Scan step consumes an expected terminal and advances the state to the next position (Using Grammar Masking to Ensure Syntactic Validity in LLM-based Modeling Tasks). Formally, if and the input token at position is , then we add to . In the Transformer, input tokens are part of the initial embeddings. Let be the one-hot (or embedded) representation of the actual token at . We want the model to carry the state from to if the token matches. We can achieve this with content-based attention. Suppose contains a feature for “expecting terminal next” and the token embedding indicates the actual token. We can design one attention head such that: the query at position includes the previous token information, and the key at position includes the expected terminal information. For example, define query vector (including which is token ) and key (which will have a high dot-product with if was expecting that token). In practice, the Transformer can use positional embeddings to know that is immediately before , or use a relative position bias for neighbor tokens. The attention weight for scanning between and might be modeled as:
    This will be large only if two conditions hold: (1) position ’s state encodes an expectation for a terminal (say ), and (2) (the token at ) is exactly that terminal . If the token doesn’t match the expected symbol, then no attention linkage forms (the dot product remains low). When the match occurs, the head will carry the value over to :
    What is contained in ? It can be a transformed version of the state that was expecting , now marking that has been seen. In other words, could encode the Earley item if contained . This is how the attention mechanism moves the “dot” past a terminal. All such scans for every position happen in parallel in self-attention: each token position that fulfills some expectation at will pass that state to . (If multiple states at expect the token, multiple contributions can be passed; attention naturally sums them weighted, or multiple heads could handle different expectations.) After this attention, position ’s hidden state now includes the advanced states. Because we use residual addition, still also contains whatever it originally had (e.g. its own predicted states from before). But now it has extra pieces corresponding to states carried over from that succeeded in scanning. This mirrors how Earley’s chart gets all states from that matched the th token advanced into it. Mathematically, if prior to scanning encoded and token was , then after attention encodes . If the state becomes complete (i.e. was empty), that will be handled in completion. In short, self-attention can implement the Scan step by linking adjacent positions conditioned on token identity, using dot-product matches as a differentiable proxy for “token equals expected symbol”. This maintains sequential order because a state only moves from to if the correct terminal was present.
  • (c) Completion via Self-Attention (Long-Range Dependency): Earley’s Complete step connects a just-completed constituent with any parser states that were waiting for it (Using Grammar Masking to Ensure Syntactic Validity in LLM-based Modeling Tasks). If is a completed state ending at position (meaning nonterminal spans from to ), and there is some incomplete state that was expecting , then Earley adds to . This “long-distance” update (from to ) is naturally handled by Transformer attention, since any position can attend to any other. We configure another attention head such that queries represent completed constituents and keys represent awaiting constituents (or vice versa). Concretely, suppose at layer the hidden state at position includes a feature for “nonterminal completed here with start ”. And suppose the hidden state (at the start position ) includes a feature “expecting nonterminal ” as part of some larger rule. We want to receive from the information about that rule context, so that can now mark as present. We can set up attention where position is the query and position is the key/value:
    The network will learn to make this inner product large when two conditions hold: (1) carries a signal that a constituent ending at is available (this can be encoded since might have received an advanced state with via scanning or earlier predictions), and (2) carries a signal that was expected at . If those match (same nonterminal ), the attention weight will be high. Then gets an additive contribution from :
    The value vector can be designed to represent the awaiting state now advanced through . Essentially, holds the template of the rule that had a gap ; once is filled (completed at ), is updated with that filled state. After this attention, includes the information that “ (originating at ) is now complete up to here”. This is exactly what Earley would add to . Because the Transformer does this for all pairs in parallel, multiple possible completions can be processed at once. And thanks to residuals, earlier incomplete info at or other content isn’t lost – we’re only adding new completed states to . It’s worth noting that in Earley, the completion step might trigger further predictions or even further completions (if was empty, itself becomes complete and can complete something earlier). In the Transformer, these secondary effects naturally happen in subsequent layers: once has the new state, a further FFN could predict anything expects next, or another attention head/layer could use ’s completion to update an even higher-level state. Layer by layer, the network can thus carry out multi-step completions that would require a loop in the Earley algorithm. In fact, the attention mechanism iteratively resolves dependencies until the entire input is parsed. Researchers have observed that this iterative refinement occurs in practice: higher Transformer layers increasingly refine and combine lower-layer information to build up syntactic structure, analogous to completing larger and larger spans ([2305.13673] Physics of Language Models: Part 1, Learning Hierarchical Language Structures). By the final layer, the model’s representation has effectively solved the same dependencies Earley would have – each position encodes what nonterminals span there, which parse states are completed at the end, etc., consistent with a full parse.

Justification of Sequential Integrity: The above equations show each step’s neural analogue. The key point is that a Transformer can be trained to approximate the indicator functions (e.g. “expecting ” or “completed ”) with continuous vectors that the attention’s dot-products can recognize. There is an implicit enforcement of order: a Completion attention link will only be strong if had an expectation and had the completed symbol – meaning the Predict and Scan steps for must have occurred earlier (in previous layers) to produce those signals. If they hadn’t, or would lack the requisite feature and the attention weight stays low. Thus, even though the Transformer doesn’t run an explicit loop, it respects Earley’s dependencies by construction: no state propagates unless conditions are met. In essence, the network computes a fixed-point of the Earley algorithm’s inference: it keeps passing information until all expectations are either satisfied or no further progress can be made, which in a well-formed sentence results in the start symbol being completed at the final position. This aligns with findings that pretrained Transformers implicitly perform parsing as they process text (). They don’t violate the grammar rules; rather, they learn to embody them in the pattern of attention and activation across layers, executing the spirit of Earley’s algorithm in a parallel but mathematically equivalent manner.

Summary of Equations: To tie everything together, we can write an abstract update for a Transformer layer that combines these operations:

  • Let be the portion of encoding predicted (expected) symbols at ,
  • represent the token at ,
  • the portion encoding unmatched (incomplete) expectations, and
  • the portion encoding completed constituents at .

Then one layer’s effect (attention + FFN) can be expressed as:

Here is the FFN function for predictions (as described), is the scanning attention update (nonzero mainly for and matching symbols), and is the completion attention (nonzero for matching nonterminal expectations/completions). The exact formulas for and involve the softmax weights as described earlier. While this looks complex, it’s just a decomposition of the Transformer’s standard equations into parts corresponding to Earley steps. Each part has been justified: adds new expected items at the same position (like Predict), moves states to next position if tokens match (Scan), and connects positions to complete higher-level rules (Complete). The combination shows how a Transformer layer can simulate a sweep of Earley’s algorithm. Multiple layers allow repeating this process, so even nested or iterative predictions/completions (which Earley would do in a loop) are handled. In conclusion, through these equations we see how attention and FFN layers interact to perform parsing: the FFN expands the state space locally (grammar closure), the self-attention passes messages between positions (state transitions and completions), and residual connections accumulate these contributions. This layered computation closely tracks the sequential structure of Earley’s algorithm, proving that a Transformer can encode and execute an approximate Earley parse despite operating in parallel. All the essential dependencies (predict before scan, scan before complete) are enforced by the network’s learned weight structure and the requirement of matching keys/queries. Hence, mathematically, the Transformer’s updates can be understood as an emulation of Earley’s predict-scan-complete cycle spread out across the model’s depth, yielding parse-consistent representations by the final layer () ([2305.13673] Physics of Language Models: Part 1, Learning Hierarchical Language Structures).

Sources: Dynamic parsing algorithms and transformers – Earley algorithm phases (Using Grammar Masking to Ensure Syntactic Validity in LLM-based Modeling Tasks); Transformers encode CFG parsing via attention ([2305.13673] Physics of Language Models: Part 1, Learning Hierarchical Language Structures); Transformers can execute parsing algorithms in practice () ([2112.09174] Learning Bounded Context-Free-Grammar via LSTM and the Transformer:Difference and Explanations).