SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper · CVPR · 2023

How to Backdoor Diffusion Models?

Pin-Yu Chen, Sheng-Yen Chou, Tsung-Yi Ho

Code that ran

8 of 15 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 5 have no contract verdict; 3 failures of our instrument; 7 no recorded run), measured 2026-11-22; 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/Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper.json · badge: /api/ran/Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper.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
IBM/BadDiffusion canonical (classifier label)
classifier basis: census
8 ran · 7 no recorded run
FunctionStatusWhere it lives
auto_rows_cols Ran
ran on a synthesized input
IBM/BadDiffusion/anp_util.py
code served (permissive licence) · get_code("35d6234d5937647b")
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 int; 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 numpy as np

ARGS = {
    "n": 12,
    "rows": None,
    "cols": None,
}
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 tuple, ndim 1, dtype family int — 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
batch_sampling Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
IBM/BadDiffusion/model.py
pointer only (licence: Apache-2.0); the stored copy get_code serves, from invisibletriggerdiffusion/invisible_triggers_for_diffusion, is pointer only (licence: NONE) · get_code("68b412f99839b629")
How it ran

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

get_grid_size Ran
ran on a synthesized input
IBM/BadDiffusion/anp_util.py
code served (permissive licence) · get_code("92940c6c2beee371")
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 int; 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 numpy as np

def get_grid_size(n: int):
    if n <= 0:
        return (0, 0)
    sqrt_min = int(np.floor(np.sqrt(n)))
    for r in reversed(range(sqrt_min + 1)):
        if n % r == 0:
            c = n // r
            return (r, c)
    return (r, c)

