SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2305.15054 · EMNLP · 2023

A Mechanistic Interpretation of Arithmetic Reasoning in Language Models using Causal Mediation Analysis

Yonatan Belinkov, Mrinmaya Sachan, Alessandro Stolfo

arXiv · PDF · Open in the Atlas

Code that ran

7 of 8 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (3 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 4 failures of our instrument; 1 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.15054.json · badge: /api/ran/2305.15054.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
alestolfo/lm-arithmetic marked official in Papers with Code
Papers with Code archive
7 ran · 1 no recorded run
FunctionStatusWhere it lives
BaseModel Ran
ran on a synthesized input · constructed an object; no result was computed
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("8590248469763c76")
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 an instance of its own class, BaseModel: the run constructed the object and did not call it, so no result was computed. 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)

# The BaseModel.__init__ method takes a model_version string parameter
# and sets various boolean flags based on string matching against that parameter.
# No other parameters are used.

ARGS = {
    "model_version": "gpt2-medium"
}
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 BaseModel — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BaseModel 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
OverrideGPTJAttention Ran
ran on a synthesized input · constructed an object; no result was computed
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("321851d637ab70ed")
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 an instance of its own class, OverrideGPTJAttention: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn
from transformers.models.gptj.modeling_gptj import GPTJAttention
import torch.nn.functional as F

torch.manual_seed(0)

