SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2410.21272 · 2024

Arithmetic Without Algorithms: Language Models Solve Math With a Bag of Heuristics

arXiv · PDF · Open in the Atlas

Code that ran

4 of 6 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, 1 violated it and 0 have no contract verdict; 2 failures 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/2410.21272.json · badge: /api/ran/2410.21272.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
technion-cs-nlp/llm-arithmetic-heuristics canonical (classifier label)
classifier basis: census
4 ran · 2 no recorded run
FunctionStatusWhere it lives
analyzed_operand_pairs_factor Ran
ran, honoured the contract we drafted
technion-cs-nlp/llm-arithmetic-heuristics/heuristics_classification.py
code served (permissive licence) · get_code("9fe2ffb255572164")
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 float, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

from dataclasses import dataclass
from typing import List, Dict, Optional, Tuple

@dataclass
class HeuristicAnalysisData:
    """
    Various pre-calculated data structures that contain required data for heuristic analysis
    """
    also_check_bottom_results: bool = None
    op1_op2_pairs: List = None
    top_op1_op2_indices: List = None
    top_results: List = None
    max_op: int = None
    max_single_token: int = None
    operator_idx: int = None
    k_per_heuristic_cache: Dict = None

# Create a valid HeuristicAnalysisData instance
# The function uses:
# - len(heuristic_analysis_data.op1_op2_pairs)
# - heuristic_analysis_data.max_op ** 2

heuristic_data = HeuristicAnalysisData(
    also_check_bottom_results=True,
    op1_op2_pairs=[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)],  # 5 pairs
    top_op1_op2_indices=[0, 1, 2],
    top_results=[10, 20, 30],
    max_op=10,  # max_op ** 2 = 100
    max_single_token=5,
    operator_idx=0,
    k_per_heuristic_cache={"key": "value"}
)

ARGS = {
    "heuristic_analysis_data": heuristic_data
}
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 float, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_neurons_associated_with_prompt Ran
ran; our contract draft was wrong, not the code
technion-cs-nlp/llm-arithmetic-heuristics/heuristics_analysis.py
code served (permissive licence) · get_code("94fe006567da0e7b")
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 re

# Construct heuristic_classes: a dictionary mapping heuristic names to lists of (layer, neuron, score) tuples
heuristic_classes = {
    "result_1mod2": [
        (0, 0, 0.95),
        (1, 2, 0.87),
    ],
    "op1_region_1_5": [
        (0, 1, 0.92),
        (2, 3, 0.88),
    ],
    "op2_value_3": [
        (1, 0, 0.85),
    ],
    "both_operands_mod_1_2": [
        (0, 2, 0.91),
    ],
    "same_operand": [
        (1, 1, 0.89),
    ],
    "result_region_5_10": [
        (2, 0, 0.86),
    ],
    "result_multi_value=[2,4,6]": [
        (0, 3, 0.93),
    ],
    "result_pattern_0[0-9][0-9]": [
        (1, 3, 0.84),
    ],
}

# Construct a prompt string that will match certain heuristics
# For "2+3=", the result is 5 (which is 1 mod 2), op1 is 2 (in region 1-5), op2 is 3
prompt = "2+3="

ARGS = {
    "prompt": prompt,
    "heuristic_classes": heuristic_classes,
}
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
is_associated_heuristic Ran
ran, violated the contract we drafted
technion-cs-nlp/llm-arithmetic-heuristics/heuristics_analysis.py
code served (permissive licence) · get_code("a58cf7d7df7ace19")
How it ran

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

import re

def is_associated_heuristic(heuristic_name: str, prompt: str):
    """
    Returns if the heuristic type is relevant for the prompt.
    Some examples:
    - is_relevant_heuristic("result_1mod2", "2+3=") -> True
    - is_relevant_heuristic("op1_region_1_5", "2+3=") -> True
    - is_relevant_heuristic("op1_region_1_5", "6-3=") -> False
    """
    operator = re.findall(f'[\\+\\-\\*\\/]', prompt)[0]
    op1, op2 = prompt.split(operator)
    op1, op2 = (int(op1), int(op2[:-1]))
    if heuristic_name.startswith('result'):
        measured_value = eval(f'{op1}{operator}{op2}')
    elif heuristic_name.startswith('op1'):
        measured_value = op1
    elif heuristic_name.startswith('op2'):
        measured_value = op2
    elif 'both_operands' in heuristic_name:
        if 'mod' in heuristic_name:
            m, n = map(int, re.findall('\\d+', heuristic_name.split('operands_')[1]))
            return op1 % n == m and op2 % n == m
        elif 'region' in heuristic_name:
            region = tuple(map(int, heuristic_name.split('_')[3:]))
            return region[0] <= op1 < region[1] and region[0] <= op2 < region[1]
    elif heuristic_name == 'same_operand':
        return op1 == op2
    else:
        raise ValueError(f'Unknown heuristic type {heuristic_name}')
    if 'mod' in heuristic_name:
        m, n = map(int, re.findall('\\d+', heuristic_name.split('_')[1]))
        return measured_value % n == m
    elif 'region' in heuristic_name:
        region = tuple(map(int, heuristic_name.split('_')[2:]))
        return region[0] <= measured_value <= region[1]
    elif 'multi_value' in heuristic_name:
        multi_values = list(map(int, heuristic_name.split('=')[1].strip('[]').split(',')))
        return measured_value in multi_values
    elif 'value' in heuristic_name:
        value = int(heuristic_name.split('_')[2])
        return measured_value == value
    elif 'pattern' in heuristic_name:
        pattern = heuristic_name.split('_')[2]
        return re.match(f'^{pattern}$', str(measured_value).zfill(3)) is not None
    else:
        raise ValueError(f'Unknown heuristic type {heuristic_name}')


