Elamur Research

SyntaxShap: Syntax-aware Explainability Method for Text Generation

Paper · 2024 · Kenza Amara, Rita Sevastjanova and Mennatallah El-Assady

Summary

An explanation of a generated word should show which parts of the preceding text affected its prediction. That becomes difficult when the words depend on one another. A word can contribute little alone yet matter strongly in a particular grammatical context. SyntaxShap addresses this problem by making sentence structure part of the explanation procedure. It uses a dependency tree, a representation of grammatical relationships between words, to restrict the combinations of input words examined when estimating their importance. The aim is to explain a particular next-token prediction more faithfully while respecting the organization of the sentence.

The method adapts the coalition-based reasoning behind Shapley values. A coalition is a selected group of input features; here, those features are words or tokens. To assess a token, SyntaxShap compares the predicted probability of the generated token before and after adding that input token to several permitted coalitions. It averages these changes to obtain an attribution score. Unlike an unrestricted Shapley calculation, its coalitions follow rules derived from the levels of a dependency tree. The weighted variant, SyntaxShap-W, additionally reduces the influence assigned to words farther from the tree’s root. Both procedures explain an existing predictor through its outputs, without requiring access to its internal computations.

The experiments explain predictions from GPT-2 and Mistral 7B using sentences drawn from Generics, ROCStories, and a negation dataset. The authors compare their methods with several established explanation approaches and a random baseline. For Mistral 7B, the syntax-based methods perform strongly on tests that retain highly ranked input tokens and examine how much the prediction changes. The advantage is conditional: on GPT-2, FeatureAblation and SampleShapley give better faithfulness results in important settings. The paper also studies whether attribution patterns change consistently when a sentence is negated. Its syntax-based explanations better distinguish pairs whose predicted next tokens remain equal from pairs whose predictions differ.

The most revealing result concerns the relationship between faithful explanation and human understanding. In an analysis of 22 Mistral 7B cases where a completion fails to respect negation, SyntaxShap and its weighted variant place the negation token first in importance in more than 80% of cases. A reader might instead expect an apparently ignored negation to receive little importance. The discrepancy shows why these criteria need separate treatment: a token can affect a prediction without having the semantic effect a person expects. SyntaxShap therefore contributes both an explanation method and an evaluation argument. Its evidence supports syntax-aware attribution for the tested next-token settings, while leaving open how well it extends to longer passages, difficult parses, other languages, and explanations intended for human decision-making.

Deep dive: SyntaxShap: Syntax-aware Explainability Method for Text Generation

SyntaxShap uses grammatical dependencies to explain next-token predictions, testing faithfulness, coherence, and agreement with human expectations. · about 35 minutes to read

The problem and its context

Explaining a word requires considering its context

In text generation, the significance of an input word depends on the words around it. A subject, a verb, and a modifier form relationships that cannot be recovered by inspecting their identities separately. Removing one word can change how another is interpreted. An explanation that treats every word as an isolated feature may therefore miss an important part of the prediction process.

The paper studies this issue through the task of predicting the next token. An autoregressive language model produces text incrementally, using the preceding input to assign probabilities to possible continuations. SyntaxShap asks a local question about that process: for this input and this particular continuation, which input tokens affected the predicted probability?

“Local” matters here. The explanation concerns an individual prediction under a particular context. It is not a general account of everything the predictor has learned about a word, a grammatical construction, or a subject. The same input token can receive a different attribution when the surrounding sentence changes or when a different possible continuation is being explained.

The authors motivate the task partly through the use of generative systems in settings where understanding their behavior matters. Good performance on many tasks does not remove the need to examine specific failures. Negation is a motivating example: the paper points to Truong and colleagues’ analysis of negation benchmarks as evidence that apparently simple linguistic distinctions can remain difficult.

This makes explanation more demanding than identifying words that look relevant to a human reader. The question is which words affect the actual prediction, including cases where that prediction seems semantically inappropriate. An explanation designed only to confirm ordinary linguistic expectations could conceal the behavior it is supposed to reveal.

Why the authors choose a model-agnostic approach

The paper places SyntaxShap within interpretability, particularly methods that explain predictions after a system has been trained. Its approach is model-agnostic: it relies on obtaining outputs for altered inputs instead of examining a particular internal architecture.

The authors argue that this is practically useful because access to many language systems is limited. If only an interface for submitting inputs and receiving predictions is available, explanations based on internal activations or training details may be unavailable. A method that queries the predictor can still investigate its behavior.

Model-agnostic does not mean assumption-free. An explanation procedure must decide how to alter an input, which outputs to inspect, and how to combine the resulting observations. SyntaxShap makes a deliberate assumption at this stage: grammatical dependencies provide a useful structure for selecting the input combinations against which a token’s contribution should be measured.

The related-work discussion distinguishes perturbation approaches from surrogate approaches. Perturbation methods change features and observe the resulting output differences. Surrogate methods construct a simpler explanation around a prediction. The paper identifies LIME and SHAP as prominent approaches in this area and situates them within the broader landscape described by the survey of explainability for large language models.

The earlier LIME work is relevant because it offers local explanations without tying the procedure to a single classifier architecture. SyntaxShap shares the concern with local, externally observable behavior, but organizes its attribution calculation through syntactic restrictions on coalitions.

What Shapley values contribute

Shapley values originate in cooperative game theory. The central attribution idea is to assess what a participant adds when joining different groups. Translated into prediction explanation, the participants are input features, and the group’s value comes from the predictor’s output.

For text, a coalition might contain some of the input words. A token’s marginal contribution is the output change obtained by including that token in the coalition. Aggregating such changes across contexts gives a feature attribution.

This is appealing because it makes contextual dependence explicit. A word is not judged only in isolation. Its contribution is measured against several combinations of other words, allowing different interactions to influence its final score.

The paper nonetheless argues that textual applications need more structure. Words interact strongly, and arbitrary subsets can ignore the relationships that make a sentence meaningful. The authors also observe that much of the existing SHAP-related work for language had emphasized classification rather than the explanation of next-token generation.

Their proposal belongs to a wider effort to incorporate dependencies into attribution. The related-work section discusses asymmetric Shapley values, which use known dependency information and relax symmetry, and causal Shapley values, which account for causal structure. It also describes approaches that construct coalitions from graph neighborhoods or connected groups.

SyntaxShap uses this general direction without claiming that a dependency parse is a causal account of generation. The parse is a linguistic relational structure used to govern which coalitions are examined. The observed output changes still come from the predictor being explained.

Why grammatical trees are a plausible organizing principle

A dependency tree connects words through head–dependent relationships. Its purpose is to represent grammatical organization instead of the sentence’s left-to-right order alone. A modifier can be linked to the word it modifies even when other material separates them.

The paper draws motivation from earlier work on syntax-sensitive language prediction. It describes research in which syntactic information affects sentence-acceptability judgments and work finding that autoregressive next-word predictions are sensitive to syntactic structure. It also notes earlier uses of dependency information in machine translation.

These observations motivate a narrower question: if grammatical relations matter for prediction, can those relations also help organize its explanation? SyntaxShap tests that possibility by using a parse to determine the contexts in which token contributions are measured.

The closest comparison in the paper’s discussion is HEDGE, which builds hierarchical explanations by grouping words according to measured interactions. Its grouping criterion aims to preserve influential relationships while controlling changes in prediction. SyntaxShap substitutes an explicit grammatical structure for this interaction-based organization.

That substitution is the conceptual contribution. It introduces a linguistic prior into coalition construction. The explanation still depends on the predictor’s measured responses, but the set of responses collected is shaped by a dependency tree.

The method therefore has an immediate attraction and an immediate risk. It can avoid treating every arbitrary word subset as equally informative. At the same time, its explanations inherit the limitations of the parse and of the particular rules used to turn that parse into permitted coalitions. The later experiments address whether this choice helps under the paper’s evaluation criteria; they do not make the choice universally correct.

The method, step by step

Begin with a particular prediction

SyntaxShap starts from an input sentence and an autoregressive predictor. The predictor assigns probabilities to possible next tokens. The explanation targets the token selected from that output, holding its identity fixed while testing altered versions of the input.

The paper introduces the task with an input sequence and a generated sequence:

x = (x₁, …, xₙ),    ŷ = (ŷ₁, …, ŷₘ),    m = 1

Here, x is the input sentence, xᵢ is its token at position i, and n is the input length. The generated sequence is ŷ, its individual generated tokens are ŷⱼ, and m is the number of generated tokens under consideration. The study restricts m to 1, so each explanation addresses the immediate continuation.

The predictor is denoted f. Its output fᵧ(x) is the probability assigned to candidate token y given input x. The token being explained is identified through the highest predicted probability:

ŷ = argmaxᵧ fᵧ(x)

The symbol ŷ denotes the selected continuation, y ranges over candidate continuations, and argmax returns the candidate with the largest value. Subsequent coalition evaluations inspect the probability of this same ŷ. They do not redefine the explanation target whenever a masked input happens to favor another continuation.

This distinction prevents the attribution calculation from changing its question midway. A coalition may make a different word more likely, but the marginal contribution still measures its effect on the original target token.

Parse the input into grammatical dependencies

The next stage uses dependency parsing to construct a tree. Words become nodes, and grammatical relationships become directed connections between heads and dependents. The paper obtains these structures with spaCy, specifying version 3.7.2 in its appendix.

A node’s level is determined by its position in the tree relative to the root. The root occupies level 1. Nodes farther down occupy later levels. SyntaxShap uses these levels to control coalition formation.

This is more specific than simply selecting any connected part of the tree. Its rules are defined through depth: at a given level, earlier levels must already be present, later levels must be absent, and words at the current level may be combined in different subsets.

The authors’ motivating illustration concerns the contribution of the input word husband to predicting wife. The purpose is to measure how much adding husband changes the probability of wife across the permitted contexts. The example conveys the attribution question without making grammatical relevance alone determine the answer.

From sentence to syntax-aware token attributions

The steps in order.

From sentence to syntax-aware token attributionsStep 1: Predict the next token1. Predict the next tokenStep 2: Parse the input sentence2. Parse the input sentenceStep 3: Assign tokens to tree levels3. Assign tokens to tree levelsStep 4: Construct permitted word coalitions4. Construct permitted word coalitionsStep 5: Measure each token’s probability changes5. Measure each token’s probability changesStep 6: Average changes into attribution scores6. Average changes into attribution scoresStep 7: Optionally apply inverse-level weights7. Optionally apply inverse-level weights

The tree supplies the permitted contexts; the predictor supplies the measured contributions. Both are necessary. A syntactically prominent word does not automatically receive a large unweighted score unless including it changes the target probability across the tested coalitions.

Construct coalitions level by level

A coalition is a set of input features retained for an evaluation. Let Xₗ denote all tokens at tree level l. Let X₍<ₗ₎ denote every token at an earlier level. The power set P(Xₗ) contains all possible subsets of the current level.

The family of permitted coalitions at level l can be written clearly as:

𝒮ₗ = {X₍<ₗ₎ ∪ σ : σ ∈ P(Xₗ)}

The symbol 𝒮ₗ denotes the family of coalitions associated with level l. The symbol σ is a selected subset of Xₗ, ∪ means set union, and P is the power-set operation. Each coalition therefore includes all earlier-level tokens together with some selection from the current level.

This rule has an important consequence: words lower in the tree cannot appear in a coalition formed at an earlier level. Conversely, when the procedure reaches a later level, all preceding levels are already included.

The paper states these restrictions separately:

lᵢ > l ⇒ xᵢ ∉ S

Here, lᵢ is the tree level of token xᵢ, l is the level at which coalition S is formed, and ∉ means that the token is absent. A token below the current level is excluded.

lᵢ < l ⇒ xᵢ ∈ S

The symbols have the same meanings, while ∈ means membership. A token above the current level must be present.

At the current level itself, subsets vary. Tokens sharing a level can therefore be assessed in several combinations with their peers, while earlier material remains fixed within that level’s coalition family.