ARGS = {
    "n": 12
}
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 tuple, ndim 1, dtype family int — 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
normalize Ran
ran on a synthesized input
IBM/BadDiffusion/util.py
code served (permissive licence) · get_code("3b79327399fa95f6")
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 float, shape (2, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

torch.manual_seed(0)

# Create a small numpy array for testing
x_numpy = np.array([[1.0, 2.0, 3.0, 4.0],
                     [5.0, 6.0, 7.0, 8.0]])

# Create a small torch tensor for testing
x_torch = torch.tensor([[1.0, 2.0, 3.0, 4.0],
                        [5.0, 6.0, 7.0, 8.0]])

# Define ARGS with all parameters
ARGS = {
    'x': x_numpy,
    'vmin_in': None,
    'vmax_in': None,
    'vmin_out': 0,
    'vmax_out': 1,
    'eps': 1e-05
}
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 ndarray, 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
p_losses_diffuser Ran
ran; our contract draft was wrong, not the code
IBM/BadDiffusion/loss.py
code served (permissive licence) · get_code("82fe5c3e9ba22a97")
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 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
from torch import nn
import torch.nn.functional as F

torch.manual_seed(0)

# Create a minimal noise schedule with required attributes and methods
class MinimalNoiseSchedule:
    def __init__(self):
        # Create alphas_cumprod and alphas tensors
        # These are typically decreasing schedules for diffusion
        num_timesteps = 10
        self.alphas_cumprod = torch.linspace(1.0, 0.1, num_timesteps)
        self.alphas = torch.linspace(1.0, 0.5, num_timesteps)
    
    def add_noise(self, x_start, noise, timesteps):
        """Add noise to x_start at given timesteps"""
        alphas_cumprod = self.alphas_cumprod.to(device=x_start.device, dtype=x_start.dtype)
        t = timesteps[0].item() if timesteps.dim() > 0 else timesteps.item()
        sqrt_alpha = alphas_cumprod[t] ** 0.5
        sqrt_one_minus_alpha = (1 - alphas_cumprod[t]) ** 0.5
        return sqrt_alpha * x_start + sqrt_one_minus_alpha * noise

# Create a minimal model that matches how it's used in p_losses_diffuser
class MinimalDiffusionModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
    
    def forward(self, x, timesteps, return_dict=False):
        # x shape: [batch, 4]
        # timesteps shape: [batch]
        # Output should be noise prediction of same shape as x
        noise_pred = self.linear(x)
        if return_dict:
            return {"sample": noise_pred}
        else:
            return (noise_pred,)

# Construct all arguments
noise_sched = MinimalNoiseSchedule()
model = MinimalDiffusionModel()
x_start = torch.randn(2, 4)  # batch_size=2, feature_dim=4
R = torch.randn(2, 4)  # Same shape as x_start
timesteps = torch.tensor([3, 5])  # batch_size=2, values in range [0, 10)
noise = torch.randn(2, 4)  # Same shape as x_start
loss_type = 'l2'

ARGS = {
    'noise_sched': noise_sched,
    'model': model,
    'x_start': x_start,
    'R': R,
    'timesteps': timesteps,
    'noise': noise,
    'loss_type': loss_type
}
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 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
path_gen Ran
ran on a synthesized input
IBM/BadDiffusion/util.py
code served (permissive licence) · get_code("c80b476232d096b6")
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 os
from typing import Union, List

# Analyze the function: path_gen takes lists of strings and floats, and iterates through them
# to build file paths. The first parameter 'dirs' is Union[str, os.PathLike] but is iterated over,
# so it should be a list or iterable of directory paths.

ARGS = {
    "dirs": ["/tmp/model_output", "/tmp/backup"],
    "ckpts": ["v1", "v2"],
    "datasets": ["cifar10", "mnist"],
    "epochs": [10, 20],
    "clean_rates": [0.8, 0.9],
    "poison_rates": [0.1, 0.2],
    "triggers": ["pattern_a", "pattern_b"],
    "targets": ["class_0", "class_1"],
    "postfixes": ["final", "checkpoint"]
}
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 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
q_sample_diffuser Ran
ran on a synthesized input
IBM/BadDiffusion/loss.py
code served (permissive licence) · get_code("f70bd3df0ffba5cd")
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 4, 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 MockNoiseScheduler:
    def __init__(self, num_timesteps=100):
        self.alphas_cumprod = torch.linspace(0.9999, 0.0001, num_timesteps)
        self.alphas = torch.linspace(0.9999, 0.0001, num_timesteps)
    
    def add_noise(self, x_start, noise, timesteps):
        alphas_cumprod = self.alphas_cumprod.to(device=x_start.device, dtype=x_start.dtype)
        sqrt_alphas_cumprod_t = alphas_cumprod[timesteps] ** 0.5
        sqrt_one_minus_alphas_cumprod_t = (1 - alphas_cumprod[timesteps]) ** 0.5
        
        def unqueeze_n(x):
            return x.reshape(len(x_start), *[1] * len(x_start.shape[1:]))
        
        sqrt_alphas_cumprod_t = unqueeze_n(sqrt_alphas_cumprod_t)
        sqrt_one_minus_alphas_cumprod_t = unqueeze_n(sqrt_one_minus_alphas_cumprod_t)
        
        return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise

noise_sched = MockNoiseScheduler(num_timesteps=100)

x_start = torch.randn(2, 4, 3)
R = torch.randn(2, 4, 3)
timesteps = torch.tensor([10, 25])
noise = torch.randn(2, 4, 3)

ARGS = {
    "noise_sched": noise_sched,
    "x_start": x_start,
    "R": R,
    "timesteps": timesteps,
    "noise": noise
}
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, ndim 4, 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
read_json Ran
ran; our contract draft was wrong, not the code
IBM/BadDiffusion/baddiffusion.py
code served (permissive licence) · get_code("410e560ea7b3decb")
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) 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 argparse
import os
import json
import tempfile

# Create a temporary directory to serve as checkpoint directory
temp_dir = tempfile.mkdtemp()

# Create a sample JSON file in the temp directory
sample_data = {"key": "value", "number": 42}
json_file_path = os.path.join(temp_dir, "config.json")
with open(json_file_path, 'w') as f:
    json.dump(sample_data, f)

# Create the args namespace with the checkpoint directory
args = argparse.Namespace(ckpt=temp_dir)

