Earley Algorithm Overview: The Earley parser is a chart parsing algorithm that processes input from left to right and handles any context-free grammar, including ambiguous or left-recursive ones (). It maintains a chart (often conceptualized as a table or matrix) of state sets S[k] at each input position k. Each state (Earley item) has the form (A → α • β, i), meaning nonterminal A is being expanded, α is the portion of its production already recognized, β is the portion yet to be recognized, and i is the start position of this production. The algorithm uses three main operations at each position ():
- Predictor: If the next symbol
βafter the dot is a nonterminal, predict all possible productions of that nonterminal at the current position. In other words, add new states with that nonterminal on the left and a dot at the beginning of its RHS (e.g. from(A → α • B β, i), add states(B → • γ, k)for each productionB → γ) (Earley parser - Wikipedia). This step populates the chart with all grammar rules that could occur next given the current partial parse. - Scanner: If the next symbol
βis a terminal, scan the next word of the input. If the next input token matches that terminal, advance the dot over it (e.g. from(A → α • a β, i)at chart positionk, consume tokenaat positionkand produce(A → α a • β, i)in chartS[k+1]) (Earley parser - Wikipedia). This moves to the next input position and represents recognizing that terminal. - Completer: If the dot is at the end of a production (meaning a rule
Bhas been fully matched), complete that constituent. For every state in the chart where that nonterminalBwas expected next, advance the dot in those states. For example, if we have just finished parsing aBfrom positionjtok((B → γ •, j)inS[k]), then for each state(A → α • B β, i)inS[j], add a new state(A → α B • β, i)toS[k](Earley parser - Wikipedia). This step links completed constituents back to any waiting higher-level productions.
These operations are applied iteratively at each position until no new states can be added, then the parser moves to the next input position, starting from S[0] which is seeded with the start symbol. Conceptually, the chart of states can be seen as a matrix or triangular table indexed by start and end positions, with Earley states populating cells corresponding to spans (in Earley, many states reside in a single index S[k] with varying start positions) (). The term “matrix form” refers to formulating these state transitions in terms of matrix or vector operations. For example, one can represent the prediction step as a matrix that, given a vector encoding the presence of a nonterminal at a position, outputs all possible next states (rules) at that same position. Likewise, completion can be viewed as linking two positions (start i and current k) – analogous to multiplying a matrix encoding active expectations at i with one encoding completed constituents at k. In essence, Earley’s chart-filling can be formalized in a deductive or algebraic framework (), though implementing it efficiently often still involves explicit loops rather than literal matrix multiplications.
Probabilistic Extension (PCFG Next-Token Prediction): Earley’s algorithm can be extended to Probabilistic CFGs by carrying probabilities with each state, using a semiring or dynamic programming approach to accumulate weights (). In a PCFG, each production rule A → γ has an associated probability. As the Earley parser processes the input, it can compute the prefix probability – the total probability of all parse trees that produce the observed prefix. Crucially, Earley’s incremental chart also reveals the set of grammatical choices for the next word given the prefix (). To predict the next token distribution after a prefix, one can look at the states in the latest chart S[n] (for prefix length n): any state of the form (X → α • t β, j) in S[n] indicates that a terminal symbol t is expected next by some partial parse (). By summing the probabilities of all states expecting a given terminal t, we obtain the probability of t being the next token under the grammar (). For example, if at position n the chart has states anticipating ')' and ',' (perhaps from different parses), and the total probability mass of states expecting ')' is higher, then ')' is the more likely next token. This method, derived from Earley’s algorithm, was described by Stolcke (1995) as a way to compute next-word probabilities from a PCFG (). In summary, the Matrix Form Earley Algorithm for PCFGs involves encoding grammar predictions and completions in a structured way (potentially matrix operations) to efficiently propagate probabilities, and using the completed chart at a given prefix to read off the probability distribution of each possible next terminal. It is essentially an autoregressive PCFG language model that at each step outputs a distribution over next tokens consistent with all parse continuations ().
How a Two-Layer Transformer Could Simulate Earley Parsing
A decoder-only Transformer with two self-attention layers can, in principle, learn to emulate the computations of the Earley parsing algorithm described above. Transformers are powerful sequence models (even theoretically Turing-complete) and can encode dynamic programming steps in their pattern of attention and hidden states (). Here’s how a two-layer transformer might represent Earley’s predict-scan-complete mechanism internally:
- Encoding Grammar Rules in Weights: The transformer’s weights (in attention or feed-forward sublayers) can store information about the PCFG’s rules. For instance, a particular pattern of attention or a specific neuron activation could be associated with a grammar rule (like
B → γ). When a certain nonterminal is expected in the context, the transformer’s feed-forward network could generate an embedding that represents initiating that rule. This is analogous to the Predictor step: the transformer’s first layer could take a state that “expects” nonterminalBand output a representation of the predicted rule(B → • γ)at the same position. Because the transformer’s feed-forward network applies a learned function at each position independently (apart from attention inputs), it can be used to add new states at the same chart position. In effect, the first layer’s feed-forward could compute the closure of predictions for any expected nonterminals, expanding them in parallel (since the feed-forward can produce a combination of features corresponding to all possible expansions of that nonterminal). - Self-Attention for Completion: The self-attention mechanism allows each position to gather information from other positions in the prefix. A transformer head can learn to act like Earley’s Completer: when a constituent spanning from some origin
jto the current positionkis recognized (finished), the model should propagate that information to any earlier positionsjthat were waiting for this constituent. Concretely, a head at layer 1 might cause positionk(current) to attend back to positionj(the start of a previously predicted constituent) to fetch the state(A → α • B β, i)and then advance its dot. The output of that attention could update positionk’s representation to include(A → α B • β, i)– thus completingAthroughB. Because self-attention in a decoder is typically causal (each position can attend to any earlier position), it naturally supports these backward-looking dependencies needed for completing constituents. This means, for example, position 5 in the sequence could attend to position 2 if a phrase that began at 2 ends at 5, effectively carrying out the completion step via an attention head. - Multi-Head Specialization: With multiple attention heads in a layer, a two-layer transformer can dedicate different heads to different sub-tasks of the Earley algorithm. For instance, one head might specialize in tracking what nonterminal is expected next (scanning/predicting terminals), another head might track the span starts for completion, and yet another could carry information about higher-level predictions. One head could always attend to the start-of-sentence (position 0) to propagate the start rule and global predictions (simulating the initial predictor seeding the chart with the start symbol). Another head might attend locally (e.g. each position attending to the immediately preceding position) to handle the Scanner (consuming the known next terminal in the input). Yet another head might attend far back to link completed spans to their origins (Completer). By combining these, the transformer can integrate the results of scan/predict/complete in its hidden state.
- Layer Interactions: In a two-layer transformer, the first layer can perform the bulk of the Earley chart update (predict and complete steps) for each position given the prefix, and the second layer can refine this and produce the final next-token prediction. For example, after layer 1, each position’s hidden vector could encode all active Earley states in
S[k](the set of grammar items valid up to that point). Layer 2’s attention could then focus the model’s computation on the last position (end-of-prefix) to aggregate which terminals are possible next. Essentially, layer 2 might act like a read-out of the chart: it could have a head that attends from the final prefix positionnto all positions0..n(or specifically to those positions that originate currently active parses) to collect signals of which terminals are anticipated next. The feed-forward in layer 2 can then transform the collected chart information at positionninto a probability distribution over vocabulary terminals (via the output projection). In this way, the second layer uses the Earley states computed by the first layer to predict the next token. - Feed-Forward as Nonlinear Combination: Each transformer’s feed-forward sublayer (the intermediate MLP) can mix and transform the attended information in complex ways. This is useful for encoding grammar logic. For instance, if one attention head brings in a vector indicating “Nonterminal B completed at this position”, and another head brings “Nonterminal C is expected next at this position”, the feed-forward network could combine those to infer that “A → B C” has been recognized up to B, so now C is the next needed symbol.” Such combinations allow the network to enforce grammar rules. The ReLU (or similar) activations can act like conditions, only firing if certain combinations of inputs (i.e., certain states co-occur) happen, analogous to matching the right-hand side of a grammar rule. Thus, the feed-forward layer can implement the logical step of advancing the dot when a predicted sequence of symbols is found.
In summary, a two-layer transformer has enough structure to emulate an Earley parser’s incremental parsing: the first layer’s self-attention and feed-forward can generate and propagate the chart states (predicting nonterminals and completing constituents by attending to earlier parts of the input), and the second layer can consolidate that information to decide on the next token. Empirical evidence suggests that transformers trained on data from a PCFG do learn an internal mechanism akin to chart parsing. For example, recent work showed that a moderately sized transformer (BERT) can approximately execute the Inside-Outside algorithm (a chart parsing algorithm for PCFGs) internally (). In that study, the model’s embeddings were found to encode parse trees and grammar rule probabilities, indicating that the transformer had learned to internally represent a dynamic parse chart. While an exact Earley algorithm might be complex to hard-code in a tiny two-layer network, the attention heads can simulate pointer movements (like completing spans) and the feed-forward layers can apply grammar rule logic, thereby approximating Earley’s predict-scan-complete cycle within the continuous vector operations.
Probing the Transformer for Earley-Style Parsing Behavior
How can we tell if our transformer is truly implementing an Earley-like parsing strategy internally? We need to open up the black box and analyze its computations. A probing strategy should target the telltale signs of chart-based parsing in the model’s activations and attention patterns. Here’s a concrete plan:
- 1. Attention Pattern Analysis: Examine the transformer’s self-attention weights for systematic behaviors that correspond to parsing. For an Earley-style parser, we expect certain attention heads to consistently attend to positions that correlate with constituent boundaries or rule origins. For example, a “completion head” might frequently attend from a later position back to the position where the current constituent started. If the model is parsing, a token that completes a phrase should draw attention to the start of that phrase (or to the nonterminal that began there). We might visualize attention matrices for various inputs to see if there are diagonal bands or jumps aligning with known grammar spans. Another sign would be a head that always attends to the zeroth position (or a fixed position) to propagate the start symbol and top-down predictions through the sequence – analogous to how the Earley algorithm keeps around the start state in every chart. If we find an attention head that, say, for every token after a certain type of phrase, looks back to the token that began that phrase, it suggests the model is mimicking the completion step of a chart parser. Prior works have found that even standard Transformers sometimes have heads that attend in ways that mirror syntactic structure (for instance, attending to matching parentheses or related verbs and nouns). Such structured attention patterns would support the hypothesis of an internal parsing mechanism.
- 2. Activation and Neuron Probing: Use probing classifiers on the model’s hidden activations to directly detect the presence of parse states. For each position
kin an input, we can train a simple probe (e.g. a linear classifier or small neural network) on the hidden state to predict properties like “Which nonterminals are currently expected at this position?” or “Is there a completed constituent of type X ending here?”. If the transformer is implementing Earley parsing, its hidden state at positionkshould encode the content of chartS[k]– essentially, which grammar rules are active and where they started. We might discover, for example, one neuron (or a combination of a few neurons) that activates strongly if a certain nonterminal (like anNPorVerbPhrase) has been fully parsed ending at this position. Another set of neurons might encode a stack-like memory of open constituents (even though the transformer lacks an explicit stack, it could learn to represent similar information in a distributed way). If linear probes can recover the presence of specific Earley items or nonterminal predictions with high accuracy, that indicates those discrete parse facts are embedded in the continuous representation (). In research, probing has revealed that transformer embeddings often contain latent parse tree information, recoverable as constituency or dependency structure, even without explicit supervision (). We can leverage that here by designing probes for the “chart content.” For instance, feed the model many sentences from the known PCFG and at each prefix position record the hidden state; then label those with the set of Earley states computed by a classical Earley parser. Train a classifier to predict whether a particular Earley state is present from the hidden vector. Strong performance would be evidence that the model’s vectors explicitly carry Earley states. - 3. Causal Interventions (Activation Patching): Go beyond correlation and test causation by manipulating activations. Activation patching involves swapping or overwriting parts of the model’s internal activations to see if the model’s behavior changes in a way consistent with parsing. For example, take two different partial sequences that have different parse charts at a certain position, and interchange their internal states at that position (in one model forward pass) before the model produces the next token. If the transformer truly uses an Earley-chart representation, then giving it the “wrong” chart state should alter its next-token predictions to reflect that chart. Concretely, suppose sequence A expects a noun next (according to grammar) and sequence B expects a verb next at position 5; if we swap their layer-1 hidden states at position 5, does sequence A’s transformed model now predict a verb as next token (as B would) instead of a noun? A successful swap causing a corresponding prediction change would strongly indicate that those hidden states were carrying parsing information about next expected categories. Similarly, we can ablate an attention head suspected of doing completion or prediction by setting its output to zero, and see if the model then fails to enforce grammatical constraints. If nullifying a certain head causes the model to start making ungrammatical predictions (e.g. it predicts tokens that violate the grammar, or it loses the ability to handle long-distance dependencies), that head was likely implementing a critical part of the Earley algorithm. This kind of causal analysis helps confirm that not only does the model’s state correlate with parse features, but that state is actually used for its predictions (). Researchers have used such interventions in interpretability studies (e.g. to identify circuit components in GPT-2 that handle subject-verb agreement or to patch in known correct parse information and see if it fixes model errors).
- 4. Experiments for Chart Parsing Behavior: We should design specific test sentences or grammars that stress the need for Earley-style parsing, and see how the model copes. For instance, use an ambiguous grammar where a given prefix can lead to two different next-token possibilities depending on a subtle difference in parse (Earley would keep both active). Present such a prefix to the model and check its prediction probabilities: are both possibilities present with appropriate probabilities (indicating it’s summing over both parses)? If the transformer is effectively parsing, it should exhibit prefix probabilities matching those from a PCFG Earley parser (). Another experiment: use long-range dependencies that require remembering an open nonterminal over several tokens. For example, a grammar with nested structures (like multiple parentheses or subordinate clauses). An Earley parser would handle this by carrying an open state through the chart until a matching closure appears. If the transformer is doing similar work, its attention patterns or hidden state should clearly reflect the nesting (some heads might keep attending back to the opening token until a closing token is found). We can probe intermediate positions in such cases to see if the model knows a constituent is unclosed. Additionally, incremental probability evaluation: compute the model’s surprise (negative log probability) for a sentence prefix-by-prefix and compare to a known Earley PCFG parser’s prefix probability. A close match in values or trends (e.g. higher surprise at garden-path disambiguation points, as a parser would have when one parse is pruned) would imply the model is effectively doing PCFG-like parsing internally.
Expected Signs of Earley Mechanism: If the transformer truly implements Earley parsing, we anticipate observations such as: (a) Distinct attention heads align with parse structure, e.g. a head that points to rule start positions for completions, or one that uniformly attends to the previous token to carry on sequential scanning. (b) Hidden state encodes chart content – our probes might recover nonterminal indicators or even reconstruct full parse trees from a single forward pass (). Zhao et al. (2023) indeed found that a transformer trained on PCFG data had internal representations from which parse trees and even span probabilities (the inside-outside probabilities) could be linearly extracted () (). We would expect similar for an Earley mechanism: for each span or prefix, the model’s embeddings contain the information about which constituents are possible or completed there. (c) Intervention results: when we patch in correct parse info, the predictions should correct accordingly; when we remove parse info, the model should become inconsistent. For example, if we disable the “completion head,” the model might start ignoring long-range grammar dependencies (perhaps predicting words that would only be valid if a phrase had ended, failing to remember it hasn’t). All these outcomes would strongly indicate the presence of an Earley-style incremental parsing process inside the transformer.
Possible Failure Cases and Alternative Explanations
It’s important to consider that even if our probes don’t find perfect evidence of Earley parsing, the transformer could still be achieving the correct next-token predictions via other means or incomplete parsing strategies:
- Shallow Heuristics vs. True Parsing: One failure case is that the model might appear to follow the grammar without actually constructing a full parse chart. It could be using heuristic patterns learned from data (e.g. “if I see
thefollowed by an adjective, likely a noun comes next”) rather than explicitly simulating grammar rules. In probing, this might manifest as no single attention head cleanly doing the “completion” role – instead, the information is smeared across many weights, or the model might rely on semantic cues. For instance, a transformer might predict the next word by semantic association or by an n-gram-like memory, which often correlates with grammaticality but is not a proper parse. Evidence of this would be if the model fails on sentences that are grammatically valid but semantically odd (which a true parser shouldn’t be confused by). Indeed, prior studies noted that when input sentences are semantically meaningless but grammatically correct, some language models’ purported parsing ability drops (), suggesting they might lean on semantics rather than pure syntax. - Shallow Stack or Finite-State Approximation: Instead of the full Earley algorithm (which considers multiple parallel parse states), the model could be implementing a simpler left-to-right predictive parser (like an LL(1) or deterministic PDA). A two-layer transformer might simulate a single-stack pushdown automaton that handles the grammar if the grammar is near-deterministic. In such a case, the model would effectively choose one parse path (perhaps the most likely) and follow it, rather than summing over all parses. This would still yield a grammatical sequence but would break down in cases of ambiguity or when the most likely path isn’t the correct one later. If we observe that the model, when faced with ambiguity, seems to commit to one interpretation early (reflected in its attention or activations) and is then surprised later when that interpretation fails, it could be using a greedy top-down parse instead of Earley’s breadth-first chart. Such behavior would be an alternative algorithm (more like a probabilistic recursive descent or beam search in the model’s “mind”) rather than full Earley.
- Shifting of Work to Feed-Forward Layers: It could be that the transformer encodes the outcome of parsing in its weights without explicitly mimicking the algorithm step by step. For example, the feed-forward network might learn a direct mapping from certain prefix patterns to the distribution over next tokens, essentially “bypassing” explicit chart construction. This would be more like a giant memorized state machine that just so happens to agree with the grammar’s predictions. In this scenario, you wouldn’t find neat interpretable structures like nonterminal-specific neurons or attention heads pointing to span boundaries; the computation would be distributed in a way that’s hard to align with Earley states. The model could be implementing an Inside-Outside algorithm implicitly (which is a bottom-up probability computation) instead of Earley’s top-down approach – the final results (next token probabilities) would be the same, but the mechanism differs. For instance, the transformer might internally marginalize over parses in a single matrix multiplication-like step, analogous to the inside algorithm, rather than explicitly iterating with predict/complete steps.
- Alternate Parsing Strategies: There are other parsing algorithms (e.g. CYK, left-corner parsing, LR parsing). The transformer might latch onto one of those if it aligns better with the training data or the architecture. For example, a CYK-style approach would fill in possible constituents for spans in a more bottom-up way. We could distinguish this by looking at attention: CYK might require heads that combine information from two sub-spans (which standard self-attention might struggle with directly, as it’s not inherently designed to take two disjoint spans and merge them without intermediate positions). A left-corner parser (a hybrid top-down/bottom-up strategy) might manifest as attention focusing on the most recently started constituent. If our probes show that the model heavily relies only on very local attention (e.g. each token mostly attends to its immediate left neighbor or a fixed window), it might be doing something closer to a shift-reduce parser or an RNN-like mechanism, rather than a full chart.
- Insufficient Layers for Full Earley: With only two layers, the model might simply lack the depth to perfectly implement the entire Earley procedure, especially for grammars requiring multiple rounds of prediction/completion. It might approximate the algorithm for short-range dependencies but fail for more complex sentences. A failure case to watch for is if the model’s performance degrades on sentences with deeply nested or long-distance dependencies that Earley parsing would handle if done properly. That could indicate the model only learned a partial parsing strategy (for example, it might handle up to one level of embedding but not two – perhaps corresponding to using one layer to simulate one level of the stack).
In conclusion, by combining probing techniques and careful experiments, we aim to verify if the two-layer transformer is truly doing Earley-style chart parsing or if it’s using a simpler or less interpretable strategy. Strong attention patterns aligned with grammar rules, hidden states that linearly map to parse items, and the ability to surgically intervene in those states would support the Earley hypothesis. On the other hand, if analyses reveal no clear parse-tracking signals or if the model frequently violates grammar in ways a proper parser wouldn’t, it may be resorting to an alternative algorithm or an incomplete parsing mechanism. In such cases, enhancing the model (more layers or an inductive bias like a stack (Stack Attention: Improving the Ability of Transformers to Model Hierarchical Patterns | OpenReview)) might be necessary for it to truly implement general context-free parsing.