Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Unlearn Diff

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

You can find the full documentation for this project at the following URL: https://ramailotech.github.io/msu_unlearningalgorithm/

Features

  • Comprehensive Algorithm Support: Includes commonly used concept erasing and machine unlearning algorithms tailored for diffusion models. Each algorithm is encapsulated and standardized in terms of input-output formats.

  • Automated Evaluation: Supports automatic evaluation on datasets like UnlearnCanvas or IP2P. Performs standard and adversarial evaluations, outputting metrics as detailed in UnlearnCanvas and UnlearnDiffAtk.

  • Extensibility: Designed for easy integration of new unlearning algorithms, attack methods, defense mechanisms, and datasets with minimal modifications.

Supported Algorithms

The initial version includes established methods benchmarked in UnlearnCanvas and defensive unlearning techniques:

  • CA (Concept Ablation)
  • ED (Erase Diff)
  • ESD (Efficient Substitution Distillation)
  • FMN (Forget Me Not)
  • SU (Saliency Unlearning)
  • SH (ScissorHands)
  • SA (Selective Amnesia)
  • SPM (Semi Permeable Membrane)
  • UCE (Unified Concept Editing) For detailed information on each algorithm, please refer to the respective README.md files located inside mu/algorithms.

Project Architecture

The project is organized to facilitate scalability and maintainability.

.
├── data/
│ ├── i2p-dataset/
│ │ ├── sample/
│ │ └── full/
│ └── unlearn-canvas-dataset/ # Renamed for clarity
│ ├── sample/
│ └── full/
│
├── docs/ # Documentation, API references, user guides
│
├── models/ # Pre-trained model weights (e.g., Stable Diffusion, LORAs)
│
├── notebooks/ # Example notebooks and experimental code (merges 'examples/')
│
├── outputs/ # All generated outputs (images, artifacts) from runs
│
├── scripts/ # Standalone utility scripts
│ ├── download_models.py
│ └── prepare_datasets.py
│
├── src/ # Centralized source code for the entire application
│ │
│ ├── mu/ # Core unlearning logic (previously 'mu/')
│ │ ├── __init__.py
│ │ ├── algorithms/
│ │ │ ├── esd/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── algorithm.py # Core ESD implementation
│ │ │ │ ├── configs/ # ESD-specific configs
│ │ │ │ ├── model.py # ESD-specific model
│ │ │ │ ├── trainer.py # ESD-specific trainer
│ │ │ │ └── utils.py # ESD-specific utilities
│ │ │ └── ca/
│ │ │ └── ... # etc.
│ │ ├── core/ # Base classes shared across unlearning algorithms
│ │ │ ├── base_algorithm.py
│ │ │ ├── base_trainer.py
│ │ │ └── base_model.py
│ │ └── datasets/ # Data handling and loading modules
│ │ ├── __init__.py
│ │ ├── base_handler.py
│ │ └── unlearn_canvas.py
│ │
│ ├── attack/ # Attack logic (previously 'mu_attack/')
│ │ ├── __init__.py
│ │ ├── algorithms/ # Specific attack implementations (previously 'attackers/')
│ │ ├── configs/
│ │ │ ├── illegal/
│ │ │ └── ...
│ │ └── tasks/ # Attack tasks (nudity, violence, etc.)
│ │
│ ├── defense/ # Defense logic (previously 'mu_defense/')
│ │ ├── __init__.py
│ │ └── algorithms/
│ │ └── adv_unlearn/
│ │ ├── __init__.py
│ │ ├── algorithm.py
│ │ ├── configs/
│ │ ├── model.py
│ │ ├── trainer.py
│ │ └── image_generator.py
│ │
│ ├── evaluation/ # Centralized evaluation framework
│ │ ├── __init__.py
│ │ ├── evaluator.py # Main evaluator runner script
│ │ ├── metrics/
│ │ │ ├── accuracy.py
│ │ │ ├── asr.py
│ │ │ ├── clip.py
│ │ │ └── fid.py
│ │ └── utils/ # Evaluation-specific utilities (e.g., log parsers)
│ │ └── parser.py
│ │
│ └── utils/ # Project-wide shared utilities
│ ├── __init__.py
│ ├── logger.py
│ └── path_setup.py
│
├── tests/ # All tests for the source code
│ ├── test_unlearning.py
│ ├── test_attack.py
│ └── test_evaluation.py
│
├── environment.yaml # Project-wide environment dependencies
├── main.py # Main entry point to run training, evaluation, etc.
└── README.md # Project overview and setup instructions

