SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2510.22851 · NeurIPS · 2025

Semantic Surgery: Zero-Shot Concept Erasure in Diffusion Models

Yan Liu, Jingwen Ye, Yuecong Xu, Lexiang Xiong, Chengyu Liu

arXiv · PDF · Open in the Atlas

Code that ran

17 of 19 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; 3 honoured the contract we drafted, 1 violated it and 0 have no contract verdict; 13 failures of our instrument; 2 no recorded run), measured 2026-11-24; 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/2510.22851.json · badge: /api/ran/2510.22851.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
Lexiang-Xiong/Semantic-Surgery canonical (classifier label)
classifier basis: census
17 ran · 2 no recorded run
FunctionStatusWhere it lives
cache_path Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_ASR.py
code served (permissive licence) · get_code("f4ead451d398bd73")
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 os

def cache_path(folder):
    return os.path.join(folder, 'cache.json')

ARGS = {
    'folder': '/tmp/test_cache'
}
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
compute_similarity Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/src/utils.py
code served (permissive licence) · get_code("31d9b92035c79e97")
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 (2,) 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 two embeddings with shape (batch_size, seq_len, embedding_dim)
# batch_size=2, seq_len=3, embedding_dim=4
embedding1 = torch.randn(2, 3, 4)
embedding2 = torch.randn(2, 3, 4)

ARGS = {
    "embedding1": embedding1,
    "embedding2": embedding2,
}
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 1, dtype family float, shape (2,) — shape (2,) 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
detect_AOD Ran
ran, honoured the contract we drafted
Lexiang-Xiong/Semantic-Surgery/src/detection_aod.py
code served (permissive licence) · get_code("bbb4939397081666")
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 requests
from unittest.mock import Mock, patch
import io

torch_seed = 0

# Create a mock image file object
img = io.BytesIO(b"fake image data")

concept = "person"

api_key = "test_api_key_12345"

url = "https://api.example.com/detect"

ARGS = {
    "img": img,
    "concept": concept,
    "api_key": api_key,
    "url": url,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
requests — 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
draw_boxes_and_save Ran
ran, honoured the contract we drafted
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_aod.py
code served (permissive licence) · get_code("d7478f40ee9494e2")
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 3, dtype family int, shape (480, 640, 3) 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 cv2
import numpy as np
from pathlib import Path
import tempfile
import os

# Create a temporary test image
temp_dir = tempfile.mkdtemp()
image_path = os.path.join(temp_dir, "test_image.jpg")
test_image = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8)
cv2.imwrite(image_path, test_image)

# Create result dictionary with detection data
result = {
    'data': [
        [
            {
                'label': 'airplane',
                'score': 0.95,
                'bounding_box': [50, 60, 150, 180]
            },
            {
                'label': 'automobile',
                'score': 0.87,
                'bounding_box': [200, 100, 350, 250]
            },
            {
                'label': 'unknown',
                'score': 0.72,
                'bounding_box': [400, 150, 500, 300]
            }
        ]
    ]
}

# Create save path
save_path = os.path.join(temp_dir, "output", "result.jpg")

# Create custom color map
color_map = {
    'airplane': (0, 255, 0),
    'automobile': (0, 0, 255),
    'unknown': (255, 165, 0),
    'default': (255, 0, 0)
}

ARGS = {
    'image_path': image_path,
    'result': result,
    'save_path': save_path,
    'font_scale': 0.8,
    'thickness': 2,
    'color_map': color_map
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
cv2, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 3, dtype family int, shape (480, 640, 3) — shape (480, 640, 3) 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
extract_celebrity_name Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_gcd.py
code served (permissive licence) · get_code("bd1f73e052a52c82")
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 re

def extract_celebrity_name(text):
    patterns = ['A portrait of (.*)_(\\d+)\\.png', 'An image capturing (.*) at a public event_(\\d+)\\.png', 'An oil painting of (.*)_(\\d+)\\.png', 'A sketch of (.*)_(\\d+)\\.png', '(.*) in an official photo_(\\d+)\\.png']
    no_match = True
    for pattern in patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1)
    if no_match:
        print(text)
        raise ValueError('The input image name does not match any of the expected patterns.')