ARGS = {
    "args": args,
    "file": "config.json"
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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
batch_sampling_save Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/model.py
pointer only (licence: Apache-2.0); the stored copy get_code serves, from invisibletriggerdiffusion/invisible_triggers_for_diffusion, is pointer only (licence: NONE) · get_code("ffd3703863aadaca")
How it ran

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

calculate_activation_statistics Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/fid_score.py
code served (permissive licence) · get_code("a17aa1b06ec919e8")
How it ran

no invocation recorded.

calculate_frechet_distance Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/fid_score.py
code served (permissive licence) · get_code("0def50a351111624")
How it ran

no invocation recorded. this sample carries JSON test cases instead of a setup block; get_reference_implementation serves them with the level they back.

get_activations Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/fid_score.py
code served (permissive licence) · get_code("9f5980b8530c7409")
How it ran

no invocation recorded.

match_count Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/util.py
code served (permissive licence) · get_code("249f0aa58e000fbc")
How it ran

no invocation recorded.

write_json Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/anp_config.py
code served (permissive licence) · get_code("a9dabfb1026845ab")
How it ran

no invocation recorded.

write_json Not yet run
unverified (harvested, no recorded run)
IBM/BadDiffusion/anp_util.py
code served (permissive licence) · get_code("0fd705e26a0e56cb")
How it ran

no invocation recorded.

Also present in other papers' code

Of 15 samples lifted from this paper's linked repositories, 15 carry a function identity and 0 do not. Of the 14 distinct functions with an identity, 7 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 7 later) and 7 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
calculate_frechet_distance 74 other papers
32 dated earlier, 24 later, 18 same year, order not determinable
1610.09585 (2016-10)
Conditional Image Synthesis With Auxiliary Classifier GANs
1706.08500 (2017-06)
GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium
1807.11458 (2018-07)
To learn image super-resolution, use a GAN to learn how to do image degradation first
and 71 more not named here
calculate_activation_statistics 10 other papers
7 later, 3 same year, order not determinable
2305.08192 (2023-05)
Diffusion Models for Imperceptible and Transferable Adversarial Attack
2306.06874 (2023-06)
VillanDiffusion: A Unified Backdoor Attack Framework for Diffusion Models
2312.12030 (2023-12)
Towards Accurate Guided Diffusion Sampling through Symplectic Adjoint Method
and 7 more not named here
get_activations 6 other papers
4 later, 2 same year, order not determinable
2306.06874 (2023-06)
VillanDiffusion: A Unified Backdoor Attack Framework for Diffusion Models
2312.12030 (2023-12)
Towards Accurate Guided Diffusion Sampling through Symplectic Adjoint Method
aaai_28602 (2024 (year only))
Reducing Spatial Fitting Error in Distillation of Denoising Diffusion Models
and 3 more not named here
read_json 2 other papers
1 later, 1 same year, order not determinable
2306.06874 (2023-06)
VillanDiffusion: A Unified Backdoor Attack Framework for Diffusion Models
batch_sampling 1 other paper
1 later
2406.00816 (2024-06)
Invisible Backdoor Attacks on Diffusion Models
batch_sampling_save 1 other paper
1 later
2406.00816 (2024-06)
Invisible Backdoor Attacks on Diffusion Models
p_losses_diffuser 1 other paper
1 later
2406.00816 (2024-06)
Invisible Backdoor Attacks on Diffusion Models

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

Diffusion models are state-of-the-art deep learning empowered generative models that are trained based on the principle of learning forward and reverse diffusion processes via progressive noise-addition and denoising. To gain a better understanding of the limitations and potential risks, this paper presents the first study on the robustness of diffusion models against backdoor attacks. Specifically, we propose BadDiffusion, a novel attack framework that engineers compromised diffusion processes during model training for backdoor implantation. At the inference stage, the backdoored diffusion model will behave just like an untampered generator for regular data inputs, while falsely generating some targeted outcome designed by the bad actor upon receiving the implanted trigger signal. Such a critical risk can be dreadful for downstream tasks and applications built upon the problematic model. Our extensive experiments on various backdoor attack settings show that BadDiffusion can consistently lead to compromised diffusion models with high utility and target specificity. Even worse, BadDiffusion can be made cost-effective by simply finetuning a clean pre-trained diffusion model to implant backdoors. We also explore some possible countermeasures for risk mitigation. Our results call attention to potential risks and possible misuse of diffusion models. Our code is available on https://github.com/IBM/BadDiffusion.

For agents

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

get_harvested_code_for_paper("Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper")
get_code_for_paper("Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper")
have("Chou_How_to_Backdoor_Diffusion_Models_CVPR_2023_paper")

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

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

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

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

Connect an agent — have() is free.