Datasets

We use the Unlearn Canvas benchmark dataset, available here. Currently, the algorithms are trained using 5 images belonging to the themes of Abstractionism and Architectures.

Usage

This section contains the usage guide for the package.

Installation

Prerequisities

Ensure conda is installed on your system. You can install Miniconda or Anaconda:

After installing conda, ensure it is available in your PATH by running. You may require to restart the terminal session:

Before installing the unlearn_diff package, follow these steps to set up your environment correctly. These instructions ensure compatibility with the required dependencies, including Python, PyTorch, and ONNX Runtime.

Step-by-Step Setup:

  1. Create a Conda Environment Create a new Conda environment named myenv with Python 3.8.5:
conda create -n myenv python=3.8.5
  1. Activate the Environment Activate the environment to work within it:
conda activate myenv
  1. Install Core Dependencies Install PyTorch, torchvision, CUDA Toolkit, and ONNX Runtime with specific versions:
conda install pytorch==1.11.0 torchvision==0.12.0 cudatoolkit=11.3 onnxruntime==1.16.3 -c pytorch -c conda-forge
  1. Install our unlearn_diff Package using pip:
pip install unlearn_diff
  1. Install Additional Git Dependencies:

After installing unlearn_diff, install the following Git-based dependencies in the same Conda environment to ensure full functionality:

pip install git+https://github.com/CompVis/taming-transformers.git@master git+https://github.com/openai/CLIP.git@main git+https://github.com/crowsonkb/k-diffusion.git git+https://github.com/cocodataset/panopticapi.git git+https://github.com/Phoveran/fastargs.git@main git+https://github.com/boomb0om/text2image-benchmark

The <algorithm_name> has to be one of the folders in the mu/algorithms folder.

Downloading data and models.

After you install the package, you can use the following commands to download.

  1. Dataset:

    • unlearn_canvas:

      • Sample:
      download_data sample unlearn_canvas
      
      • Full:
      download_data full unlearn_canvas
      
    • i2p:

      • Sample:
      download_data sample i2p
      
      • Full:
      download_data full i2p
      
  2. Model:

    • compvis:
      download_model compvis
      
    • diffuser:
      download_model diffuser
      
  3. Download best.onnx model

download_best_onnx
  1. Download coco dataset
download_coco_dataset

Run Train

Each algorithm has their own script to run the algorithm, Some also have different process all together. Follow usage section in readme for the algorithm you want to run with the help of the github repository. You will need to run the code snippet provided in usage section with necessary configuration passed.

Example usage for erase_diff algorithm (CompVis model)

The default configuration for training is provided by erase_diff_train_mu. You can run the training with the default settings as follows:

Using the Default Configuration

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu
)
algorithm.run()



Overriding the Default Configuration

If you need to override the existing configuration settings, you can specify your custom parameters (such as ckpt_path and raw_dataset_dir) directly when initializing the algorithm. For example:

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_mualgorithm=EraseDiffAlgorithm(
erase_diff_train_mu,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/quick-canvas-dataset/sample",
use_sample=True, #uses sample datasettemplate_name="Abstractionism",
dataset_type="unlearncanvas",
devices="0"
)
algorithm.run()


Note: When fine-tuning the model, if you want to use a sample dataset, set use_sample=True (default).Otherwise, set use_sample=False to use the full dataset.

Machine unlearning with i2p dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/i2p-dataset/sample",
num_samples=1,
dataset_type="i2p",
template="i2p",
template_name="self-harm",
use_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Run on your own dataset

Step-1: Generate your own dataset

generate_images_for_prompts --model_path models/diffuser/style50 --csv_path data/prompts/generic_data.csv

Note:

  • generate_images_for_prompts: This command invokes the image generation script. It uses a diffusion model to generate images based on textual prompts.

  • --model_path: Specifies the path to the diffusion model to be used for image generation. In this example, the model is located at models/diffuser/style50.

  • --csv_path: Provides the path to a CSV file containing the prompts. Each prompt in this CSV will be used to generate an image, allowing you to build a dataset tailored to your needs.

