SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2202.07304 · 2022

XAI for Transformers: Better Explanations through Conservative Propagation

arXiv · PDF · Open in the Atlas

Code that ran

10 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 8 have no contract verdict; 1 failure of our instrument; 2 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/2202.07304.json · badge: /api/ran/2202.07304.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
ameenali/xai_transformers canonical (classifier label)
classifier basis not recorded on the link
10 ran · 2 no recorded run
FunctionStatusWhere it lives
LayerNorm Ran
ran on a synthesized input
ameenali/xai_transformers/utils.py
code served (permissive licence) · get_code("8aae8fd9930a694c")
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 LayerNormImpl. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 torch.nn as nn

torch.manual_seed(0)

class Args:
    def __init__(self):
        self.lnv = 'nowb'
        self.sigma = 0.5
        self.adanorm_scale = 1.0
        self.nowb_scale = 1.0
        self.mean_detach = False
        self.std_detach = False

ARGS = {
    'normalized_shape': 4,
    'eps': 1e-05,
    'elementwise_affine': True,
    'export': False,
    'args': Args()
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
apex, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type LayerNormImpl — a LayerNormImpl output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a LayerNormImpl 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
apply_self_attention_rules Ran
ran on a synthesized input
ameenali/xai_transformers/IMDB/run_imdb.py
code served (permissive licence) · get_code("62d56a2c8e317a8d")
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 3, dtype family float, shape (2, 4, 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 torch

torch.manual_seed(0)

# R_ss: used as right operand in torch.matmul(cam_ss, R_ss)
# cam_ss: used as left operand in torch.matmul(cam_ss, R_ss)
# For matmul to work: cam_ss shape (..., n, k) @ R_ss shape (..., k, m) -> result (..., n, m)
# Using distinct dimensions: batch=2, n=4, k=3, m=5

R_ss = torch.randn(2, 3, 5)  # shape (batch, k, m)
cam_ss = torch.randn(2, 4, 3)  # shape (batch, n, k)

ARGS = {
    "R_ss": R_ss,
    "cam_ss": cam_ss,
}
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 Tensor, ndim 3, dtype family float, shape (2, 4, 5) — shape (2, 4, 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
avg_heads Ran
ran; our contract draft was wrong, not the code
ameenali/xai_transformers/IMDB/run_imdb.py
code served (permissive licence) · get_code("27481013d8c59da1")
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 torch
import torch.nn as nn

torch.manual_seed(0)

# Construct arguments for avg_heads function
# The function expects:
# - cam: a tensor that will be reshaped to (-1, height, width)
# - grad: a tensor that will be reshaped to (-1, height, width)

# Create cam tensor with shape (batch, heads, height, width)
# Using distinct sizes: batch=2, heads=4, height=3, width=5
cam = torch.randn(2, 4, 3, 5)

# Create grad tensor with same shape as cam
grad = torch.randn(2, 4, 3, 5)

ARGS = {
    "cam": cam,
    "grad": grad
}
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 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
create_data_loader Ran
ran on a synthesized input
ameenali/xai_transformers/IMDB/imdb.py
code served (permissive licence) · get_code("e68f6ccbc2173bdb")
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 DataLoader. 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 pandas as pd
from unittest.mock import Mock

torch.manual_seed(0)

# Create a minimal tokenizer mock that implements encode_plus
class MinimalTokenizer:
    def encode_plus(self, text, add_special_tokens=True, max_length=128, 
                   return_token_type_ids=True, pad_to_max_length=True, 
                   return_attention_mask=True, return_tensors='pt', truncation=True):
        # Return mock encoded tensors
        batch_size = 1
        seq_len = max_length
        return {
            'input_ids': torch.randint(0, 1000, (batch_size, seq_len)),
            'attention_mask': torch.ones(batch_size, seq_len),
            'token_type_ids': torch.zeros(batch_size, seq_len)
        }

# Create sample data
reviews = ['This movie is great!', 'I did not like it']
sentiment_scores = [1, 0]

# Create a DataFrame with the required columns
df = pd.DataFrame({
    'review': reviews,
    'sentiment_score': sentiment_scores
})

tokenizer = MinimalTokenizer()
max_len = 16
batch_size = 2

ARGS = {
    'df': df,
    'tokenizer': tokenizer,
    'max_len': max_len,
    'batch_size': batch_size
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
pandas, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataLoader — a DataLoader output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataLoader 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_adjmat Ran
ran on a synthesized input
ameenali/xai_transformers/attribution.py
code served (permissive licence) · get_code("38d43b4feccaaa24")
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 numpy as np

# Construct arguments for get_adjmat
# Parameters:
# - mat: a 3D numpy array of shape (n_layers, length, length)
# - input_tokens: a list/array of tokens corresponding to positions

# Create a small 3D matrix
# Shape: (n_layers=2, length=3, length=3)
mat = np.array([
    [[0.1, 0.2, 0.3],
     [0.4, 0.5, 0.6],
     [0.7, 0.8, 0.9]],
    [[0.15, 0.25, 0.35],
     [0.45, 0.55, 0.65],
     [0.75, 0.85, 0.95]]
])

# Create input tokens - one token per position in length dimension
input_tokens = ['token_a', 'token_b', 'token_c']

ARGS = {
    'mat': mat,
    'input_tokens': input_tokens
}
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 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
get_sst_dataset Ran
ran on a synthesized input
ameenali/xai_transformers/SST/sst.py
code served (permissive licence) · get_code("7448a1b293e85dc5")
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 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 torch

class MockTokenizer:
    def __call__(self, texts, padding=False):
        # Return mock tokenized output with required keys
        batch_size = len(texts)
        return {
            'input_ids': [[101, 2054, 2003, 102] for _ in range(batch_size)],
            'token_type_ids': [[0, 0, 0, 0] for _ in range(batch_size)],
            'attention_mask': [[1, 1, 1, 1] for _ in range(batch_size)]
        }

torch.manual_seed(0)

mock_tokenizer = MockTokenizer()

datasets = {
    'train': {
        'sentence': ['This is a test', 'Another test sentence'],
        'label': [0, 1]
    },
    'validation': {
        'sentence': ['Validation sentence one', 'Validation sentence two'],
        'label': [1, 0]
    }
}

ARGS = {
    'datasets': datasets,
    'tokenizer': mock_tokenizer
}
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 tuple, ndim 2, dtype family float — 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
load_imdb Ran
ran on a synthesized input
ameenali/xai_transformers/IMDB/imdb.py
code served (permissive licence) · get_code("3f92118756cbc8b1")
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 DataFrame. 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 pandas as pd
import tempfile
import os

# Create a temporary CSV file with test data
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, 'imdb.csv')

# Create sample IMDB data
df_sample = pd.DataFrame({
    'sentiment': ['positive', 'negative', 'positive', 'negative'],
    'text': ['great movie', 'terrible film', 'amazing', 'awful']
})
df_sample.to_csv(temp_file, index=False)

ARGS = {
    'file': temp_file
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
pandas — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataFrame — a DataFrame output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataFrame output the recorded ndim 2 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
rename_params Ran
ran on a synthesized input
ameenali/xai_transformers/IMDB/run_imdb.py
code served (permissive licence) · get_code("0918e3d36dec3d64")
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)

def rename_params(key):
    for k_ in ['key', 'query', 'value']:
        key = key.replace(k_, 'p' + k_)
    return key

# The function takes a single parameter 'key' which is a string
# It performs string replacements on 'key' and returns the modified string
# We need to provide a string that contains some of the substrings it will replace

ARGS = {
    'key': 'attention.query.key.value_output'
}
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
softmax Ran
ran, honoured the contract we drafted
ameenali/xai_transformers/attribution.py
code served (permissive licence) · get_code("91fe7a23c1c052b7")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Sonnet 4.5, prompt python_fixture_v1) and returned ndarray, ndim 2, dtype family float, shape (3, 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

# Create a simple 2D array for testing softmax
# Using shape (3, 4) to have distinct dimensions
x = np.array([[1.0, 2.0, 3.0, 4.0],
              [2.0, 3.0, 4.0, 5.0],
              [3.0, 4.0, 5.0, 6.0]])

ARGS = {
    'x': x
}
Setup block drafted by
a language model, Claude Sonnet 4.5, prompt python_fixture_v1
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 2, dtype family float, shape (3, 4) — shape (3, 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
to_sentiment Ran
ran on a synthesized input
ameenali/xai_transformers/IMDB/imdb.py
code served (permissive licence) · get_code("3ff61564e786e665")
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 int, ndim 0, dtype family int, 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 torch

torch.manual_seed(0)

def to_sentiment(rating):
    rating = str(rating)
    if rating == 'positive':
        return 0
    else:
        return 1

ARGS = {
    'rating': 'positive'
}
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 int, ndim 0, dtype family int, 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
compute_flows Not yet run
unverified (harvested, no recorded run)
ameenali/xai_transformers/attribution.py
code served (permissive licence) · get_code("e6f03715bb008a76")
How it ran

no invocation recorded.

make_p_layer Not yet run
unverified (harvested, no recorded run)
ameenali/xai_transformers/xai_transformer.py
code served (permissive licence) · get_code("c8b195f1d000eaf9")
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, 3 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 0 the same month, 2 later) and 9 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
softmax 4 other papers
3 dated earlier, 1 later
1804.08049 (2018-04)
Semi-supervised User Geolocation via Graph Convolutional Networks
1901.09216 (2019-01)
Modelling Bounded Rationality in Multi-Agent Interactions by Generalized Recursive Reasoning
1905.03381 (2019-05)
AutoAssist: A Framework to Accelerate Training of Deep Neural Networks
and 1 more not named here
avg_heads 1 other paper
1 later
2404.03118 (2024-04)
LVLM-Interpret: An Interpretability Tool for Large Vision-Language Models
compute_flows 1 other paper
1 dated earlier
2005.00928 (2020-05)
Quantifying Attention Flow in Transformers

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

Transformers have become an important workhorse of machine learning, with numerous applications. This necessitates the development of reliable methods for increasing their transparency. Multiple interpretability methods, often based on gradient information, have been proposed. We show that the gradient in a Transformer reflects the function only locally, and thus fails to reliably identify the contribution of input features to the prediction. We identify Attention Heads and LayerNorm as main reasons for such unreliable explanations and propose a more stable way for propagation through these layers. Our proposal, which can be seen as a proper extension of the well-established LRP method to Transformers, is shown both theoretically and empirically to overcome the deficiency of a simple gradient-based approach, and achieves state-of-the-art explanation performance on a broad range of Transformer models and datasets.

For agents

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

get_harvested_code_for_paper("2202.07304")
get_code_for_paper("2202.07304")
have("2202.07304")

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

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

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

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

Connect an agent — have() is free.