SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2402.09259 · 2024

SyntaxShap: Syntax-aware Explainability Method for Text Generation

arXiv · PDF · Open in the Atlas

Code that ran

8 of 13 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 2 honoured the contract we drafted, 3 violated it and 0 have no contract verdict; 3 failures of our instrument; 5 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2402.09259.json · badge: /api/ran/2402.09259.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
k-amara/syntax-shap canonical (classifier label)
classifier basis: census
8 ran · 5 no recorded run
FunctionStatusWhere it lives
compute_output_dims Ran
ran, honoured the contract we drafted
k-amara/syntax-shap/syntaxshap/_explanation.py
code served (permissive licence) · get_code("ede50da320fa78ec")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family int; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np
import scipy.sparse

def _first_item(x):
    for item in x:
        return item
    return None

def _compute_shape(x):
    if not hasattr(x, '__len__') or isinstance(x, str):
        return tuple()
    elif not scipy.sparse.issparse(x) and len(x) > 0 and isinstance(_first_item(x), str):
        return (None,)
    else:
        if isinstance(x, dict):
            return (len(x),) + _compute_shape(x[next(iter(x))])
        if len(getattr(x, 'shape', tuple())) > 1:
            return x.shape
        if len(x) == 0:
            return (0,)
        elif len(x) == 1:
            return (1,) + _compute_shape(_first_item(x))
        else:
            first_shape = _compute_shape(_first_item(x))
            if first_shape == tuple():
                return (len(x),)
            else:
                matches = np.ones(len(first_shape), dtype=bool)
                for i in range(1, len(x)):
                    shape = _compute_shape(x[i])
                    assert len(shape) == len(first_shape), 'Arrays in Explanation objects must have consistent inner dimensions!'
                    for j in range(0, len(shape)):
                        matches[j] &= shape[j] == first_shape[j]
                return (len(x),) + tuple((first_shape[j] if match else None for j, match in enumerate(matches)))

# Create test data with distinct dimensions for clarity
batch_size = 2
data_dim = 4
output_dim = 3

# values: shape (batch_size, data_dim, output_dim) - model output with batch, feature, and output dims
values = np.random.randn(batch_size, data_dim, output_dim)

# base_values: shape (1, data_dim, output_dim) - baseline for comparison
base_values = np.random.randn(1, data_dim, output_dim)

# data: shape (batch_size, data_dim) - input data
data = np.random.randn(batch_size, data_dim)

# output_names: list of output names matching output dimension
output_names = ["output_0", "output_1", "output_2"]

ARGS = {
    "values": values,
    "base_values": base_values,
    "data": data,
    "output_names": output_names
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, scipy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family int — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
convert_feat_to_mask Ran
ran; our contract draft was wrong, not the code
k-amara/syntax-shap/syntaxshap/explainers/_syntax.py
code served (permissive licence) · get_code("df7238e59087c763")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned ndarray, ndim 1, dtype family float, shape (7,) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np

# The function takes two parameters:
# - feature: used as an index into mask array (np.zeros(m))
# - m: the size of the mask array to create

# From the function body:
# mask = np.zeros(m)  -> m should be an integer
# mask[feature] = 1   -> feature should be a valid index or array of indices

ARGS = {
    "feature": np.array([0, 2, 4]),  # array of indices to set to 1
    "m": 7,  # size of the mask
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family float, shape (7,) — shape (7,) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
generate_explanatory_masks Ran
ran; our contract draft was wrong, not the code
k-amara/syntax-shap/syntaxshap/metrics.py
code served (permissive licence) · get_code("fabf25aaf5b6c859")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 2, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np
from typing import List, Optional

class SimpleTokenizer:
    """Minimal tokenizer that splits on whitespace."""
    def tokenize(self, text):
        return text.split()

# Set up inputs
str_inputs = [
    "hello world test prompt",
    "another sample text here"
]

# Create shapley_scores as a list of lists of arrays
# For each input string, we have arrays corresponding to each token
# Each array has shape (vocab_size,) - we'll use vocab_size=5
shapley_scores = [
    [np.array([0.1, 0.5, 0.3, 0.2, 0.4]),
     np.array([0.2, 0.6, 0.1, 0.3, 0.5]),
     np.array([0.3, 0.4, 0.2, 0.6, 0.1]),
     np.array([0.4, 0.3, 0.5, 0.1, 0.2])],
    [np.array([0.5, 0.2, 0.4, 0.3, 0.1]),
     np.array([0.1, 0.5, 0.3, 0.2, 0.4]),
     np.array([0.2, 0.6, 0.1, 0.3, 0.5]),
     np.array([0.3, 0.4, 0.2, 0.6, 0.1])]
]

tokenizer = SimpleTokenizer()
k = 0.5  # Use 50% of tokens
next_token_id = 1  # Focus on token ID 1

ARGS = {
    "str_inputs": str_inputs,
    "shapley_scores": shapley_scores,
    "k": k,
    "tokenizer": tokenizer,
    "next_token_id": next_token_id
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 2, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
identity Ran
ran, violated the contract we drafted
k-amara/syntax-shap/syntaxshap/links.py
code served (permissive licence) · get_code("2553ac83ca78410e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned ndarray, ndim 1, dtype family float, shape (4,) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numba
import numpy as np

@numba.njit
def identity(x):
    """ A no-op link function.
    """
    return x

# The function takes a single parameter 'x' and returns it unchanged.
# It's a simple no-op function that works with numba.
# We need to pass something that numba can handle - typically a numeric array.

x_value = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float64)

ARGS = {
    "x": x_value
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numba, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family float, shape (4,) — shape (4,) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
is_1d Ran
ran, violated the contract we drafted
k-amara/syntax-shap/syntaxshap/_explanation.py
code served (permissive licence) · get_code("e3c7e31f2f094463")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np

# Test case 1: 1D list of scalars
val_1d_list = [1, 2, 3, 4]

# Test case 2: 1D numpy array
val_1d_array = np.array([1, 2, 3, 4])

# We'll use the 1D list case for ARGS
ARGS = {
    "val": val_1d_list
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
logit Ran
ran, violated the contract we drafted
k-amara/syntax-shap/syntaxshap/links.py
code served (permissive licence) · get_code("fecc5a713db5e4c9")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned ndarray, ndim 1, dtype family float, shape (4,) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np
import numba

# The logit function takes a single parameter x
# It computes log(x / (1 - x)), which requires x to be in (0, 1)
# x should be a numpy array or scalar with values strictly between 0 and 1

# Create a small numpy array with values in the valid range (0, 1)
x = np.array([0.2, 0.5, 0.7, 0.9])

ARGS = {
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numba, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family float, shape (4,) — shape (4,) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
padleft_mask Ran
ran, honoured the contract we drafted
k-amara/syntax-shap/syntaxshap/metrics.py
code served (permissive licence) · get_code("5d10648588a144ac")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 2, dtype family float, shape (3, 5) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np
import torch

torch.manual_seed(0)

# Create sample masks - list of optional numpy arrays with different lengths
masks = [
    np.array([1.0, 1.0, 1.0]),
    np.array([1.0, 1.0]),
    None
]

# Replace None with a valid mask for testing
masks = [
    np.array([1.0, 1.0, 1.0]),
    np.array([1.0, 1.0]),
    np.array([1.0])
]

max_length = 5

ARGS = {
    "masks": masks,
    "max_length": max_length
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (3, 5) — shape (3, 5) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
save_path Ran
ran; our contract draft was wrong, not the code
k-amara/syntax-shap/syntaxshap/explain.py
code served (permissive licence) · get_code("6bd33d5cb64c00c4")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import os

class Args:
    def __init__(self):
        self.result_save_dir = '/tmp/test_results'
        self.model_name = 'resnet50'
        self.dataset = 'cifar10'
        self.algorithm = 'lime'
        self.seed = 42
        self.num_batch = 5

ARGS = {
    'args': Args()
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
california Not yet run
unverified (harvested, no recorded run)
k-amara/syntax-shap/syntaxshap/datasets.py
code served (permissive licence) · get_code("2a27f190c3200160")
How it ran

no invocation recorded.

imagenet50 Not yet run
unverified (harvested, no recorded run)
k-amara/syntax-shap/syntaxshap/datasets.py
code served (permissive licence) · get_code("120b0748cd14efa4")
How it ran

no invocation recorded.

load_model Not yet run
unverified (harvested, no recorded run)
k-amara/syntax-shap/syntaxshap/model.py
code served (permissive licence) · get_code("473e8cfc361163dc")
How it ran

no invocation recorded.

weight_matrix Not yet run
unverified (harvested, no recorded run)
k-amara/syntax-shap/syntaxshap/explainers/_syntax.py
code served (permissive licence) · get_code("eda4531c0d51f914")
How it ran

no invocation recorded.

weight_matrix_subset Not yet run
unverified (harvested, no recorded run)
k-amara/syntax-shap/syntaxshap/explainers/_syntax.py
code served (permissive licence) · get_code("725b5bebc44ac43b")
How it ran

no invocation recorded.

Also present in other papers' code

Of 13 samples lifted from this paper's linked repositories, 13 carry a function identity and 0 do not. Of the 13 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 0 later) and 12 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
is_1d 1 other paper
1 dated earlier
2212.08158 (2022-12)
MM-SHAP: A Performance-agnostic Metric for Measuring Multimodal Contributions in Vision and Language Models & Tasks

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

To harness the power of large language models in safety-critical domains, we need to ensure the explainability of their predictions. However, despite the significant attention to model interpretability, there remains an unexplored domain in explaining sequence-to-sequence tasks using methods tailored for textual data. This paper introduces SyntaxShap, a local, model-agnostic explainability method for text generation that takes into consideration the syntax in the text data. The presented work extends Shapley values to account for parsing-based syntactic dependencies. Taking a game theoric approach, SyntaxShap only considers coalitions constraint by the dependency tree. We adopt a model-based evaluation to compare SyntaxShap and its weighted form to state-of-the-art explainability methods adapted to text generation tasks, using diverse metrics including faithfulness, coherency, and semantic alignment of the explanations to the model. We show that our syntax-aware method produces explanations that help build more faithful and coherent explanations for predictions by autoregressive models. Confronted with the misalignment of human and AI model reasoning, this paper also highlights the need for cautious evaluation strategies in explainable AI.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2402.09259")
get_code_for_paper("2402.09259")
have("2402.09259")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2402.09259.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2402.09259.svg)](https://syntology.ai/paper/2402.09259)

Connect an agent — have() is free.