SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2506.07883 · 2025

Diffusion Counterfactual Generation with Semantic Abduction

arXiv · PDF · Open in the Atlas

Code that ran

8 of 9 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 7 have no contract verdict; 0 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/2506.07883.json · badge: /api/ran/2506.07883.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
rajatrasal/diffusion-counterfactuals canonical (classifier label)
classifier basis not recorded on the link
8 ran · 1 no recorded run
FunctionStatusWhere it lives
evaluate_classifier Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/classifier.py
code served (permissive licence) · get_code("8afb07a694e85597")
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 torch
import torch.nn as nn
import numpy as np
from torch.utils.data import Dataset

torch.manual_seed(0)

# Define a minimal classifier model
class SimpleClassifier(nn.Module):
    def __init__(self, input_dim, num_classes):
        super().__init__()
        self.linear = nn.Linear(input_dim, num_classes)
    
    def forward(self, x):
        return self.linear(x)

# Define a minimal test dataset
class SimpleDataset(Dataset):
    def __init__(self, num_samples, input_dim, num_classes):
        self.num_samples = num_samples
        self.input_dim = input_dim
        self.num_classes = num_classes
    
    def __len__(self):
        return self.num_samples
    
    def __getitem__(self, idx):
        # Return (input, target) tuple
        x = torch.randn(self.input_dim)
        y = torch.randint(0, 2, (self.num_classes,)).float()
        return x, y

# Create instances
input_dim = 4
num_classes = 3
num_samples = 6

clf_model = SimpleClassifier(input_dim=input_dim, num_classes=num_classes)

cfg = {
    'general': {
        'device': 'cpu'
    },
    'classifier': {
        'num_class': num_classes,
        'test': {
            'dataloader': {
                'batch_size': 2,
                'shuffle': False
            }
        }
    }
}

test_dataset = SimpleDataset(num_samples=num_samples, input_dim=input_dim, num_classes=num_classes)