Step-2: Train on your own dataset

frommu.algorithms.erase_diff.algorithmimportEraseDiffAlgorithmfrommu.algorithms.erase_diff.configsimporterase_diff_train_i2palgorithm=EraseDiffAlgorithm(
erase_diff_train_i2p,
ckpt_path="/home/ubuntu/Projects/UnlearnCanvas/UnlearnCanvas/machine_unlearning/models/compvis/style50/compvis.ckpt", #replace it with your ckpt pathraw_dataset_dir="data/generic_data",
num_samples=1,
dataset_type="generic", #add the dataset type as generictemplate_name="self-harm", #concept to eraseuse_sample=True, #uses sample datasetdevices="0"
)
algorithm.run()

Evaluation:

  1. Evaluate using unlearn canvas dataset:

Note: Currently it supports evaluation for unlearn canvas dataset. I2p and generic dataset support needs to be added.

frommu.algorithms.erase_diffimportEraseDiffEvaluatorfrommu.algorithms.erase_diff.configsimport (
erase_diff_evaluation_config
)
fromevaluation.metrics.accuracyimportaccuracy_scorefromevaluation.metrics.clipimportclip_scorefromevaluation.metrics.fidimportfid_scoreevaluator=EraseDiffEvaluator(
erase_diff_evaluation_config,
ckpt_path="outputs/erase_diff/finetuned_models/erase_diff_self-harm_model.pth",
)
generated_images_path=evaluator.generate_images()
accuracy=accuracy_score(gen_image_dir=generated_images_path,
dataset_type="unlearncanvas",
classifier_ckpt_path="/home/ubuntu/Projects/models/classifier_ckpt_path/style50_cls.pth",
forget_theme="Bricks",
seed_list= ["188"] )
print(accuracy['acc'])
print(accuracy['loss'])
fid, _=fid_score(generated_image_dir=generated_images_path) #Defaults to the COCO dataset if reference_image_dir is not provided."print(fid)
clip_score=clip_score() #Defaults to the COCO dataset if image path is not provided."print(clip_score)
#Optionally if you want to use your own datasetreference_image_dir="data/quick-canvas-dataset/sample"fid, _=fid_score(generated_image_dir=generated_images_path,
reference_image_dir=reference_image_dir)
print(fid)

Classifiers for evaluation

Nudenet classifier

Requirements for Testing:

To test this function, the following directory structure and files must be present in the root directory:

  • imgs/ folder - Must be located inside the root directory (data/i2p/imgs/)

  • prompts.csv file - Must be present in the root directory (data/i2p/prompts.csv)

fromevaluation.metrics.nudenetimportprocess_nudity_classificationprocess_nudity_classification()
#Optionally, to run with custom parametersprocess_nudity_classification(root='data/i2p', mode='check_none_nude', threshold=0.5)

Q16 classifier

importtorchfromevaluation.metrics.q16importq16_binary_classifier, harm_evalDEVICE="cuda"iftorch.cuda.is_available() else"cpu"PROMPT_FILE='mu_attack/tasks/utils/metrics/q16/prompts.p'#replace with your own pathIMAGE_TO_TEST='data/i2p/imgs/image_test.png'#replace with your own test image pathclip_model, classifier=q16_binary_classifier(device=DEVICE, prompt_path=PROMPT_FILE)
label, scores=harm_eval(clip_model, classifier, IMAGE_TO_TEST, DEVICE)
label_text="Benign"iflabel==0else"Malicious"print(f"\nFinal Label: {label} ({label_text})")
print(f"Confidence Scores:")
print(f" - Benign: {scores[0].item():.4f}")
print(f" - Malicious: {scores[1].item():.4f}")

Link to our example usage notebooks

  1. Erase-diff (compvis model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_erase_diff.ipynb

  1. forget-me-not (Diffuser model)

https://github.com/RamailoTech/msu_unlearningalgorithm/blob/main/notebooks/run_forget_me_not.ipynb

About

Unlearn Diff is an open-source Python package designed to streamline the development of unlearning algorithms and establish a standardized evaluation pipeline for diffusion models. It provides researchers and practitioners with tools to implement, evaluate, and extend unlearning algorithms effectively.

Resources

Contributing

Stars

7 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages