1. Formalizing Earley Parsing vs. Transformer Operations

Earley Parsing Recap: Earley’s algorithm maintains a set of states (or “items”) at each input position. Each state is a tuple (Rule, dot, origin) indicating a grammar rule with a marker (dot) showing how much of the rule has been matched so far, and the position (origin) where this rule began. At each position j, Earley performs three operations sequentially:

  • Predict: If a state at position j has a nonterminal A after the dot (meaning A is the next symbol expected), then add new states at j for each production of A (with the dot at the beginning of A’s RHS). This “predicts” possible sub-structures starting at j.
  • Scan: If the next symbol after the dot is a terminal t and the input token at position j is t, then advance the dot and add that state to position j+1. This consumes the token t.
  • Complete: If a state at j has the dot at the end of a rule (meaning a nonterminal A was just recognized from some origin i to j), then complete any pending states that were expecting A at that origin i. In other words, for each state in the chart at position i of the form (X → ...·A..., origin=k), advance the dot past A and add that updated state to position j. This represents completing A and making progress in any rule that was waiting for A.

These operations are iterated in order for each position from 0 to n. Notably, the operations for position j depend on all results up to j (including repeated predictions/completions at j itself before moving to j+1).

2-Layer Transformer Setup: We consider a Transformer-like model with two layers processing an input sequence of tokens in parallel. For clarity, assume:

  • Layer 1: Produces some initial representation for each token (e.g. via token embedding and maybe a feed-forward sublayer). This layer could also incorporate some grammar-based preprocessing if allowed (more on this later). We’ll denote the output of layer 1 at position j as h¹_j.
  • Layer 2: Applies self-attention across positions (with a residual connection). The problem specifies that the second layer has only attention (no additional feed-forward after). So layer 2 allows each position to attend to other positions and aggregate information. Let the output of layer 2 at position j be h²_j.

We also assume causal masking (since Earley parsing is left-to-right): position j’s layer-2 attention can only attend to positions ≤ j (not future tokens), ensuring we respect the parse order. This mimics how Earley doesn’t use information from future input during parsing.

Mapping Idea: To simulate Earley’s steps in this 2-layer transformer, we need to encode the parser’s intermediate state sets into the transformer’s hidden representations and use attention to propagate these states. Conceptually:

  • Predict (in parallel): In Earley, prediction at position j adds new states at j based on a nonterminal expected at j. In a transformer, layer 1 could be designed to incorporate all initial predictions for each position. For example, if the grammar’s start symbol is S, position 0 might immediately include predicted states for S (just as Earley would at position 0). More generally, we could encode in h¹_j a representation of any grammar rules that might begin at j. However, a naive approach might include all possible nonterminals or rules at every position, which is inefficient. A better approach is to encode only what’s needed – but “needed” depends on the parse context, which we don’t know until parsing proceeds. This circular dependence is the crux of the challenge.
  • Scan: The actual input token at position j is already part of the transformer’s input. The matching of an expected terminal with the actual token can be handled locally. For instance, h¹_j can encode the token itself. If a state in the representation of j expects token “x” and the token is “x,” we need a way for that expectation to advance to j+1’s representation. In a transformer, such advancement could be achieved if position j+1 attends to position j in layer 2, and if j’s representation carries a signal “I had a state expecting token x which was satisfied.” In other words, h²_{j+1} could receive from h¹_j the information that a state has scanned successfully. This requires carefully designing the attention/query-key mechanism so that an expected terminal at j matches the actual token at j and triggers an update to j+1. (This is complex to do exactly, but we describe adjustments in section 5.)
  • Complete: Completion is the most non-local step. If a nonterminal A finishes at position j with origin i, Earley adds a new state at j (advancing any state that was waiting for A at i). In the transformer, position j needs to acquire information from some earlier position i that “a constituent A began at i and is now ending at j.” How can position j know this in two layers? The only opportunity is in the layer-2 attention: h²_j can attend to h¹_i for any i < j. If h¹_i contained an encoded state “expecting A starting at i” and h¹_j (or some position between i and j) signals “nonterminal A completed here,” then attention could link these to update h²_j accordingly.

In summary, a rough mapping would be:

  • Layer 1: Provide initial token info and possibly predicted grammar states for each position independently. (For example, embed each token and maybe embed all grammar rules that start with that token or something heuristic.)
  • Layer 2 (self-attention): Perform the Complete and Scan propagation in one sweep. Each position j will attend to earlier positions to gather any states that should complete at j, and attend to the immediately previous position j-1 to carry over any state that scanned a terminal into j. The multi-head attention could, in theory, use different heads for different types of propagation (one head focusing on immediate predecessor for scanning, another head scanning further back for possible completions).

This formal mapping is challenging because Earley’s algorithm may perform many predict-complete cycles at one position before moving on, whereas a 2-layer transformer has a fixed, limited computation per position. We next address the fundamental challenge in this mapping.

2. Challenge: Sequential Dependencies vs. Parallel Processing

Earley’s Sequential Dependency: In Earley parsing, processing position j to completion (predicting all needed states, scanning the token, completing any possible constituents) is a prerequisite for processing position j+1. The state at j+1 depends on the fully updated chart at j. If we try to parallelize Earley naively (process multiple positions at once), we hit dependency issues: many of the “tasks” at j+1 can’t be done until tasks at j finish. In fact, researchers have noted that “dependencies between Earley items force much of the work to be performed sequentially.” (Can Earley parser work in parallel? - Computer Science Stack Exchange). This inherent sequentiality is what makes Earley difficult to parallelize.

Transformers Are Parallel: A standard transformer encoder processes all tokens simultaneously in each layer – there is no built-in notion of “finish position 0, then move to 1, etc.” All positions j in layer 2 will attend to positions < j (with a causal mask) in the same forward pass. There is no mechanism to enforce an order in which positions update beyond the masking. Essentially, position j in layer 2 can use information from positions < j (from layer 1 outputs), but it cannot wait for those positions to perform multiple rounds of inference beyond what’s already in their layer-1 representation.

The Core Conflict: In Earley, by the time we handle scanning at position j, we assume that position 0 … j have gone through potentially multiple predict/complete loops and have final state sets. In a 2-layer transformer, however, we have only one pass of attention to “simulate” all those updates. Position j’s layer-2 computation will see position i’s layer-1 output (for i<j), but those layer-1 outputs themselves did not benefit from seeing other tokens (if layer 1 was just embeddings/FFN). In other words, position i in layer 1 does not know about any completions that might happen at some later k > i; it only encodes trivial local info. The dependency chain in Earley – where state info percolates from left to right through intermediate positions – is hard to reconcile with the transformer’s two-layer, parallel update structure.

Concretely, imagine a nonterminal A that spans from position 2 to position 10 in the input. Earley would discover A only when it reaches position 10 and completes it, then it would immediately complete any awaiting rules back from origin 2 to 10. In a transformer, position 10 can attend to position 2 directly. But will position 2’s representation contain the information “I have a pending A expecting to be completed”? Possibly yes (if we encoded that in layer 1), but position 10 also needs to somehow know “the substring 2–10 is an A”. That information is not explicitly in the input; it’s a result of parsing. A parallel transformer would have to infer this in one shot using attention, effectively computing a global relation “span(i,j) is of type X” without iterative refinement.

Conclusion of Challenge: The key difficulty is that Earley’s iterative algorithm implies a depth of computation proportional to input length in the worst case, while a fixed-depth transformer tries to compress all necessary computation into just 2 layers. Scanning at j depending on all prior work means a naive parallel simulation might try to do j steps of reasoning in one layer – which a constant number of layers cannot explicitly do. This suggests a direct, trivial mapping will fail for general cases: the transformer would either need more layers to sequentially simulate the steps, or some clever trick to encode the effect of those steps in parallel. We explore whether 2 layers could ever be enough next.

3. Is a 2-Layer Transformer Sufficient for Full Earley Parsing?

In general, a 2-layer transformer (even with multi-head attention) is not sufficient to perform full general context-free parsing like Earley’s algorithm for arbitrarily long inputs. The reason ties back to formal language theory and the power of neural networks with limited depth:

  • A 2-layer transformer is a very shallow network. With standard configurations, each layer can perform only a constant number of operations on the sequence (e.g., one round of attention weighting and addition). Earley parsing, by contrast, may require on the order of n sequential steps for an input of length n (in the worst case, e.g., a highly ambiguous grammar or many nested nonterminals). Compressing n steps of inference into 2 parallel operations is generally infeasible unless n is very small or the grammar has a trivial structure.
  • Recent theoretical work backs this up. Hahn (2020) showed that self-attention networks have fundamental limitations in modeling hierarchical or recursive structures unless the number of layers (or heads) grows with the input length ([1906.06755] Theoretical Limitations of Self-Attention in Neural Sequence Models). Context-free grammars (which Earley targets) produce hierarchical parse trees of unbounded depth; a fixed-depth transformer cannot fully capture such unbounded recursion. In essence, a standard transformer with fixed layers can’t implement an arbitrary pushdown automaton needed for parsing an arbitrary context-free language.
  • A 2-layer transformer might handle some limited-depth parsing problems or small grammars. For example, there are contrived cases where a carefully designed 2-layer transformer can recognize a bounded-depth Dyck language (balanced parentheses) if provided extra help (like explicit encoding of parenthesis depth in layer 1) () (). But these are special cases or require the network to be given significant prior structure. For a general grammar, the needed parse “state” can grow with input length (more nested constituents, etc.), which two layers cannot accommodate explicitly.
  • The second layer’s multi-head self-attention does allow global information exchange across the sequence, so in principle each position’s final representation h² can aggregate signals from anywhere in the prefix. This means a 2-layer transformer could simultaneously consider many possible completions or predictions in parallel. However, it would effectively have to compute something akin to the entire parse chart in one fell swoop. Without an iterative process, there is no opportunity to correct or refine intermediate states, which is typically necessary for parsing complex sentences.

Conclusion: For a full Earley parse (which finds all possible parses or at least a correct parse for any context-free grammar), a transformer with only 2 layers is generally insufficient. It lacks the iterative depth needed to simulate the step-by-step accumulation of parse states. Each additional layer in a transformer can be seen as an extra “round” of computation or inference. Simulating the complete Earley algorithm likely requires O(n) rounds in the worst case (or at least O(log n) rounds using clever parallel algorithms like CYK’s divide-and-conquer). With only 2 rounds available, the model would fail on inputs requiring more extensive sequential reasoning.

That said, if the grammar or inputs are extremely simple (e.g., minimal nesting) or if we only require partial recognition, a 2-layer model might approximate some parsing. But in the general case, we need either more layers or other mechanisms to compensate, as discussed next.

4. Self-Attention vs. Additional Mechanisms for State Propagation

Self-Attention Alone: Self-attention is powerful for learning dependencies, but by itself it does not provide a memory of unbounded length or an inherent sequential chain of reasoning. Each self-attention head computes a weighted sum of other positions’ representations. In one layer, this is essentially one step of information propagation (each position looks at others once). Multiple heads in the same layer still constitute one parallel step (just focusing on different aspects). With two layers, we have two such steps. This is not enough to carry out arbitrarily long sequences of dependent computations. As one study notes, standard scaled dot-product attention “does not have a mechanism for handling hierarchical patterns of arbitrary nesting depth”, limiting its ability to recognize certain syntactic structures (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview).

For Earley parsing, “state propagation” means carrying information about open constituents and expectations forward through the string. To propagate state across many tokens (especially for long-range dependencies or deeply nested constructs), a network typically would need either recursion or iterative processing. Self-attention with fixed layers cannot simulate a loop that runs potentially n times.

Residual Connections Are Not Time Steps: Transformers do include residual connections (adding the input of a sublayer to its output), but these serve to stabilize learning and allow layers to refine representations by reference to the original. They do not create a recurrent computation over positions in the sense of processing one token after another repeatedly – all tokens still get processed in parallel in each layer. So a residual connection alone doesn’t introduce the needed sequential iteration. It merely lets each layer’s output be a sum of new information and the previous layer’s information. In two layers, you essentially get: h²j = f(attention(h¹{\le j})) + h¹_j (simplified). This can combine info from earlier positions with the original, but it can’t perform an unbounded loop.

Need for Additional Mechanisms: To truly handle context-free parsing, the transformer would require something beyond vanilla self-attention:

  • Recurrence / Iteration: One way is to iteratively apply the same layers multiple times (effectively unrolling a recurrence). For example, one could reuse the 2-layer network for several “timesteps,” feeding the output back into the input, to simulate multiple Earley steps. Standard transformers don’t do this by default (they have fixed layers, no external loop), but one could imagine a model that runs until convergence or uses an RNN-like loop around the attention module. Without such recurrence, the network is stuck with a fixed small number of inference steps.
  • Augmented Self-Attention: Researchers have proposed modifications like Stack-Augmented Attention (stack-attention) (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview), which give the model a form of stack memory (like a pushdown automaton) to handle arbitrary CFL patterns. In such models, the attention mechanism is changed to explicitly maintain a stack of states that can grow with input length. This kind of specialized attention can, in theory, implement the needed pushdown behavior of a parser (pushing nonterminals, popping on completion, etc.). A standard 2-layer transformer without this cannot push or pop anything – it has no mechanism to increase the effective state depth as needed for nested structures.
  • Embedding Grammar Constraints: Another aid could be encoding some grammar knowledge directly into the network’s structure or embeddings. For instance, one might augment each token’s representation with features that encode which grammar rules could start or end at that position, or what nonterminal category the token could belong to. This external encoding could reduce the amount of reasoning the transformer needs to do. In extreme form, one could pre-compute an Earley chart partially and feed it into a network as input features. However, that is essentially solving parsing outside the network rather than inside it.

In summary, self-attention alone (in a shallow network) cannot propagate the parse state sufficiently far or through enough steps for complex inputs. Either a form of recurrence (more layers or iterative loops) or specialized mechanisms (like a learned stack or tree-awareness) are required to handle the full generality of Earley’s parse computations. This aligns with formal results that a fixed-size transformer can’t recognize general context-free languages without such enhancements ([1906.06755] Theoretical Limitations of Self-Attention in Neural Sequence Models) (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview).

5. Possible Adjustments for a 2-Layer Transformer to Approximate Earley Parsing

Given that a direct, naive mapping of Earley’s step-by-step algorithm to a 2-layer transformer fails for general cases, we consider what mathematical adjustments or design tricks might let a transformer approximate the parser in two layers. The goal is to enable efficient parallel processing of the parse without a deep network. Some proposals:

  • Incorporate Parallel Dynamic Programming via Attention: We can view context-free parsing as a dynamic programming problem (like the CYK algorithm or Valiant’s algorithm using matrix multiplication). These algorithms combine smaller spans into larger spans in a few rounds of computation (logarithmic in the sentence length, if massively parallel operations are allowed). To emulate this in a transformer, we could use multi-head attention to simulate combining of spans. For example, one attention head could be responsible for checking adjacent tokens (spans of length 1 or 2) for possible grammar matches (like scanning and minimal completes), and another head could attempt to combine information from two smaller spans to form a larger span. In theory, with carefully trained weights, a single layer of multi-head attention can perform a limited form of span combination in parallel. The second layer might then refine or finalize the combinations. However, with only 2 layers, this effectively limits us to at most two levels of span merging (e.g., terminals → small phrases in layer 1, small phrases → bigger phrases in layer 2). This might parse short sentences or shallow structures, but not arbitrary depth. It’s an approximation of Earley: we’re trading exact sequential steps for a parallel heuristic. The network might learn to approximate the effect of multiple Earley steps by a weighted sum that “short-circuits” some of the intermediate steps.
  • Use Learned Representations for States: Instead of literal Earley states, the transformer can learn continuous representations that encode set of possible parses so far. For instance, let h¹_j be a vector that encodes all parse states that end at or before position j (in some distributed form). If such an encoding is possible, then a single attention layer could propagate these inferences. Position j attending to i (for i<j) could be seen as: “consider a constituent that starts at i and ends at j”. If the model’s weights know the grammar, it could combine h¹_i and h¹_j to decide if a valid nonterminal covers i..j. In practice, designing such representations is hard, but one could imagine training the model to embed chart information. Mathematically, this is like precomputing the transitive closure of the “predict/complete” relations in a vector form and having attention do a bilinear check for consistency. This approach leans on the transformer’s ability to learn internal algorithmic behavior: it might not follow Earley’s step-by-step exactly, but it learns a function that maps the whole sequence to the parse outcome in two layers. This is more of a learned approximation than a deterministic mapping.
  • “Unroll” the Two Layers Through Residual Recurrence: While residual connections don’t naturally perform iterative computation, one can force a form of iteration by reusing layers. For example, one could feed the output of layer 2 back into layer 2 multiple times (with shared weights) – essentially a fixed-point iteration. This would turn the 2-layer network into a recurrent network that can do multiple cycles of attention until convergence or a fixed number of iterations. Each iteration would behave like another Earley round (Predict/Complete). To keep within the spirit of 2 layers, one might call this a “recurrently used 2-layer transformer.” This isn’t truly two layers in execution (since you run it many times), but it keeps parameter count low. If true recurrence is not allowed, another trick is to initialize the input in a way that encodes multiple copies of the sequence or positions (like positional encodings that allow attention to simulate a multi-hop propagation). These are fairly complex adjustments and amount to adding a recurrence mechanism manually.
  • Augment with External Memory Tokens: Another adjustment is to introduce a small number of special tokens or “memory slots” that can interact with all positions via attention. These could collect global information and redistribute it, effectively performing some of the complete/predict work. For example, a special token could attend to all positions i < j and learn to compute whether a nonterminal was predicted at i and completed at j, then feed that information to position j. This is similar to how one might use an external data structure in parallel algorithms. With only 2 layers, these memory tokens get at most two rounds of interaction, but they might encode complex relations in their weights. This idea goes beyond a pure transformer (it’s more like adding a scratch pad for the algorithm to use).
  • Specialized Attention Patterns: We might design the attention pattern (or the queries/keys) to directly encode Earley relations. For instance, have one attention head’s query represent “I am position j, looking for any origin i and nonterminal A such that A was expected at i and can complete at j.” The corresponding keys at position i might represent “I have an expectation for nonterminal A starting here.” If we could encode nonterminal symbols in the queries/keys (say, via different attention heads or via feature channels in the vectors), then the dot-product attention can naturally line up positions i and j that satisfy the completion relation. Mathematically, if we let part of h¹_i encode a one-hot vector for each nonterminal A that was predicted at i, and let h¹_j encode one-hot vectors for each nonterminal A that could end at j, then an attention head could compute a high score (strong affinity) between i and j for the matching A. This would effectively identify a completed constituent A: i→j. The attention output could then add a representation of that completed A into h²_j (completing the state at j). In practice, implementing this requires the model to know which nonterminals can end at j – which again is not known a priori unless the model learned to predict it from the tokens. So this approach might work if the model has learned to approximate the grammar rules. It’s more of a clever weight design idea than a guaranteed method.

Summarizing the Adjustments: If a straightforward 2-layer transformer can’t exactly do Earley parsing, we can:

  • Add iterative elements (recurrent use of layers or sequential processing disguised in the architecture).
  • Enhance the attention to have a form of memory (like stack or global tokens) or logic that mimics the grammar operations.
  • Encode more information in the representations upfront (so that fewer inferential steps are needed during attention).

All these adjustments are essentially ways to either increase the effective depth of computation or to bake more of the algorithm’s logic into the network’s parameters/structure.

Efficiency Consideration: The question specifically asks about approximating Earley efficiently in two layers. Efficiency here could mean parallel runtime (two layers is O(1) parallel time) or it could mean using the transformer’s parallelism to get near-linear time parsing. A plausible interpretation is leveraging the transformer to do in O(n) (or even sub-quadratic) what Earley does in O(n³) in worst case. Some of the adjustments above (like specialized attention heads that perform global matching) could indeed speed things up by using parallel computation. For example, if the transformer can match nonterminal predictions and completions with a single attention operation (essentially doing many possible completions in parallel), that’s a big efficiency gain. However, the transformer might need a very large width or many heads to encode all possibilities, which is a trade-off (more parallel hardware instead of more sequential steps). The LATE algorithm in parallel parsing research achieved speed-up by using extra data structures to allow out-of-order processing (Can Earley parser work in parallel? - Computer Science Stack Exchange); analogously, the transformer’s learned weights and attention could be seen as “extra structure” that lets it bypass strictly sequential processing.

In conclusion, a naive two-layer transformer cannot straightforwardly replicate Earley’s predict-scan-complete cycle for general context-free grammars – the sequential dependency and potentially unbounded loops are at odds with the fixed low depth. Self-attention alone is insufficient to carry the necessary state through long sequences ([1906.06755] Theoretical Limitations of Self-Attention in Neural Sequence Models) (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview). To bridge the gap, we must either increase the model’s effective depth (via recurrence or unrolling) or introduce new mechanisms that give the transformer some form of memory or algorithmic bias toward parsing. With such adjustments – for example, a stack-aware attention or cleverly crafted multi-head operations – a transformer could approximate Earley parsing in two layers, at least for certain grammars or to a certain depth. The solution might not be a faithful simulation of Earley’s step-by-step procedure, but rather a parallel algorithm that achieves the same final result (recognizing or parsing the input) using the transformer’s parallel attention capabilities. This remains an area where theoretical insights and practical experiments intersect, as understanding the exact capabilities of shallow transformers for structured tasks is an ongoing research question.

Sources:

  1. Earley’s algorithm parallelization challenges (Can Earley parser work in parallel? - Computer Science Stack Exchange) (Can Earley parser work in parallel? - Computer Science Stack Exchange) – illustrates why Earley is inherently sequential due to item dependencies.
  2. Hahn (2020) on self-attention limitations ([1906.06755] Theoretical Limitations of Self-Attention in Neural Sequence Models) – formal result that fixed-depth self-attention can’t handle arbitrary hierarchical structures (context-free languages) without scaling depth with input length.
  3. Stack Attention (DuSell & Chiang, 2024) (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview) – discusses adding a stack mechanism to attention to recognize arbitrary context-free languages, highlighting standard transformer’s limitations.