The method also includes an empty coalition at a hypothetical level 0. This supplies a starting context before any actual sentence token is present. The complete collection combines coalitions formed across the tree levels.

Coalitions are sets, so the same collection of retained tokens should not become a different context merely because it can be described through adjacent stages of construction. The paper’s counting argument handles repeated boundaries between levels when deriving the number of updates.

These rules deserve careful interpretation. A coalition formed at a particular level obeys the stated depth restrictions. When a token’s marginal contribution is evaluated against a coalition from an earlier level, adding that token creates the paired input used for the comparison. The method is a particular tree-guided attribution scheme, instead of a requirement that every evaluated input constitute a complete grammatical sentence.

Measure what a token adds

For each input token, SyntaxShap gathers the permitted coalitions that do not already contain it. These include coalitions from earlier levels and eligible coalitions at the token’s own level.

The attribution is the average difference between the target probability with and without that token:

ϕᵢ = (1/Nᵢ) Σ₍S ∈ (⋃ₚ₌₀ˡⁱ⁻¹ 𝒮ₚ) ∪ 𝒮ₗᵢ⁽⁻ⁱ⁾₎ [fŷ(S ∪ {xᵢ}) − fŷ(S)]

The symbol ϕᵢ is the attribution assigned to token xᵢ. Its level is lᵢ. The family 𝒮ₚ contains coalitions formed at level p, and the union over p collects those from levels preceding lᵢ. The family 𝒮ₗᵢ⁽⁻ⁱ⁾ contains coalitions at the token’s level that exclude it. Nᵢ is the number of eligible coalitions in the averaging set. The function fŷ returns the probability of the original predicted token ŷ.

Inside the brackets, S ∪ {xᵢ} retains the coalition’s features and adds the token being assessed. Subtracting fŷ(S) gives its marginal contribution in that context.

A positive difference means that adding the input token raises the target probability for that coalition. A negative difference means that it lowers the probability. Averaging these effects summarizes the token’s contribution across the contexts selected by the syntax-based rules.

The score is therefore target-specific and context-dependent. It is not a direct measure of how much meaning the word contains, how grammatically necessary it is, or how important a human reader considers it.

The paper gives the exclusion family using subsets with xᵢ removed:

𝒮ₗ⁽⁻ⁱ⁾ = {X₍<ₗ₎ ∪ (σ \ {xᵢ}) : σ ∈ P(Xₗ)}

Here, 𝒮ₗ⁽⁻ⁱ⁾ is the level-l coalition family after excluding token xᵢ, and the backslash denotes set difference. The other terms retain their earlier meanings. This construction ensures that the comparison can add the assessed token to a context in which it is absent.

Count the permitted updates

Tokens at the same tree level receive the same number of coalition evaluations, although their measured contributions can differ.

The paper derives the count as:

Nₗ = Σₚ₌₀ˡ⁻¹ 2ⁿᵖ + 2ⁿˡ⁻¹ − l

Here, Nₗ is the number of updates for a token at level l. The quantity nₚ is the number of tokens at level p, nₗ is the number at the current level, and n₀ is set to 0 for the hypothetical starting level. The summation gathers contributions from earlier levels; the remaining terms account for eligible same-level coalitions and repeated boundaries.

The count can also be expressed in the recursive form used by the authors’ argument:

Nₗ = 1 + Σₚ₌₁ˡ⁻¹ (2ⁿᵖ − 1) + 2ⁿˡ⁻¹ − 1

The initial 1 accounts for the empty coalition. Each earlier real level p supplies its nonempty extensions, represented by 2ⁿᵖ − 1. The current level contributes subsets that omit the assessed token, with the final subtraction handling the already-counted boundary context.

This calculation makes the computational dependence visible. A level containing many tokens admits many subsets. Restricting coalitions through depth reduces the calculation relative to enumerating all unrestricted feature combinations, but does not eliminate combinatorial growth within a broad level.

Apply the weighted variant

SyntaxShap-W introduces an additional preference for tokens nearer the root. The authors motivate this through the idea that upper levels often contain the sentence’s grammatical foundations, such as its main predicate and central participants.

The weight assigned to level l is:

wₗ = 1/l

The quantity wₗ is the multiplier for level l. Increasing depth reduces the multiplier. This weighting is an explicit design choice; it does not emerge from the predictor’s probability changes.

The weighted attribution becomes:

ϕᵢ = (wₗᵢ/Nᵢ) Σ₍S ∈ (⋃ₚ₌₀ˡⁱ⁻¹ 𝒮ₚ) ∪ 𝒮ₗᵢ⁽⁻ⁱ⁾₎ [fŷ(S ∪ {xᵢ}) − fŷ(S)]

The symbols match the unweighted expression, with wₗᵢ adding the inverse-depth multiplier for token xᵢ. The variant uses the same coalition structure and probability differences, then changes how strongly the resulting contribution enters the final attribution.

This makes the comparison between the variants informative. Both incorporate grammatical organization when choosing contexts. Only the weighted version additionally assumes that tree depth should directly affect the final score.

Handle words that split into several tokens

Dependency parsing and language-system tokenization need not divide a sentence into identical units. The parse operates on words, while a tokenizer may represent a word using several subtokens.

SyntaxShap addresses this by duplicating the corresponding word node in the dependency structure. Each subtoken becomes a separate node with the same grammatical role. The explanation calculation can then operate over the actual tokens supplied to the predictor.

Equal structural treatment does not mean that every subtoken must have the same measured influence. It means they inherit the same tree role rather than being assigned unrelated positions because of the tokenizer’s segmentation.

The preprocessing also excludes unsuitable inputs. The authors remove sentences whose tokenized length exceeds 15, sentences parsed into several spans, and sentences containing punctuation from the specified Python punctuation set. These choices keep the calculation manageable and the tree representation within the intended setting.

There is no training stage for SyntaxShap in these experiments. The authors explain pretrained predictors. They parse and filter the data, obtain the next-token outputs, query altered inputs, and aggregate the resulting differences. They also state that their implementation is publicly available through the project’s code and SyntaxShap website.