# Create a mock attention module that has the required attributes
class MockAttention(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed_dim = 4
        self.num_attention_heads = 2
        self.head_dim = self.embed_dim // self.num_attention_heads
        self.rotary_dim = 2
        self.attn_dropout = nn.Dropout(0.1)
        self.resid_dropout = nn.Dropout(0.1)

attention = MockAttention()

# Create attn_override - a tensor of attention weights to override with
# Shape: (batch, num_heads, seq_len, seq_len)
attn_override = torch.randn(2, 2, 3, 3)

# Create attn_override_mask - a boolean mask indicating where to apply the override
# Shape: (batch, num_heads, seq_len, seq_len)
attn_override_mask = torch.randint(0, 2, (2, 2, 3, 3), dtype=torch.bool)

ARGS = {
    "attention": attention,
    "attn_override": attn_override,
    "attn_override_mask": attn_override_mask,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type OverrideGPTJAttention — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a OverrideGPTJAttention 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
OverrideGPTNeoXAttention Ran
ran on a synthesized input · constructed an object; no result was computed
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("1693cce78428b98a")
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 an instance of its own class, OverrideGPTNeoXAttention: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn

torch.manual_seed(0)

# Create a minimal mock attention module that has the required attributes
class MockAttention(nn.Module):
    def __init__(self):
        super().__init__()
        self.num_attention_heads = 2
        self.hidden_size = 8
        self.rotary_ndims = 4
        self.rotary_emb = MockRotaryEmb()
    
class MockRotaryEmb(nn.Module):
    def __init__(self):
        super().__init__()
    
    def forward(self, x, seq_len=None):
        # Return cos and sin tensors
        cos = torch.ones(1, 1, seq_len if seq_len else 4, 4)
        sin = torch.ones(1, 1, seq_len if seq_len else 4, 4)
        return cos, sin

# Create mock attention override tensors
attn_override = torch.randn(2, 2, 4, 4)  # (batch, heads, seq_len, seq_len)
attn_override_mask = torch.ones(2, 2, 4, 4)  # (batch, heads, seq_len, seq_len)

# Create the mock attention module
attention = MockAttention()

ARGS = {
    'attention': attention,
    'attn_override': attn_override,
    'attn_override_mask': attn_override_mask
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type OverrideGPTNeoXAttention — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a OverrideGPTNeoXAttention 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
batch Ran
ran; our contract draft was wrong, not the code
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("a3baae78dba11763")
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 generator. 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)

# The function 'batch' takes an iterable and a batch size
# It uses len() on the iterable and slicing with [ndx:min(...)]
# So we need an object that supports both len() and slicing

# Simple list works perfectly as an iterable
iterable = list(range(10))  # A simple list of 10 items
bsize = 3  # Batch size

ARGS = {
    "iterable": iterable,
    "bsize": bsize
}
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 generator — a generator output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a generator 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
convert_to_words Ran
ran; our contract draft was wrong, not the code
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("e05197d9ca4ca998")
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.

# SETUP CODE

# The function convert_to_words takes a single parameter 'num'
# It converts a number (as int or str) to its word representation
# The function accepts numbers with length 0-4 (empty string, single digit, up to 9999)

ARGS = {
    'num': 42
}
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_lama_vocab_subset Ran
ran; our contract draft was wrong, not the code
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("f6dd1bef86ad606f")
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
import shutil
from unittest.mock import Mock

# Create a temporary directory structure with mock LAMA data
temp_dir = tempfile.mkdtemp()
trex_dir = os.path.join(temp_dir, 'TREx')
os.makedirs(trex_dir, exist_ok=True)

# Create mock JSONL files for each relation in RELS_SUBSET
RELS_SUBSET = ['P36', 'P1376', 'P279', 'P19', 'P103', 'P20']

for rel_id in RELS_SUBSET:
    filepath = os.path.join(trex_dir, f'{rel_id}.jsonl')
    with open(filepath, 'w') as f:
        # Write sample data with obj_label
        f.write(json.dumps({'obj_label': 'Berlin'}) + '\n')
        f.write(json.dumps({'obj_label': 'France'}) + '\n')
        f.write(json.dumps({'obj_label': 'dog'}) + '\n')
        # Write a multi-token label that should be skipped
        f.write(json.dumps({'obj_label': 'New York'}) + '\n')

# Create a mock tokenizer
class MockTokenizer:
    def __init__(self):
        self.vocab = {
            'a': 0, 'Berlin': 1, 'France': 2, 'dog': 3,
            'New': 4, 'York': 5
        }
    
    def tokenize(self, text):
        # Simple whitespace tokenization
        return text.split()
    
    def convert_tokens_to_ids(self, tokens):
        return [self.vocab.get(token, 999) for token in tokens]

tokenizer = MockTokenizer()

# Create mock args object
class MockArgs:
    def __init__(self, lama_path):
        self.lama_path = lama_path

args = MockArgs(temp_dir)

ARGS = {
    'tokenizer': tokenizer,
    '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 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_files Ran
ran; our contract draft was wrong, not the code
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("598e56c91095f2bc")
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
import shutil

# Create a temporary directory with test JSONL files
test_dir = tempfile.mkdtemp()

# Create sample JSONL files
file1_path = os.path.join(test_dir, "data1.jsonl")
with open(file1_path, 'w') as f:
    f.write(json.dumps({"id": 1, "text": "hello"}) + "\n")
    f.write(json.dumps({"id": 2, "text": "world"}) + "\n")

file2_path = os.path.join(test_dir, "data2.jsonl")
with open(file2_path, 'w') as f:
    f.write(json.dumps({"id": 3, "text": "foo"}) + "\n")
    f.write(json.dumps({"id": 4, "text": "bar"}) + "\n")

# Create a file to exclude
file3_path = os.path.join(test_dir, "excluded.jsonl")
with open(file3_path, 'w') as f:
    f.write(json.dumps({"id": 5, "text": "skip"}) + "\n")

ARGS = {
    "dirname": test_dir,
    "excluded_files": ["excluded.jsonl"]
}
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
Model Not yet run
unverified (harvested, no recorded run)
alestolfo/lm-arithmetic/intervention_models/intervention_model.py
code served (permissive licence) · get_code("33b1862cd0f12fcb")
How it ran

no invocation recorded.

Also present in other papers' code

Of 8 samples lifted from this paper's linked repositories, 8 carry a function identity and 0 do not. Of the 8 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 8 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

Mathematical reasoning in large language models (LMs) has garnered significant attention in recent work, but there is a limited understanding of how these models process and store information related to arithmetic tasks within their architecture. In order to improve our understanding of this aspect of language models, we present a mechanistic interpretation of Transformer-based LMs on arithmetic questions using a causal mediation analysis framework. By intervening on the activations of specific model components and measuring the resulting changes in predicted probabilities, we identify the subset of parameters responsible for specific predictions. This provides insights into how information related to arithmetic is processed by LMs. Our experimental results indicate that LMs process the input by transmitting the information relevant to the query from mid-sequence early layers to the final token using the attention mechanism. Then, this information is processed by a set of MLP modules, which generate result-related information that is incorporated into the residual stream. To assess the specificity of the observed activation dynamics, we compare the effects of different model components on arithmetic queries with other tasks, including number retrieval from prompts and factual knowledge questions. 1

For agents

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

get_harvested_code_for_paper("2305.15054")
get_code_for_paper("2305.15054")
have("2305.15054")

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

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

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

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

Connect an agent — have() is free.