SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2305.12535 · ACL · 2023

Explaining How Transformers Use Context to Build Predictions

Javier Ferrando, Marta Costa-Jussà, Ioannis Tsiamas, Gerard Gállego

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; 0 honoured the contract we drafted, 0 violated it and 8 have no contract verdict; 1 failure 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/2305.12535.json · badge: /api/ran/2305.12535.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
mt-upc/logit-explanations canonical (classifier label)
classifier basis: census
9 ran · 3 no recorded run
FunctionStatusWhere it lives
model_preds Ran
ran; our contract draft was wrong, not the code
mt-upc/logit-explanations/lm_saliency.py
pointer only (licence: Apache-2.0); the stored copy get_code serves, from kayoyin/interpret-lm, is pointer only (licence: NONE) · get_code("4f8ea1ef4a3b4d38")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (Apache-2.0), but get_code serves the stored copy, first harvested from kayoyin/interpret-lm, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

normalize_attribution_visualization Ran
ran on a synthesized input
mt-upc/logit-explanations/src/utils_contributions.py
code served (permissive licence) · get_code("2bdd8bf55d1dacd1")
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 (2, 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 torch
import numpy as np

torch.manual_seed(0)

# Create a small tensor of attributions with shape (batch=2, features=4)
# The function calls min(0, keepdim=True) and max(0, keepdim=True)
# which operates along dimension 0 (batch dimension)
attributions = torch.randn(2, 4)

ARGS = {
    "attributions": attributions
}
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 (2, 4) — shape (2, 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
normalize_contributions Ran
ran on a synthesized input
mt-upc/logit-explanations/src/utils_contributions.py
code served (permissive licence) · get_code("49edb238be0a61d0")
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 (3, 2, 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 torch
import torch.nn.functional as F

torch.manual_seed(0)

# Create model_contributions: a 3D tensor with shape (num_layers, batch_size, feature_dim)
# The function iterates over dimension 0, then uses min/max/sum on dimension -1
model_contributions = torch.randn(3, 2, 4)

# Test with different scaling options
# The function only uses 'min_max', 'sum_one', 'min_sum', 'softmax', 't', or other
# We'll use 'min_max' as the default scaling method
scaling = 'min_max'

# resultant_norm is optional and only used when scaling == 'min_sum'
# It should be a 1D tensor with length equal to model_contributions.size(0)
resultant_norm = torch.randn(3)

ARGS = {
    'model_contributions': model_contributions,
    'scaling': scaling,
    'resultant_norm': resultant_norm
}
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 (3, 2, 4) — shape (3, 2, 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
read_attribution_scores Ran
ran on a synthesized input
mt-upc/logit-explanations/src/utils_evaluation.py
code served (permissive licence) · get_code("d666903d478de356")
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
import os
import tempfile

# Create temporary directory structure and files for the function to read
temp_dir = tempfile.mkdtemp()
results_dir = os.path.join(temp_dir, 'results')
os.makedirs(results_dir, exist_ok=True)

# Create dataset subdirectory
dataset_dir = os.path.join(results_dir, 'cifar10')
os.makedirs(dataset_dir, exist_ok=True)

# Create sva subdirectory
sva_dir = os.path.join(results_dir, 'sva_5')
os.makedirs(sva_dir, exist_ok=True)

# Create sample JSON files that the function might try to read
sample_explanations = {
    "sample_id_1": [0.1, 0.2, 0.3],
    "sample_id_2": [0.4, 0.5, 0.6]
}

# Write JSON file for non-sva case
with open(os.path.join(dataset_dir, 'train_model_attention.json'), 'w') as f:
    json.dump(sample_explanations, f)

# Write JSON file for sva case
with open(os.path.join(sva_dir, 'sva_5_model_attention_5.json'), 'w') as f:
    json.dump(sample_explanations, f)

# Change to temp directory so relative paths work
original_dir = os.getcwd()
os.chdir(temp_dir)

ARGS = {
    'name_path': 'model',
    'dataset': 'cifar10',
    'subset': 'train',
    'method': 'attention'
}
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
read_blimp_dataset Ran
ran on a synthesized input
mt-upc/logit-explanations/extract_explanations.py
code served (permissive licence) · get_code("d84edf920238d8c2")
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 os
import tempfile

# Create a temporary directory structure to mock the blimp dataset
temp_dir = tempfile.mkdtemp()
blimp_with_targets_dir = os.path.join(temp_dir, 'data', 'blimp_with_targets')
os.makedirs(blimp_with_targets_dir, exist_ok=True)

# Create a sample CSV file for the blimp subset
sample_data = pd.DataFrame({
    'sentence': ['The cat sat on the mat.', 'Dogs play in the park.'],
    'label': [1, 0],
    'target': ['correct', 'incorrect']
})
sample_data.index.name = 'index'
sample_csv_path = os.path.join(blimp_with_targets_dir, 'agreement_anim.csv')
sample_data.to_csv(sample_csv_path)

# Update the working directory for the function to find the data
original_cwd = os.getcwd()
os.chdir(temp_dir)

ARGS = {
    'blimp_subset': 'agreement_anim'
}
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
read_sentence_target_foil Ran
ran on a synthesized input
mt-upc/logit-explanations/src/utils_evaluation.py
code served (permissive licence) · get_code("4a8acba50f4c94f6")
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 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 pandas as pd
import torch

torch.manual_seed(0)

# Create a minimal DataFrame with the required columns
df = pd.DataFrame({
    'one_prefix_prefix': [
        'The cat sat on the mat ***mask*** quickly',
        'Dogs are very ***mask*** animals'
    ],
    'one_prefix_word_good': ['sleeping', 'loyal'],
    'one_prefix_word_bad': ['flying', 'edible']
})

# Define arguments for the function
ARGS = {
    'df': df,
    'subset': 'sva',
    'idx': 0
}
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 tuple, ndim 1, 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
register_embedding_gradient_hooks Ran
ran on a synthesized input
mt-upc/logit-explanations/lm_saliency.py
code served (permissive licence) · get_code("11312f5a29459cc0")
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 RemovableHandle. 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 torch.nn as nn

torch.manual_seed(0)

# Create a minimal config class for 'opt' model type
class MinimalConfig:
    def __init__(self, model_type='opt'):
        self.model_type = model_type

# Create minimal embedding layer
class MinimalEmbedding(nn.Module):
    def __init__(self, vocab_size=10, embedding_dim=4):
        super().__init__()
        self.embed_tokens = nn.Embedding(vocab_size, embedding_dim)
    
    def forward(self, x):
        return self.embed_tokens(x)

# Create minimal decoder for OPT model structure
class MinimalDecoder(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed_tokens = nn.Embedding(10, 4)
    
    def forward(self, x):
        return self.embed_tokens(x)

# Create minimal OPT model
class MinimalOPTModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = MinimalConfig(model_type='opt')
        self.model = type('obj', (object,), {})()
        self.model.decoder = MinimalDecoder()
    
    def forward(self, x):
        return self.model.decoder(x)

# Create the model instance
model = MinimalOPTModel()

# Create embeddings_gradients list
embeddings_gradients = []

ARGS = {
    'model': model,
    'embeddings_gradients': embeddings_gradients
}
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 RemovableHandle — a RemovableHandle output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a RemovableHandle 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
register_embedding_list_hook Ran
ran on a synthesized input
mt-upc/logit-explanations/lm_saliency.py
code served (permissive licence) · get_code("a5d85e23d4429891")
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 RemovableHandle. 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 torch.nn as nn
import numpy as np

torch.manual_seed(0)

# Create a minimal config class that the function checks
class MinimalConfig:
    def __init__(self, model_type):
        self.model_type = model_type

# Create minimal embedding layer
class EmbeddingLayer(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed = nn.Embedding(num_embeddings=10, embedding_dim=4)
    
    def forward(self, x):
        return self.embed(x)

# For 'opt' model type
class OptModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = MinimalConfig('opt')
        self.model = nn.Module()
        self.model.decoder = nn.Module()
        self.model.decoder.embed_tokens = EmbeddingLayer()
    
    def forward(self, x):
        return self.model.decoder.embed_tokens(x)

# For 'bloom' model type
class BloomModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = MinimalConfig('bloom')
        self.transformer = nn.Module()
        self.transformer.word_embeddings = EmbeddingLayer()
    
    def forward(self, x):
        return self.transformer.word_embeddings(x)

# For other model types (gpt-2 style)
class GPT2Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.config = MinimalConfig('gpt2')
        self.transformer = nn.Module()
        self.transformer.wte = EmbeddingLayer()
    
    def forward(self, x):
        return self.transformer.wte(x)

# Create a model instance
model = GPT2Model()

# Create an empty list to collect embeddings
embeddings_list = []

ARGS = {
    "model": model,
    "embeddings_list": embeddings_list,
}
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 RemovableHandle — a RemovableHandle output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a RemovableHandle 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
tokens2words Ran
ran on a synthesized input
mt-upc/logit-explanations/extract_explanations.py
code served (permissive licence) · get_code("640771894bf085d4")
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.

ARGS = {
    "tokenized_text": ["Ġhello", "world", "Ġfoo", "bar"],
    "bos": False
}
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 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_module Not yet run
unverified (harvested, no recorded run)
mt-upc/logit-explanations/src/contributions.py
code served (permissive licence) · get_code("0b0bac3cd5d8d507")
How it ran

no invocation recorded.

load_model_tokenizer Not yet run
unverified (harvested, no recorded run)
mt-upc/logit-explanations/src/utils_contributions.py
code served (permissive licence) · get_code("0cf59c38d6eded2a")
How it ran

no invocation recorded.

track2input_tokens Not yet run
unverified (harvested, no recorded run)
mt-upc/logit-explanations/extract_explanations.py
code served (permissive licence) · get_code("ea07643ad028f852")
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, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 1 later) and 11 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
model_preds 2 other papers
1 dated earlier, 1 later
2202.10419 (2022-02)
Interpreting Language Models with Contrastive Explanations
2311.07230 (2023-11)
How are Prompts Different in Terms of Sensitivity?

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

Language Generation Models produce words based on the previous context. Although existing methods offer input attributions as explanations for a model's prediction, it is still unclear how prior words affect the model's decision throughout the layers. In this work, we leverage recent advances in explainability of the Transformer and present a procedure to analyze models for language generation. Using contrastive examples, we compare the alignment of our explanations with evidence of the linguistic phenomena, and show that our method consistently aligns better than gradient-based and perturbation-based baselines. Then, we investigate the role of MLPs inside the Transformer and show that they learn features that help the model predict words that are grammatically acceptable. Lastly, we apply our method to Neural Machine Translation models, and demonstrate that they generate human-like source-target alignments for building predictions.

For agents

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

get_harvested_code_for_paper("2305.12535")
get_code_for_paper("2305.12535")
have("2305.12535")

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

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

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

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

Connect an agent — have() is free.