Understand which Shapley properties remain

SyntaxShap is inspired by Shapley values but changes the coalition game. The paper therefore examines which familiar attribution properties survive.

For a coalition S, the value function is:

v(S) = fŷ(S)

The function v assigns the coalition’s value, and fŷ is the probability of the target continuation under that retained input. The authors note that adding input tokens need not consistently raise this value.

The method does not retain efficiency: its token attributions need not add up to the complete-input value relative to the baseline. Consequently, the scores should not be read as an exhaustive partition of the prediction’s probability.

The appendix discusses symmetry within a tree level. The intended condition concerns tokens at equal depth whose marginal effects are interchangeable:

lᵢ = lⱼ and v(S ∪ {xᵢ}) = v(S ∪ {xⱼ}) for eligible S ⇒ ϕᵢ = ϕⱼ

The quantities lᵢ and lⱼ are the levels of tokens xᵢ and xⱼ. The coalition S excludes the compared tokens, v gives its output value, and ϕᵢ and ϕⱼ are their attributions. Equal depth alone does not establish equal attribution; the matching contribution condition is also needed.

Nullity is retained:

[v(S ∪ {xᵢ}) = v(S) for every eligible S] ⇒ ϕᵢ = 0

If adding token xᵢ never changes the value of an eligible coalition, its attribution is zero. The implication follows directly from averaging marginal differences that are all zero.

The paper also states additivity:

ϕᵢ(f + g) = ϕᵢ(f) + ϕᵢ(g)

Here, f and g are output functions, and ϕᵢ(f) denotes token i’s attribution when using f. The equation describes linearity of the attribution calculation under addition of those functions.

These properties clarify what the method preserves and changes. They do not, on their own, establish that its selected words will be useful under every explanation objective. The authors explicitly separate attribution axioms from the practical evaluation of feature importance.

Relate the tree structure to computational cost

The appendix contrasts the number of marginal updates with unrestricted Shapley enumeration:

UShapley = n · 2ⁿ⁻¹

UShapley is the total update count for n input features when every feature is evaluated against all subsets that exclude it. This leads to the stated complexity O(n2ⁿ).

For SyntaxShap, the corresponding count depends on the population of each tree level:

USyntaxShap = Σₗ₌₁ᴸ nₗNₗ

USyntaxShap is the total number of updates, L is the number of levels, nₗ is the number of tokens at level l, and Nₗ is the eligible-coalition count for each token at that level.

Under the appendix’s balanced-tree approximation, its resulting complexity is:

O(nL2ⁿ⁄ᴸ)

The symbols n and L retain their meanings, and O describes the growth rate under that approximation. The expression supports a structural computational advantage over unrestricted enumeration. It is not a measured runtime guarantee for every parse, particularly when a tree has an uneven distribution of tokens across levels.

Experiments and results

Prepare sentence completions from the datasets

The experiments use three collections with different linguistic characteristics. Generics contains standalone statements intended to be semantically complete. ROCStories contains everyday narratives made of five sentences. The Negation collection supplies paired sentences differing through negation.

The authors separate ROCStories narratives into individual sentences. Across the datasets, they remove the final token before obtaining a new continuation. This creates sentence prefixes for the next-token task.

The evaluation explains what the predictor outputs for those prefixes. It does not score an explanation by whether the predictor reconstructs the removed dataset token. The source sentence supplies a context, while the explanation target comes from the predictor’s own output.

The initial Negation collection contains 534 sentences, and both tokenizer-specific filters retain 534. Generics starts with 5777 sentences; filtering leaves 3568 for GPT-2 and 3328 for Mistral. ROCStories starts with 2275, with 1592 retained under the GPT-2 filter and 1543 under the Mistral filter.

These differences matter because the underlying tokenization affects which inputs satisfy the length and preprocessing requirements. The two predictors are consequently not evaluated on identical retained collections for every dataset.

The descriptives show a contrast between the general sentence collections and the negation material. Generics has a mean token count of 9.80 and 3548 unique tokens. Its dependency-distance mean is 1.96, with a standard deviation of 0.46. ROCStories has a mean token count of 9.83 and 2082 unique tokens; its corresponding distance statistics are 2.12 and 0.47.

Negation is shorter and lexically narrower. Its mean token count is 5.54, and it contains 99 unique tokens. The mean dependency distance is 1.4, with a standard deviation of 0.30. This controlled vocabulary and simpler syntax make it useful for examining semantic changes without introducing extensive grammatical variation.

Dependency distance measures how far apart linked words occur in the sentence. Averaging those separations supplies a rough description of syntactic complexity. The paper uses spaCy’s TextDescriptives component to obtain this measure.

Compare predictors and explanation methods

The authors explain GPT-2, described in the paper as having 154M parameters, and Mistral 7B, described as having 7B parameters. The comparison asks whether the attribution methods behave similarly across the two predictors.

For the qualitative analyses, the authors favor Mistral 7B because its continuations are more specific to the input context in their setting. That choice narrows the interpretation of the coherence and semantic-alignment findings: those analyses are not demonstrated across both predictors to the same extent.

The random baseline assigns normally distributed token scores. Its role is to test whether an explanation method retains more useful input evidence than an arbitrary ranking.

LIME supplies another local explanation baseline. FeatureAblation evaluates a feature by replacing it with a baseline value and observing the output change. Its individual substitutions provide a direct perturbation comparison but do not comprehensively represent interactions among several tokens.

SampleShapley approximates Shapley attribution through randomly chosen feature permutations. Partition uses hierarchical feature grouping and is presented as a faster KernelSHAP-related approach. The paper associates its implementation with the hierarchical, interaction-sensitive ideas of HEDGE.

The authors adapt these methods to text features and sequential prediction. Their comparison therefore concerns these text-generation implementations, instead of an unrestricted claim about every use of the underlying explanation techniques.

Experiments are repeated with four random seeds. The paper reports aggregate results and describes the accompanying uncertainty values as variance. The printed values can be read as reported uncertainty, but they should not be silently reinterpreted as another statistical quantity.

Test whether retained words preserve the prediction

