SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2407.10114 · 2024

TokenSHAP: Interpreting Large Language Models with Monte Carlo Shapley Value Estimation

arXiv · PDF · Open in the Atlas

Code that ran

9 of 12 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; 1 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 8 failures of our instrument; 3 no recorded run), measured 2026-11-23; 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/2407.10114.json · badge: /api/ran/2407.10114.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
ronigold/TokenSHAP canonical (classifier label)
classifier basis: census
9 ran · 3 no recorded run
FunctionStatusWhere it lives
create_function_tool Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/tools.py
code served (permissive licence) · get_code("0f76828d9d9164c6")
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 Tool. 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 torch
import numpy as np
from typing import Dict, Any, Callable

torch.manual_seed(0)

# Create a simple executor function that simulates weather lookup
def weather_executor(args: Dict[str, Any]) -> str:
    city = args.get("city", "Unknown")
    return f"Weather in {city}: 72°F, sunny"

# Create parameters schema
parameters = {
    "type": "object",
    "properties": {
        "city": {
            "type": "string",
            "description": "The city to get weather for"
        },
        "units": {
            "type": "string",
            "description": "Temperature units (celsius or fahrenheit)",
            "enum": ["celsius", "fahrenheit"]
        }
    },
    "required": ["city"]
}

ARGS = {
    "name": "get_weather",
    "description": "Get the current weather for a specified city",
    "parameters": parameters,
    "executor": weather_executor
}
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 Tool — a Tool output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Tool 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
create_tool_from_function Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/tools.py
code served (permissive licence) · get_code("679886c1e77b60bf")
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 Tool. 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 torch
import numpy as np
from typing import Dict, Any, Optional, Callable

# Define a simple function to wrap as a tool
def get_user_info(user_id: str) -> str:
    """Get information about a user from the database"""
    return f"User {user_id}: John Doe, Active"

# Build the parameters schema
parameters = {
    "type": "object",
    "properties": {
        "user_id": {
            "type": "string",
            "description": "The unique identifier of the user"
        }
    },
    "required": ["user_id"]
}

# Construct ARGS dict
ARGS = {
    "func": get_user_info,
    "name": "get_user_info",
    "description": "Retrieve user information by user ID",
    "parameters": parameters
}
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 Tool — a Tool output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Tool 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
encode_image_to_base64 Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/base.py
code served (permissive licence) · get_code("bc481c4457599f4a")
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 base64
import tempfile
import os

# Create a temporary image file for testing
# We'll create a minimal valid PNG file
temp_dir = tempfile.gettempdir()
image_path = os.path.join(temp_dir, "test_image.png")

# Minimal valid PNG file (1x1 transparent pixel)
png_bytes = bytes([
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,  # PNG signature
    0x00, 0x00, 0x00, 0x0D,  # IHDR chunk length
    0x49, 0x48, 0x44, 0x52,  # IHDR
    0x00, 0x00, 0x00, 0x01,  # width: 1
    0x00, 0x00, 0x00, 0x01,  # height: 1
    0x08, 0x06, 0x00, 0x00, 0x00,  # bit depth, color type, etc.
    0x1F, 0x15, 0xC4, 0x89,  # CRC
    0x00, 0x00, 0x00, 0x0A,  # IDAT chunk length
    0x49, 0x44, 0x41, 0x54,  # IDAT
    0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01,  # compressed data
    0x0D, 0x0A, 0x2D, 0xB4,  # CRC
    0x00, 0x00, 0x00, 0x00,  # IEND chunk length
    0x49, 0x45, 0x4E, 0x44,  # IEND
    0xAE, 0x42, 0x60, 0x82,  # CRC
])

with open(image_path, 'wb') as f:
    f.write(png_bytes)

ARGS = {
    'image_path': image_path
}
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
get_text_before_last_underscore Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/base.py
code served (permissive licence) · get_code("41fd7230cab35fe6")
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 torch

def get_text_before_last_underscore(token):
    return token.rsplit('_', 1)[0]

ARGS = {
    'token': 'hello_world_test'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — 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
get_text_before_last_underscore Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/token_shap.py
code served (permissive licence) · get_code("5ad9e221f5b454a9")
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 torch

torch.manual_seed(0)

ARGS = {
    "token": "layer_output_weights"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — 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
load_database Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/experiments/agentshap/exp6_model_comparison.py
code served (permissive licence) · get_code("62fa5ab915e9b213")
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 dict. 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 json
from pathlib import Path
from unittest.mock import patch, MagicMock
import tempfile
import os

# Create a temporary directory structure to simulate the expected paths
temp_dir = tempfile.mkdtemp()
experiment_dir = Path(temp_dir)
apibank_dir = experiment_dir / 'DAMO-ConvAI' / 'api-bank'
database_dir = apibank_dir / 'init_database'
database_dir.mkdir(parents=True, exist_ok=True)

# Create a sample database file
sample_db = {
    "api_1": {"name": "example_api", "endpoint": "https://api.example.com"},
    "api_2": {"name": "another_api", "endpoint": "https://api.another.com"}
}
db_file = database_dir / 'test_db.json'
with open(db_file, 'w') as f:
    json.dump(sample_db, f)

# Patch the EXPERIMENT_DIR in the module to use our temp directory
def patched_load_database(name):
    db_path = database_dir / f'{name}.json'
    if db_path.exists():
        with open(db_path) as f:
            return json.load(f)
    return {}

ARGS = {
    'name': 'test_db'
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
load_module Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/experiments/agentshap/exp6_model_comparison.py
code served (permissive licence) · get_code("0cd7798a11c1b258")
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 module. 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 sys
import os
import tempfile
import importlib.util

# Create a temporary Python module file to load
temp_dir = tempfile.mkdtemp()
module_file = os.path.join(temp_dir, "test_module.py")

# Write a simple test module
with open(module_file, "w") as f:
    f.write("""
def hello_world():
    return "Hello from test module"

class TestClass:
    def __init__(self):
        self.value = 42
""")

# Define arguments for load_module function
ARGS = {
    "name": "test_module",
    "path": module_file
}
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 module — a module output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a module 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
load_prompts_from_benchmark Ran
ran, honoured the contract we drafted
ronigold/TokenSHAP/experiments/agentshap/exp6_model_comparison.py
code served (permissive licence) · get_code("7ef2f80a4e2e153d")
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 1, 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 json
from pathlib import Path
import tempfile
import os

# Create a temporary directory structure to mimic API-Bank benchmark
temp_dir = tempfile.mkdtemp()
experiment_dir = Path(temp_dir)
samples_dir = experiment_dir / 'DAMO-ConvAI' / 'api-bank' / 'lv1-lv2-samples' / 'level-1-given-desc'
samples_dir.mkdir(parents=True, exist_ok=True)

# Create sample JSONL files for a test tool
tool_name = "test_tool"
jsonl_file_1 = samples_dir / f'{tool_name}-level-1-001.jsonl'
jsonl_file_2 = samples_dir / f'{tool_name}-level-1-002.jsonl'

# Write sample data to JSONL files
sample_data_1 = [
    {"role": "User", "text": "First user prompt"},
    {"role": "Assistant", "text": "First assistant response"}
]

sample_data_2 = [
    {"role": "User", "text": "Second user prompt"},
    {"role": "Assistant", "text": "Second assistant response"}
]

with open(jsonl_file_1, 'w') as f:
    for item in sample_data_1:
        f.write(json.dumps(item) + '\n')

with open(jsonl_file_2, 'w') as f:
    for item in sample_data_2:
        f.write(json.dumps(item) + '\n')

# Patch the SAMPLES_DIR in the module
import sys
from types import ModuleType

# Create a mock module with the patched paths
mock_module = ModuleType('mock_api_bank')
mock_module.EXPERIMENT_DIR = experiment_dir
mock_module.APIBANK_DIR = experiment_dir / 'DAMO-ConvAI' / 'api-bank'
mock_module.SAMPLES_DIR = samples_dir

# Define the function with patched directory
def load_prompts_from_benchmark(tool_name, max_prompts=2):
    """Load real prompts from API-Bank benchmark."""
    prompts = []
    for jsonl_file in sorted(samples_dir.glob(f'{tool_name}-level-1-*.jsonl')):
        with open(jsonl_file) as f:
            for line in f:
                data = json.loads(line)
                if data.get('role') == 'User':
                    prompts.append(data['text'])
                    break
        if len(prompts) >= max_prompts:
            break
    return prompts

ARGS = {
    'tool_name': 'test_tool',
    'max_prompts': 2
}
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 list, ndim 1, 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
process_segmentation_results Ran
ran; our contract draft was wrong, not the code
ronigold/TokenSHAP/token_shap/visualization.py
code served (permissive licence) · get_code("3efd4b0452a3f146")
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. 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 torch
import numpy as np

torch.manual_seed(0)

# Create a result tuple with 4 elements: boxes, labels, confidences, masks
boxes = torch.randn(2, 4)  # 2 boxes, 4 coordinates each
labels = torch.tensor([0, 1])  # 2 label indices
confidences = torch.tensor([0.9, 0.8])  # 2 confidence scores
masks = torch.randn(2, 8, 8)  # 2 masks, 8x8 each

result = (boxes, labels, confidences, masks)

ARGS = {
    "result": result
}
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 tuple — a tuple output has no array shape of its own; none is 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
create_side_by_side_visualization Not yet run
unverified (harvested, no recorded run)
ronigold/TokenSHAP/token_shap/visualization.py
code served (permissive licence) · get_code("cb8d42d00bcf79ba")
How it ran

no invocation recorded.

interact_with_ollama Not yet run
unverified (harvested, no recorded run)
ronigold/TokenSHAP/token_shap/base.py
code served (permissive licence) · get_code("ecdc98a3f24e0937")
How it ran

no invocation recorded.

mp4_to_gif_with_styled_title Not yet run
unverified (harvested, no recorded run)
ronigold/TokenSHAP/token_shap/visualization.py
code served (permissive licence) · get_code("c2612159a9d48d79")
How it ran

no invocation recorded.

Also present in other papers' code

Of 12 samples lifted from this paper's linked repositories, 12 carry a function identity and 0 do not. Of the 12 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 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.

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-23.

Repositories linked to this paper

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

Abstract

As large language models (LLMs) become increasingly prevalent in critical applications, the need for interpretable AI has grown. We introduce TokenSHAP, a novel method for interpreting LLMs by attributing importance to individual tokens or substrings within input prompts. This approach adapts Shapley values from cooperative game theory to natural language processing, offering a rigorous framework for understanding how different parts of an input contribute to a model's response. TokenSHAP leverages Monte Carlo sampling for computational efficiency, providing interpretable, quantitative measures of token importance. We demonstrate its efficacy across diverse prompts and LLM architectures, showing consistent improvements over existing baselines in alignment with human judgments, faithfulness to model behavior, and consistency. Our method's ability to capture nuanced interactions between tokens provides valuable insights into LLM behavior, enhancing model transparency, improving prompt engineering, and aiding in the development of more reliable AI systems. TokenSHAP represents a significant step towards the necessary interpretability for responsible AI deployment, contributing to the broader goal of creating more transparent, accountable, and trustworthy AI systems.

For agents

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

get_harvested_code_for_paper("2407.10114")
get_code_for_paper("2407.10114")
have("2407.10114")

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

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

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

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

Connect an agent — have() is free.