ARGS = {
    "heuristic_name": "result_1mod2",
    "prompt": "2+3="
}
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 bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
predict_answer Ran
ran; our contract draft was wrong, not the code
technion-cs-nlp/llm-arithmetic-heuristics/general_utils.py
code served (permissive licence) · get_code("d8cdff520621918b")
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 torch
import torch.nn as nn

torch.manual_seed(0)

class MockModel(nn.Module):
    def __init__(self, vocab_size=100, hidden_dim=4):
        super().__init__()
        self.vocab_size = vocab_size
        self.hidden_dim = hidden_dim
        self.embedding = nn.Embedding(vocab_size, hidden_dim)
        self.linear = nn.Linear(hidden_dim, vocab_size)
    
    def to_tokens(self, prompts, prepend_bos=False):
        """Convert prompts to token tensor."""
        if isinstance(prompts, list):
            max_len = max(len(p.split()) for p in prompts)
            tokens = []
            for p in prompts:
                token_ids = [hash(word) % self.vocab_size for word in p.split()]
                if prepend_bos:
                    token_ids = [0] + token_ids
                token_ids = token_ids + [1] * (max_len + (1 if prepend_bos else 0) - len(token_ids))
                tokens.append(token_ids)
            return torch.tensor(tokens, dtype=torch.long)
        return torch.tensor([[0, 1, 2, 3]], dtype=torch.long)
    
    def forward(self, tokens, return_type='logits'):
        """Forward pass returning logits."""
        embedded = self.embedding(tokens)
        logits = self.linear(embedded)
        if return_type == 'logits':
            return logits
        return logits
    
    def to_str_tokens(self, token_ids):
        """Convert token IDs to string tokens."""
        token_map = {
            0: "<bos>",
            1: "<pad>",
            2: "hello",
            3: "world",
        }
        result = []
        for tid in token_ids:
            tid_int = tid.item() if isinstance(tid, torch.Tensor) else tid
            result.append(token_map.get(tid_int, f"token_{tid_int}"))
        return result

model = MockModel(vocab_size=100, hidden_dim=4)
prompts = ["hello world", "foo bar"]

ARGS = {
    "model": model,
    "prompts": prompts,
}
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 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
is_both_operands_m_mod_n_neuron Not yet run
unverified (harvested, no recorded run)
technion-cs-nlp/llm-arithmetic-heuristics/heuristics_classification.py
code served (permissive licence) · get_code("7a48cc020e8d747c")
How it ran

no invocation recorded.

is_operand_m_mod_n_neuron Not yet run
unverified (harvested, no recorded run)
technion-cs-nlp/llm-arithmetic-heuristics/heuristics_classification.py
code served (permissive licence) · get_code("601f73c93e0a718d")
How it ran

no invocation recorded.

Also present in other papers' code

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

Do large language models (LLMs) solve reasoning tasks by learning robust generalizable algorithms, or do they memorize training data? To investigate this question, we use arithmetic reasoning as a representative task. Using causal analysis, we identify a subset of the model (a circuit) that explains most of the model's behavior for basic arithmetic logic and examine its functionality. By zooming in on the level of individual circuit neurons, we discover a sparse set of important neurons that implement simple heuristics. Each heuristic identifies a numerical input pattern and outputs corresponding answers. We hypothesize that the combination of these heuristic neurons is the mechanism used to produce correct arithmetic answers. To test this, we categorize each neuron into several heuristic types-such as neurons that activate when an operand falls within a certain range-and find that the unordered combination of these heuristic types is the mechanism that explains most of the model's accuracy on arithmetic prompts. Finally, we demonstrate that this mechanism appears as the main source of arithmetic accuracy early in training. Overall, our experimental results across several LLMs show that LLMs perform arithmetic using neither robust algorithms nor memorization; rather, they rely on a "bag of heuristics".

For agents

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

get_harvested_code_for_paper("2410.21272")
get_code_for_paper("2410.21272")
have("2410.21272")

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

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

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

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

Connect an agent — have() is free.