ARGS = {
    'clf_model': clf_model,
    'cfg': cfg,
    'test_dataset': test_dataset
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, sklearn, torch, tqdm — 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
get_betas Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/utils/diffusion.py
code served (permissive licence) · get_code("cb62c7e81fb0b39f")
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 1, dtype family float, shape (10,) 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 math
import numpy as np
import torch

torch.manual_seed(0)

ARGS = {
    'cfg': {
        'model': {
            'timesteps': {
                'num': 10
            },
            'beta': {
                'schedule': 'linear',
                'linear': {
                    'start': 0.0001,
                    'end': 0.02
                },
                'cosine': {
                    's': 0.008,
                    'max_beta': 0.999
                }
            }
        }
    }
}
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 1, dtype family float, shape (10,) — shape (10,) 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_torchvision_transforms Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/dataset.py
code served (permissive licence) · get_code("59fde1116ac21980")
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 Compose. 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 torchvision
import torchvision.transforms as transforms

torch.manual_seed(0)

cfg = {
    'train': {
        'dataset': [
            {
                'name': 'ToTensor',
                'params': {}
            },
            {
                'name': 'D2CCrop',
                'params': {}
            },
            {
                'name': 'Normalize',
                'params': {
                    'mean': [0.5],
                    'std': [0.5]
                }
            }
        ]
    },
    'test': {
        'dataset': [
            {
                'name': 'ToTensor',
                'params': {}
            },
            {
                'name': 'Normalize',
                'params': {
                    'mean': [0.5],
                    'std': [0.5]
                }
            }
        ]
    }
}

ARGS = {
    'cfg': cfg,
    'mode': 'train'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, torchvision — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Compose — a Compose output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Compose 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_idx Ran
ran, honoured the contract we drafted
rajatrasal/diffusion-counterfactuals/model/mnist.py
code served (permissive licence) · get_code("5d47dd69d34460d0")
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 ndarray, ndim 2, dtype family int, 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 gzip
import struct
import numpy as np
import tempfile
import os

# Create a temporary IDX format file
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, "test_data.gz")

# Create a valid IDX format file in gzip
# IDX format: magic number (2 bytes) + data type (1 byte) + ndim (1 byte) + shape dimensions + data
with gzip.open(temp_file, 'wb') as f:
    # Magic number: 0x0000 (2 bytes)
    f.write(struct.pack('>H', 0x0000))
    # Data type: 0x08 for uint8 (1 byte)
    f.write(struct.pack('B', 0x08))
    # Number of dimensions: 2 (1 byte)
    f.write(struct.pack('B', 2))
    # Shape: 3x4
    f.write(struct.pack('>II', 3, 4))
    # Data: 12 uint8 values
    data = np.arange(12, dtype=np.uint8).tobytes()
    f.write(data)

ARGS = {
    "path": temp_file
}
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 ndarray, ndim 2, dtype family int, 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
load_image_pillow Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/dataset.py
code served (permissive licence) · get_code("d7b2b0a5c2a807f7")
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 Image. 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 tempfile
import os
from PIL import Image

# Create a temporary RGB image file
temp_dir = tempfile.mkdtemp()
image_path = os.path.join(temp_dir, "test_image.png")

# Create a small test image and save it
test_image = Image.new('RGB', (4, 3), color=(255, 0, 0))
test_image.save(image_path)

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
PIL — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Image — a Image output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Image output the recorded ndim 3 and dtype family int 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_morphomnist_like Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/mnist.py
code served (permissive licence) · get_code("0e3efa6fd931c56f")
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 tempfile
import os
import gzip
import struct
import numpy as np
import pandas as pd

# Create temporary directory with mock data files
tmpdir = tempfile.mkdtemp()

# Create mock training images file (train-images-idx3-ubyte.gz)
# IDX3 format: magic(4) + ndim(1) + dtype(1) + nrows(4) + ncols(4) + ... + data
train_images_path = os.path.join(tmpdir, 'train-images-idx3-ubyte.gz')
with gzip.open(train_images_path, 'wb') as f:
    # magic number (4 bytes, we'll use 0), dtype=8 (uint8), ndim=3
    f.write(struct.pack('>BBBB', 0, 0, 8, 3))
    # shape: 2 images, 28x28
    f.write(struct.pack('>III', 2, 28, 28))
    # write dummy image data
    image_data = np.random.randint(0, 256, (2, 28, 28), dtype=np.uint8)
    f.write(image_data.tobytes())

# Create mock training labels file (train-labels-idx1-ubyte.gz)
# IDX1 format: magic(4) + ndim(1) + dtype(1) + num_items(4) + data
train_labels_path = os.path.join(tmpdir, 'train-labels-idx1-ubyte.gz')
with gzip.open(train_labels_path, 'wb') as f:
    # magic number (4 bytes, we'll use 0), dtype=8 (uint8), ndim=1
    f.write(struct.pack('>BBBB', 0, 0, 8, 1))
    # shape: 2 labels
    f.write(struct.pack('>I', 2))
    # write dummy label data
    label_data = np.array([3, 7], dtype=np.uint8)
    f.write(label_data.tobytes())

# Create mock morpho metrics CSV file
metrics_path = os.path.join(tmpdir, 'train-morpho.csv')
metrics_df = pd.DataFrame({
    'index': [0, 1],
    'area': [450.5, 480.2],
    'length': [25.3, 26.1],
    'thickness': [3.2, 3.5],
    'slant': [5.1, 4.8],
    'width': [18.2, 19.5],
    'height': [28.0, 28.0]
})
metrics_df.to_csv(metrics_path, index=False)

ARGS = {
    'root_dir': tmpdir,
    'train': True,
    'columns': None
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, pandas — 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
metrics Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/benchmarking/celeba_f1.py
code served (permissive licence) · get_code("42a6db49eebe4a0a")
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. 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 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
from torchmetrics.classification import BinaryF1Score

torch.manual_seed(0)

class DummySCM(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
    
    def counterfactual(self, factual_batch, interventions):
        # Returns a dict with 'image', 'Eyeglasses', 'Smiling' keys
        batch_size = factual_batch['image'].shape[0]
        cf_image = self.linear(factual_batch['image'])
        
        result = {
            'image': cf_image,
            'Eyeglasses': torch.randint(0, 2, (batch_size,)).float(),
            'Smiling': torch.randint(0, 2, (batch_size,)).float()
        }
        return result

class DummyClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 1)
        self.device_name = 'cpu'
    
    @property
    def device(self):
        return torch.device(self.device_name)
    
    def forward(self, x_dict):
        # Takes dict with 'image' key, returns predictions
        image = x_dict['image']
        return torch.sigmoid(self.linear(image))

scm = DummySCM()
classifier_glasses = DummyClassifier()
classifier_smiling = DummyClassifier()

# Create test dataloader as list of batches
test_dataloader = [
    {
        'image': torch.randn(2, 4),
        'Eyeglasses': torch.randint(0, 2, (2,)).float(),
        'Smiling': torch.randint(0, 2, (2,)).float()
    },
    {
        'image': torch.randn(2, 4),
        'Eyeglasses': torch.randint(0, 2, (2,)).float(),
        'Smiling': torch.randint(0, 2, (2,)).float()
    }
]

feat = 'Eyeglasses'

ARGS = {
    'scm': scm,
    'test_dataloader': test_dataloader,
    'feat': feat,
    'classifier_glasses': classifier_glasses,
    'classifier_smiling': classifier_smiling,
    'last_batch': -1
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, torchmetrics, tqdm — 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
normalise Ran
ran on a synthesized input
rajatrasal/diffusion-counterfactuals/model/mnist.py
code served (permissive licence) · get_code("e8a4d61a5fec68dd")
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 small tensors for the normalise function
x = torch.randn(2, 4)
x_min = torch.randn(2, 4)
x_max = x_min + torch.abs(torch.randn(2, 4)) + 1.0  # Ensure x_max > x_min

ARGS = {
    "x": x,
    "x_min": x_min,
    "x_max": x_max,
}
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
metrics Not yet run
unverified (harvested, no recorded run)
rajatrasal/diffusion-counterfactuals/benchmarking/celeba_nto.py
code served (permissive licence) · get_code("f1703a9e979afe6b")
How it ran

no invocation recorded.

Also present in other papers' code

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

FunctionAlso present inEarliest-datedOthers named
load_idx 1 other paper
1 dated earlier
1809.10780 (2018-09)
Morpho-MNIST: Quantitative Assessment and Diagnostics for Representation Learning

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

Counterfactual image generation presents significant challenges, including preserving identity, maintaining perceptual quality, and ensuring faithfulness to an underlying causal model. While existing auto-encoding frameworks admit semantic latent spaces which can be manipulated for causal control, they struggle with scalability and fidelity. Advancements in diffusion models present opportunities for improving counterfactual image editing, having demonstrated state-of-the-art visual quality, human-aligned perception and representation learning capabilities. Here, we present a suite of diffusion-based causal mechanisms, introducing the notions of spatial, semantic and dynamic abduction. We propose a general framework that integrates semantic representations into diffusion models through the lens of Pearlian causality to edit images via a counterfactual reasoning process. To our knowledge, this is the first work to consider high-level semantic identity preservation for diffusion counterfactuals and to demonstrate how semantic control enables principled trade-offs between faithful causal control and identity preservation.

For agents

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

get_harvested_code_for_paper("2506.07883")
get_code_for_paper("2506.07883")
have("2506.07883")

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

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

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

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

Connect an agent — have() is free.