The main faithfulness evaluation ranks input tokens by their attribution and retains the highest-scoring fraction. It then asks how much the predictor’s output changes when the remaining tokens are masked.

The paper’s fidelity measure is:

Fid(t) = (1/N) Σᵢ₌₁ᴺ [fŷ(xᵢ) − fŷ(x̃ᵢ⁽ᵗ⁾)]

Here, N is the number of evaluated examples, xᵢ is an original input, and x̃ᵢ⁽ᵗ⁾ is its altered version retaining the top t% of input words according to the explanation. The symbol ŷ is the original predicted continuation for that example, and fŷ gives its probability.

A smaller decrease means that the retained tokens preserve more of the original target probability. Under this evaluation, that supports the claim that the explanation ranked influential evidence highly.

The paper also considers Fid_rand, which uses random vocabulary replacements for removed tokens. Its role is to test whether conclusions depend on how feature absence is represented.

For explanation masks, the main implementation follows the SHAP library’s attention-mask approach. A token marked as absent has its attention contribution suppressed. This simulates removal without requiring the remaining tokens to be physically concatenated into a newly shortened sentence.

The evaluation tests random replacements as an alternative. This distinction is substantive because a random word can introduce fresh content, whereas attention masking aims to suppress the original token’s contribution.

Examine more than the leading continuation

The authors argue that inspecting only the most likely continuation gives an incomplete picture of a probabilistic predictor. Several next tokens can be plausible, including semantically related alternatives.

They therefore introduce probability divergence across the leading candidates:

div@K = (1/N) Σᵢ₌₁ᴺ Σₖ₌₀ᴷ [fŷₖ(xᵢ) − fŷₖ(x̃ᵢ⁽ᵗ⁾)]

The quantity div@K aggregates changes in probability over the original leading predictions. The token ŷₖ is the candidate at rank k for the unmasked input, K sets the candidate range, and the remaining symbols have the same meanings as in fidelity. The paper prints the rank summation beginning at 0 while describing the measure through the top K predictions.

The experiments choose K = 10. The motivation is that a sentence can support several plausible completions, so preserving probability over a candidate group can be more informative than preserving only a single token.

The associated overlap measure is:

acc@K = (1/N) Σᵢ₌₁ᴺ |{ŷₖ : k ≤ K} ∩ {ỹₖ⁽ᵗ⁾ : k ≤ K}| / K

The set containing ŷₖ represents leading predictions for the complete input. The set containing ỹₖ⁽ᵗ⁾ represents leading predictions for the masked input. The intersection symbol ∩ selects shared candidates, and the surrounding bars count them. Dividing by K gives the retained proportion, which is then averaged over examples.

Higher acc@K indicates that more leading candidates survive the masking intervention. Lower div@K indicates a smaller aggregate probability change under the paper’s reporting convention.

The measures address related but distinct behavior. Candidate overlap can remain high even when probability values shift. Conversely, a probability comparison provides information that the identity of the leading token alone would conceal.

Mistral 7B favors syntax-aware attribution

The detailed numeric comparison reports div@10 at threshold t = 0.5, retaining 50% of the highest-ranked words. The faithfulness analysis covers the filtered sentence-length setting between 5 and 15 tokens.

On Mistral 7B’s Negation evaluation, the weighted variant gives the smallest reported divergence. The chart shows the mean values; the paper also reports uncertainty alongside them.

Mistral 7B on Negation, div@10 with 50% retained

The weighted syntax-aware method preserves the candidate probabilities most closely in this comparison.

Mistral 7B on Negation, div@10 with 50% retainedRandom: 0.574Random0.574LIME: 0.577LIME0.577FeatureAblation: 0.594FeatureAblation0.594SampleShapley: 0.684SampleShapley0.684Partition: 0.599Partition0.599SyntaxShap: 0.499SyntaxShap0.499SyntaxShap-W (this paper): 0.449SyntaxShap-W (this paper)0.449
The numbers
System or settingdiv@10
Random0.574
LIME0.577
FeatureAblation0.594
SampleShapley0.684
Partition0.599
SyntaxShap0.499
SyntaxShap-W (this paper)0.449

For the syntax-based methods in this setting, the reported uncertainty is ±0.002 for SyntaxShap and ±0.001 for SyntaxShap-W. Their advantage is consistent with the paper’s broader finding that grammatical coalition restrictions work well for explaining this predictor.

The preferred variant changes on Generics:

Mistral 7B on Generics, div@10 with 50% retained

The unweighted syntax-aware method leads, showing that inverse-depth weighting is not uniformly beneficial.

Mistral 7B on Generics, div@10 with 50% retainedRandom: 0.711Random0.711LIME: 0.689LIME0.689FeatureAblation: 0.760FeatureAblation0.760SampleShapley: 0.786SampleShapley0.786Partition: 0.708Partition0.708SyntaxShap (this paper): 0.638SyntaxShap (this paper)0.638SyntaxShap-W: 0.674SyntaxShap-W0.674
The numbers
System or settingdiv@10
Random0.711
LIME0.689
FeatureAblation0.760
SampleShapley0.786
Partition0.708
SyntaxShap (this paper)0.638
SyntaxShap-W0.674

The reported uncertainty for SyntaxShap on this dataset is ±0.007, while SyntaxShap-W has ±0.002. The lower mean for the unweighted version shows that a useful coalition structure does not automatically make an additional depth preference useful.

Mistral 7B’s ROCStories results point in the same direction. SyntaxShap records 0.612 ±0.005, while the weighted version records 0.637 ±0.004. Partition gives 0.667 ±0.007, and LIME gives 0.660 ±0.004.

The other comparisons also favor the syntax-based methods on this dataset. The random baseline records 0.657 ±0.002. FeatureAblation gives 0.705 ±0.007, and SampleShapley gives 0.723 ±0.004.

Taken together, these results support the paper’s claim that syntax-guided coalitions improve faithfulness for Mistral 7B under the tested interventions. They also show why the weighted and unweighted methods should be discussed separately: their relative ordering depends on the dataset.

GPT-2 changes the ranking

The GPT-2 results prevent a universal superiority claim. On Generics, FeatureAblation achieves the smallest reported divergence, with SampleShapley also ahead of either syntax-based method.

GPT-2 on Generics, div@10 with 50% retained

Feature ablation leads this setting, while the syntax-aware methods still improve on the random, local-surrogate, and partition baselines.

GPT-2 on Generics, div@10 with 50% retainedRandom: 0.572Random0.572LIME: 0.590LIME0.590FeatureAblation: 0.257FeatureAblation0.257SampleShapley: 0.283SampleShapley0.283Partition: 0.546Partition0.546SyntaxShap (this paper): 0.350SyntaxShap (this paper)0.350SyntaxShap-W: 0.429SyntaxShap-W0.429
The numbers
System or settingdiv@10
Random0.572
LIME0.590
FeatureAblation0.257
SampleShapley0.283
Partition0.546
SyntaxShap (this paper)0.350
SyntaxShap-W0.429

The star identifies the paper’s unweighted method. It does not indicate that this method has the best value across the chart.

On GPT-2’s ROCStories evaluation, FeatureAblation records 0.253 ±0.007 and SampleShapley records 0.284 ±0.007. SyntaxShap gives 0.357 ±0.002, while SyntaxShap-W gives 0.414 ±0.005. The latter methods remain ahead of Partition at 0.551 ±0.006 and LIME at 0.591 ±0.002.

For GPT-2 on Negation, FeatureAblation records 0.239 ±0.001 and SampleShapley records 0.251 ±0.004. SyntaxShap-W gives 0.259 ±0.005, and SyntaxShap gives 0.273 ±0.002.

The relevant conclusion is conditional. SyntaxShap improves on several baselines across the reported evaluations and is particularly strong for Mistral 7B. It does not outperform every competing explanation method for every predictor.

The authors emphasize that independent ablation can overlook correlated tokens even when its faithfulness metric is favorable. That is a reason to examine several explanation criteria. It does not cancel the better GPT-2 scores achieved by those baselines.

What the ablations show

The paper offers a comparison between weighted and unweighted attribution, controlled negation analyses, masking checks, and breakdowns by sentence length and dependency distance; it does not present a comprehensive ablation of alternative coalition rules.

Weighting helps selectively

Comparing SyntaxShap with SyntaxShap-W holds the permitted-coalition mechanism fixed and changes the multiplier applied according to tree depth. This is the clearest controlled comparison of a method component.

For Mistral 7B on Negation, inverse-depth weighting improves the reported divergence. On Generics and ROCStories, the unweighted method performs better. For GPT-2, weighting similarly has different consequences across the datasets.

The comparison supports a useful distinction between using syntax to select contexts and using syntax to impose an importance preference. The first is shared by both methods. The second appears only in SyntaxShap-W and is not consistently beneficial.

A word’s distance from the root therefore cannot substitute for measuring its effect on the target probability. The weighted method still measures that effect, but its structural multiplier changes the resulting ranking. Whether this improves retained-input faithfulness depends on the evaluated predictor and data.

The experiments do not establish an optimal weighting function. They test the specified inverse-level rule. They also do not show whether another grammatical property would provide a better multiplier.

Coherency asks whether explanations track prediction changes

The coherency analysis uses pairs from the Negation dataset. Each pair contains a small grammatical alteration with a potentially large semantic effect, such as inserting not or contrasting with and without.

The authors select 267 sentence pairs for Mistral 7B. In 90 pairs, the predictor produces the same next token in spite of the alteration. Other pairs produce different next tokens.

The evaluation’s expectation is conditional on that behavior. If the continuation remains equal, the authors expect the explanation patterns to be more similar. If the continuation changes, they expect greater variation between the explanations.

This is not the same as requiring the predictor to handle negation correctly. A pair may receive an identical continuation even though a person would consider that continuation inappropriate for one member. The coherency question is whether attribution patterns reflect the predictor’s observed response.

The procedure first converts attribution values into token ranks. A rank representation focuses on the ordering of token importance rather than the absolute scale of the scores.

Negation words are excluded from the paired rank vectors so that the remaining vectors have matching lengths. The authors then calculate cosine similarity between the vectors for each pair.

The pairs are separated according to whether their next-token predictions match. The analysis compares average similarity between these groups. A coherent explanation method should show stronger resemblance for the equal-prediction group than for the different-prediction group.

SyntaxShap and its weighted variant provide a clearer separation under this criterion than the competing methods discussed in the paper. Their attribution patterns are more alike when the prediction stays equal and more varied when it changes.

The result adds evidence beyond retained-input probability preservation. It suggests that the syntax-based explanations respond systematically to a controlled alteration in the input and to its effect on the output.

However, the criterion remains an operational test. Equal leading tokens do not imply identical probability distributions or identical internal processing. Different leading tokens can also arise from a modest change among close alternatives. Coherency as measured here captures a useful behavioral relationship, rather than a complete account of the underlying computation.

Semantic alignment exposes a different expectation

The semantic-alignment analysis asks whether explanations fit a particular human interpretation of negation failures. The authors collect negative sentences containing not, no, or without and label cases whose predicted continuation does not respect the negation.

For Mistral 7B, the resulting analysis includes 22 labeled instances. The authors inspect the importance rank assigned to the negation token.

Their starting expectation is intuitive: when the completion appears to disregard negation, the negation word should seem unimportant to that prediction. Under this expectation, a high numerical rank, meaning a position farther down the importance ordering, would count as better semantic alignment.

SyntaxShap produces a strikingly different pattern. The syntax-based methods place negation at the top of the importance ranking in more than 80% of the analyzed cases.

This finding is especially consequential because those methods also perform well on faithfulness for Mistral 7B’s Negation data. The disagreement cannot be dismissed simply as the behavior of an explanation method that fails the paper’s predictive tests.

The result makes the meaning of attribution more precise. A token can influence the probability of an unsuitable continuation. Influence does not require the predictor to use the token in the linguistically appropriate way.

For instance, a negation token could change the distribution while still leaving an affirmative-looking continuation in the leading position. The paper’s analysis does not identify the internal mechanism behind such behavior. It shows that the expectation “a failed semantic effect implies low token influence” does not reliably match the attribution outcome.

This supports the authors’ distinction between explanations evaluated for agreement with the predictor and explanations evaluated for agreement with human expectations. These objectives can diverge, and the evaluation should make that divergence visible.

The finding also limits what can be inferred from a heat map. A prominently highlighted negation token does not establish correct understanding of negation. Equally, a semantically inappropriate completion does not establish that the token had no measurable effect.

Masking choices preserve the main comparisons

The masking analysis compares suppressing attention for excluded tokens with replacing them using randomly chosen vocabulary tokens.

For Mistral 7B, the authors report little difference between these strategies. For GPT-2, random substitutions make explanations somewhat less faithful than the attention-masking alternative.

The paper offers a contextual explanation: introducing random words changes the surrounding representation and can alter the role of the words that remain. That makes replacement more than a neutral simulation of absence.

Despite this effect, the relative ordering of explanation methods remains consistent in the reported comparisons. The main conclusion is therefore not confined to only one of these masking choices.

This check is valuable because faithfulness is defined through an intervention. A method may appear effective partly because its selected words interact favorably with a particular way of suppressing everything else. Testing another intervention helps assess whether the comparison is fragile.

The evidence does not settle which masking strategy is best in general. It establishes that these alternatives lead to similar comparative conclusions within the paper’s setting.

Sentence length does not reveal a collapse within the tested range

The appendix groups examples by token count to examine whether explanation quality deteriorates as inputs become longer. The text describes a range from 5 to 15 tokens and requires at least 50 examples of a given length for the Generics and ROCStories averages.

The authors report that the explanation methods remain comparatively stable as token count increases across this range. SyntaxShap does not show an obvious loss of faithfulness merely because a sentence is longer within the retained data.

This is a bounded robustness result. It concerns short inputs selected by the preprocessing filters. It does not demonstrate that computation or explanation quality remains stable for substantially longer sentences.

Length also differs from grammatical difficulty. A short sentence can contain a difficult dependency, while a longer sentence can have a comparatively simple structure. The dependency-distance analysis addresses another aspect of this variation.

Dependency distance offers only partial evidence about complexity

The authors group sentences by average dependency distance, using the separation between linked words as an indicator of syntactic complexity.

For Generics, the reported faithfulness curves remain broadly stable across the examined ranges. For ROCStories, the plots suggest somewhat lower faithfulness at greater complexity.

The authors explicitly caution against treating the ROCStories pattern as a reliable trend. Its extreme distance groups contain very few observations: the appendix discusses 3 sentences at the low end and 7 at the high end.

Sparse groups make it difficult to distinguish a systematic relationship from the behavior of a few unusual examples. The analysis therefore does not establish that increasing dependency distance causes an explanation method to become less faithful.

This is an appropriately restrained result. The paper investigates the possibility and identifies why the available data do not resolve it. Its stronger evidence concerns comparative performance on the main retained collections, instead of a general law connecting syntactic complexity with explanation quality.

Limitations

Author-stated limits: sentence scope and parser reliability

The authors explicitly restrict their analysis to a single input sentence because the method works with a dependency tree for that sentence. This is a substantial boundary for a method presented in the context of text generation.

A next token can depend on information introduced earlier in a paragraph or conversation. The experiments do not test whether SyntaxShap can attribute such dependencies across sentence boundaries.

The authors suggest processing several sentences through separate trees and running their method in parallel. They also acknowledge the resulting problem: treating the trees separately may lose relationships between sentences.

The proposal therefore describes a possible extension, instead of a demonstrated solution. Combining sentence-level explanations would require care when the important evidence lies in their interaction.

Parser reliability is the other explicit limitation. SyntaxShap assumes that its dependency tree is a useful account of the input’s grammatical organization.

The authors note that spaCy can produce analyses that a linguist might dispute. Since the tree determines which coalitions are examined, a parsing error can affect the explanation even if the predictor’s probability estimates are otherwise obtained correctly.

This dependence is stronger than using a parse only to annotate a finished heat map. Here, the parse shapes the evidence gathered during the attribution calculation. An incorrect structure can exclude informative contexts or impose an inappropriate ordering on coalition construction.

The authors further state that parser performance declines outside English in their intended use. They consequently limit the method’s current scope to English sentences with relatively uncomplicated grammar.

That restriction should accompany claims of linguistic generality. The paper motivates syntax as a broad property of language, but its empirical support concerns the tested English setting and its available parsing tools.

Author-stated concerns: stochastic outputs and human interpretation

The discussion acknowledges that next-token generation has a probabilistic character that familiar explanation metrics do not fully capture.

The proposed div@K and acc@K measures address this by examining a candidate group rather than only the leading token. They provide a broader output view, but the authors call for further evaluation methods suited to stochastic generation.

Their discussion also proposes more linguistically informed evaluation. Next-token candidates have different grammatical and semantic roles. A shift among related content words may differ from a shift between a function word and a content word, even if a probability-based metric treats both as changes in candidate identity.

The paper does not implement a complete evaluation framework for these distinctions. It identifies them as useful directions for later work.

The authors also warn about false rationalization: people may interpret an explanation as confirming an ordinary linguistic story even when the predictor behaves differently.

SyntaxShap’s negation analysis illustrates the concern. A faithful attribution can conflict with the expectation that an apparently disregarded word must have had little influence. The authors argue that future explanations should help people understand both the token’s influence and the reason it may not match their expectations.

The ethics statement adds that explanations can reflect biases already present in the pretrained predictors. Faithful attribution does not remove those biases or make the resulting continuation desirable.

It also does not ensure harmless use. An explanation can accurately characterize behavior while still being misunderstood or used to support an unsuitable application. The paper raises this concern without demonstrating a particular deployment outcome.

Setup-based limits: what is actually explained

A careful reading of the experimental design reveals additional boundaries. The method is evaluated on an immediate next-token prediction, not on an entire generated response.

This matters because an attribution to one continuation cannot automatically explain a later sequence. Each generated token changes the context available for subsequent prediction. The experiments do not trace how attributions evolve through a paragraph or how several locally explained decisions combine into an overall response.

The data preparation also favors sentence-completion settings. Removing a final token from an existing sentence provides a convenient prefix, but it does not represent every kind of input used in generation.

The retained inputs exclude punctuation and cases parsed into multiple spans. Those filters remove sources of structural difficulty while making the tree-based calculation more manageable.

The length ceiling of 15 tokens further narrows the evidence. The sentence-length analysis shows stability within a short-input range, while the preprocessing itself acknowledges computational limits beyond that range.

These conditions do not invalidate the comparison. They identify the setting in which it has been demonstrated. Extending the result to longer prompts or structurally complicated language would require new evidence.

The predictor comparison is similarly bounded. The paper studies GPT-2 and Mistral 7B, and its qualitative evaluation emphasizes the latter. The differing faithfulness rankings show that explanation performance can depend on which predictor is being examined.

The experiments do not establish a simple relationship between parameter count and the value of syntax-aware attribution. Parameter count differs, but many other properties differ as well. The results support separate observations about the tested predictors rather than a general scaling explanation.

Setup-based limits: faithfulness depends on the intervention

The faithfulness procedure evaluates whether selected words preserve an output after the rest of the input is suppressed or replaced. This is a practical test of an explanation ranking, but it relies on altered inputs.

Such inputs need not resemble ordinary sentences encountered during generation. Even a linguistically motivated coalition can omit material needed for a natural utterance. Its prediction therefore measures behavior under the explanation intervention.

The masking comparison reduces concern that the main ranking is unique to one implementation of absence. It does not eliminate all dependence on intervention design.

The interpretation of div@K also requires care. Its formula aggregates signed probability changes across the original leading candidates. It is not presented as an absolute-distance measure over the complete vocabulary distribution.

As a consequence, a favorable value should be understood through the paper’s specific metric. It should not be expanded into a claim that every aspect of the full output distribution has been preserved.

Similarly, acc@K records shared candidate identities. It does not assess whether those candidates are semantically correct, interchangeable, or appropriate for the input.

The results are strongest when these distinctions remain explicit: the tests measure preservation of selected predictive properties after masking. They do not independently verify grammatical understanding, factual correctness, or human usefulness.

Setup-based limits: syntax is a prior, not a recovered mechanism

The dependency tree comes from an external parser. SyntaxShap does not infer the predictor’s actual internal grammatical representation.

Its success therefore shows that an externally supplied syntactic organization can help produce useful attributions under the tested criteria. It does not establish that the predictor follows the same tree or processes words in the same level order.

The weighted variant adds an even more direct linguistic preference. Reducing scores by depth assumes that upper-tree positions deserve greater emphasis. The mixed results show that this preference can help or hurt relative to the unweighted calculation.

The theoretical analysis also changes familiar expectations about attribution. Efficiency is not retained, so the scores do not form a complete additive allocation of the full prediction value.

A reader should therefore avoid treating each score as a conserved share of a single total. The values summarize marginal effects over a restricted coalition family.

The complexity analysis is an approximation based on tree shape. It supports the motivation for restricting coalitions, but it does not provide a benchmark of runtime across all relevant sentence structures.

The paper also does not isolate every possible structural alternative. Without comparisons to other level rules, parser variants, or equally sized nonsyntactic coalition families, the evidence cannot identify which aspect of the restriction accounts for all of the observed improvement.

Setup-based limits: human alignment remains narrowly tested

The semantic-alignment evaluation uses a small, specifically selected group of negation failures. Its 22 labeled cases provide a revealing diagnostic, but they do not establish how explanations behave across every semantic phenomenon.

The task also operationalizes human expectation through the authors’ stated assumption about ignored negation. It is not a user study measuring whether readers understand the predictor better after receiving SyntaxShap explanations.

Similarly, the coherency measure is based on rank-vector similarity and equality of the leading predicted token. It supplies a reproducible behavioral comparison, but it does not measure comprehension, appropriate reliance, or decision quality.

These are different objectives. An explanation can rank influential words well yet fail to communicate why a continuation is inappropriate. It can also look intuitive while poorly reflecting the predictor’s response to altered inputs.

The paper’s strongest contribution on this point is to expose the distinction. Its experiments do not resolve how to design an explanation that is simultaneously faithful, semantically informative, and useful to a person in a consequential task.

What came after

A Primer on the Inner Workings of Transformer-based Language Models is listed as a later work citing SyntaxShap. The available citation information gives its title and year, 2024, but does not describe its treatment of the method.

That record establishes a connection in the subsequent literature. It does not establish that the primer implemented syntax-constrained coalitions, evaluated the weighted variant, adopted the proposed metrics, or extended the negation analysis. A more specific account of how it built on SyntaxShap would require evidence beyond the citation entry.

The supported account of subsequent work is therefore limited. SyntaxShap entered a broader discussion of how to understand transformer-based language systems, but the citation information does not demonstrate an independent replication or a technical extension.

The unresolved questions remain those made concrete by the original study: whether syntax-guided attribution works beyond short, simply parsed English inputs; how it should be evaluated for probabilistic generation; and how an explanation can make predictive influence understandable when that influence conflicts with ordinary semantic expectations.

Cite

Cite as Kenza Amara, Rita Sevastjanova and Mennatallah El-Assady. 2024. SyntaxShap: Syntax-aware Explainability Method for Text Generation. Findings of the Association for Computational Linguistics: ACL 2024.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2024.findings-acl.270

@inproceedings{amara2024syntaxshap,
  title = {{SyntaxShap: Syntax-aware Explainability Method for Text Generation}},
  author = {Kenza Amara, Rita Sevastjanova and Mennatallah El-Assady},
  booktitle = {Findings of the Association for Computational Linguistics: ACL 2024},
  year = {2024},
  doi = {10.18653/v1/2024.findings-acl.270},
  url = {https://doi.org/10.18653/v1/2024.findings-acl.270}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/amara-2024-syntaxshap-syntax-aware-explainability-method/