# Test cases with valid patterns
test_text = "A portrait of Brad_Pitt_1.png"

ARGS = {
    "text": test_text
}
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
file_hash Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_ASR.py
code served (permissive licence) · get_code("2a745b1635a32599")
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 tempfile
import os

# Create a temporary file with some content
temp_file = tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix='.txt')
temp_file.write(b'This is test file content for hashing.')
temp_file.close()
temp_path = temp_file.name

ARGS = {
    'path': temp_path
}
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_cache_file_path Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_nudity.py
code served (permissive licence) · get_code("14b4b6b059bebe6b")
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 os
import tempfile

ARGS = {
    'folder_path': tempfile.gettempdir(),
    'cache_file_name': 'cache.json'
}
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_concept_detected_with_owlvit Ran
ran, violated the contract we drafted
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_owl_vit.py
code served (permissive licence) · get_code("74bd6e7cc65d3067")
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 torch
import torch.nn as nn
from PIL import Image
import io

torch.manual_seed(0)

class MockOWLProcessor:
    def __call__(self, text, images, return_tensors='pt'):
        """Mock processor that returns inputs dict"""
        return MockProcessorOutput()
    
    def post_process_object_detection(self, outputs, target_sizes, threshold=0.1):
        """Mock post-processing that returns detection results"""
        return [{'scores': torch.tensor([0.5, 0.6])}]

class MockProcessorOutput:
    def to(self, device):
        return self
    
    def keys(self):
        return ['pixel_values', 'input_ids']
    
    def __getitem__(self, key):
        if key == 'pixel_values':
            return torch.randn(1, 3, 4, 4)
        elif key == 'input_ids':
            return torch.randint(0, 100, (1, 5))
        return torch.randn(1, 4)
    
    def __iter__(self):
        return iter(['pixel_values', 'input_ids'])

class MockOWLModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 2)
    
    def forward(self, **kwargs):
        """Mock forward that returns detection outputs"""
        batch_size = 1
        output = MockModelOutput()
        return output

class MockModelOutput:
    pass

def create_temp_image():
    """Create a small temporary image file"""
    img = Image.new('RGB', (8, 8), color='red')
    temp_path = '/tmp/test_owl_image.png'
    img.save(temp_path)
    return temp_path

# Set up globals
OWL_MODEL = MockOWLModel()
OWL_PROCESSOR = MockOWLProcessor()

# Create a temporary image
image_path = create_temp_image()

ARGS = {
    'image_path': image_path,
    'concept': 'dog',
    'device': 'cpu',
    'score_threshold': 0.1
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
PIL, torch — 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
get_file_hash Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_nudity.py
code served (permissive licence) · get_code("4dd56ebd3bab6032")
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 tempfile
import os

# Create a temporary file with some content
temp_dir = tempfile.mkdtemp()
test_file = os.path.join(temp_dir, "test_file.txt")
with open(test_file, 'w') as f:
    f.write("This is test content for hashing")

ARGS = {
    "file_path": test_file
}
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_selected_alpha Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/src/utils.py
code served (permissive licence) · get_code("7d98b0ac8d4019eb")
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 torch

torch.manual_seed(0)

# alphas_raw is a list of tensors
# The function calls torch.max(alpha).item() on each alpha
# So alphas_raw should be a list of tensors with numeric values

alphas_raw = [
    torch.tensor([[0.5, 0.3], [0.7, 0.2]]),  # 2x2 tensor
    torch.tensor([[0.6, 0.8], [0.4, 0.9]]),  # 2x2 tensor
    torch.tensor([[0.2, 0.3], [0.1, 0.4]]),  # 2x2 tensor
]

# th is a threshold value for filtering
th = 0.7

ARGS = {
    "alphas_raw": alphas_raw,
    "th": th,
}
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 — 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
image_to_bytes Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/src/detection_aod.py
code served (permissive licence) · get_code("18ef7add7df1433c")
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 bytes. 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.

from io import BytesIO
from PIL import Image
import numpy as np

# Create a small test image
# The function expects an Image.Image object and a format string
img_array = np.random.randint(0, 256, (10, 10, 3), dtype=np.uint8)
test_image = Image.fromarray(img_array, mode='RGB')

ARGS = {
    'img': test_image,
    'format': 'JPEG'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
PIL, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bytes — a bytes output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a bytes 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_cache Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_ASR.py
code served (permissive licence) · get_code("f934c875a6a07f36")
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 os
import json
import tempfile

# Create a temporary directory for testing
temp_dir = tempfile.mkdtemp()

# Create a valid cache.json file in the temporary directory
cache_file_path = os.path.join(temp_dir, 'cache.json')
cache_data = {'key1': 'value1', 'key2': 'value2'}
with open(cache_file_path, 'w') as f:
    json.dump(cache_data, f)

# Define ARGS with the folder parameter
ARGS = {
    'folder': temp_dir
}
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_cache Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_nudity.py
code served (permissive licence) · get_code("333c2209ff5831ac")
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 os
import json
import tempfile

# Create a temporary directory for testing
temp_dir = tempfile.mkdtemp()

# Create a test cache file with some sample data
cache_file_path = os.path.join(temp_dir, "test_cache.json")
sample_cache_data = {
    "key1": "value1",
    "key2": ["item1", "item2"],
    "key3": {"nested": "data"}
}

with open(cache_file_path, 'w', encoding='utf-8') as f:
    json.dump(sample_cache_data, f)

ARGS = {
    "cache_file_path": cache_file_path
}
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_detector Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
Lexiang-Xiong/Semantic-Surgery/src/Inference_cli.py
code served (permissive licence) · get_code("5062c88d8f92da72")
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 MockNudeDetection. 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 sys
from pathlib import Path
from unittest.mock import MagicMock, patch

torch.manual_seed(0)

# Test case 1: NudeDetection detector
detector_config_nude = {
    'type': 'NudeDetection',
    'params': {
        'model_name': 'test_model',
        'threshold': 0.5
    }
}

# Mock the NudeDetection class
class MockNudeDetection:
    def __init__(self, **kwargs):
        self.model_name = kwargs.get('model_name')
        self.threshold = kwargs.get('threshold')

# Test case 2: ConcurrentObjectDetection detector
detector_config_aod = {
    'type': 'ConcurrentObjectDetection',
    'params': {
        'num_workers': 4,
        'batch_size': 8
    }
}

# Mock the ConcurrentObjectDetection class
class MockConcurrentObjectDetection:
    def __init__(self, **kwargs):
        self.num_workers = kwargs.get('num_workers')
        self.batch_size = kwargs.get('batch_size')

# Test case 3: custom detector
detector_config_custom = {
    'type': 'custom',
    'module': 'custom_detection_module',
    'class': 'CustomDetector',
    'args': {
        'param1': 'value1',
        'param2': 42
    }
}

# Mock custom detector class
class CustomDetector:
    def __init__(self, **kwargs):
        self.param1 = kwargs.get('param1')
        self.param2 = kwargs.get('param2')

# Create a mock module
mock_module = type(sys)('custom_detection_module')
mock_module.CustomDetector = CustomDetector
sys.modules['custom_detection_module'] = mock_module

# Test case 4: None/empty config
detector_config_none = None

# Test case 5: Empty dict
detector_config_empty = {}

# Patch the imports so they don't fail
sys.modules['detection_nude'] = MagicMock()
sys.modules['detection_nude'].NudeDetection = MockNudeDetection
sys.modules['detection_aod'] = MagicMock()
sys.modules['detection_aod'].ConcurrentObjectDetection = MockConcurrentObjectDetection

# Use a valid detector config for the main test
ARGS = {
    'detector_config': {
        'type': 'NudeDetection',
        'params': {
            'model_name': 'test_model',
            'threshold': 0.5
        }
    }
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
detection_aod, detection_nude, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MockNudeDetection — a MockNudeDetection output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a MockNudeDetection 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
parse_specify Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/src/SS_inference.py
code served (permissive licence) · get_code("24270e828641d37e")
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

torch.manual_seed(0)

# The function parse_specify takes a string with format "class1:num1,class2:num2,..."
# and returns a dict mapping class names to their counts as integers.
# We need to construct a valid specify_classes string argument.

specify_classes = "cat:5,dog:3,bird:2"

ARGS = {
    "specify_classes": specify_classes
}
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 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_checkpoint Ran
ran, honoured the contract we drafted
Lexiang-Xiong/Semantic-Surgery/src/SS_inference.py
code served (permissive licence) · get_code("3043f283bc83b29d")
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 os
import tempfile
import shutil

# Create a temporary directory for testing
test_dir = tempfile.mkdtemp()

# Create a checkpoint file with a valid integer
checkpoint_file = os.path.join(test_dir, 'checkpoint.txt')
with open(checkpoint_file, 'w') as f:
    f.write('42')

ARGS = {
    'folder': test_dir
}
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 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
sigmoid_kernel Ran
ran; our contract draft was wrong, not the code
Lexiang-Xiong/Semantic-Surgery/src/utils.py
code served (permissive licence) · get_code("e3273240409a3942")
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

torch.manual_seed(0)

# Create small test tensors
similarity = torch.randn(2, 4)  # batch_size=2, some dimension=4
gamma = torch.tensor(1.0)
bias = torch.tensor(0.5)

ARGS = {
    "similarity": similarity,
    "gamma": gamma,
    "bias": bias,
}
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 (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
concurrent_detection Not yet run
unverified (harvested, no recorded run)
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_aod.py
code served (permissive licence) · get_code("78f09e32d34ed9f9")
How it ran

no invocation recorded.

safe_single_detection Not yet run
unverified (harvested, no recorded run)
Lexiang-Xiong/Semantic-Surgery/evaluation/eval_aod.py
code served (permissive licence) · get_code("0e5bae723bce679d")
How it ran

no invocation recorded.

Also present in other papers' code

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

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

With the growing power of text-to-image diffusion models, their potential to generate harmful or biased content has become a pressing concern, motivating the development of concept erasure techniques. Existing approaches, whether relying on retraining or not, frequently compromise the generative capabilities of the target model in achieving concept erasure. Here, we introduce Semantic Surgery, a novel training-free framework for zero-shot concept erasure. Semantic Surgery directly operates on text embeddings before the diffusion process, aiming to neutralize undesired concepts at their semantic origin with dynamism to enhance both erasure completeness and the locality of generation. Specifically, Semantic Surgery dynamically estimates the presence of target concepts in an input prompt, based on which it performs a calibrated, scaled vector subtraction to neutralize their influence at the source. The overall framework consists of a Co-Occurrence Encoding module for robust multi-concept erasure and a visual feedback loop to address latent concept persistence, thereby reinforcing erasure throughout the subsequent denoising process. Our proposed Semantic Surgery requires no model retraining and adapts dynamically to the specific concepts and their intensity detected in each input prompt, ensuring precise and context-aware interventions. Extensive experiments are conducted on object, explicit content, artistic style, and multi-celebrity erasure tasks, demonstrating that our method significantly outperforms state-of-the-art approaches. That is, our proposed concept erasure framework achieves superior completeness and robustness while preserving locality and general image quality(e.g., achieving a 93.58 H-score in object erasure, reducing explicit content to just 1 instance with a 12.2 FID, and attaining an 8.09 H a in style erasure with no MS-COCO FID/CLIP degradation). Crucially, this robustness enables our framework to function as a built-in threat detection system by monitoring concept presence scores, offering a highly effective and practical solution for safer text-to-image generation. Our code is publicly available at https://github.com/Lexiang-Xiong/Semantic-Surgery.

For agents

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

get_harvested_code_for_paper("2510.22851")
get_code_for_paper("2510.22851")
have("2510.22851")

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

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

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

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

Connect an agent — have() is free.