MACE

Shilin-LU活跃维护

MACE 是 CVPR 2024 提出的扩散模型大规模概念擦除方法,能从 Stable Diffusion 等文生图模型中批量移除指定概念,适合做内容安全与版权合规。

[CVPR 2024] "MACE: Mass Concept Erasure in Diffusion Models" (Official Implementation)

暂无版本391star32fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/Shilin-LU/MACE.git
conda create -n mace python=3.10
conda activate mace
conda install pytorch==2.0.1 torchvision==0.15.2 pytorch-cuda=11.7 -c pytorch -c nvidia
pip install diffusers==0.22.0 transformers==4.46.2 huggingface_hub==0.25.2
硬件要求按 README 说明

README 未明确给出训练显存要求;数据准备阶段官方版 Grounded-SAM 可在 24GB 显存 GPU 上运行,HuggingFace 版约需 28GB 内存。

支持 Apple Silicon需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

CVPR 2024 开源实现,用闭式解与 LoRA 微调从扩散模型中批量擦除最多 100 个概念

MACE 是 CVPR 2024 提出的扩散模型大规模概念擦除方法,能从 Stable Diffusion 等文生图模型中批量移除指定概念,适合做内容安全与版权合规。

核心能力

  • 用闭式解精修 cross-attention 投影矩阵,抑制目标短语残留信息
  • 为每个待擦除概念单独训练一个 LoRA 模块
  • 闭式解融合多个 LoRA,避免模块互相干扰与灾难性遗忘
  • 支持物体、名人、艺术风格、露骨内容四类擦除任务
  • 提供已微调的 Stable Diffusion v1.4 权重可直接采样

容易踩的坑

训练前需先用 Grounded-SAM 为每个概念生成 8 张图及分割掩码,官方版安装流程较复杂,可改用 HuggingFace 版但内存需求更高;需从 OneDrive 手动下载预缓存文件放入 ./cache/,否则无法开始擦除训练;文本增强默认调用 OpenAI gpt-3.5-turbo,需设置 OPENAI_API_KEY 或改用 MiniMax 并配置对应环境变量。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    [CVPR 2024] MACE: Mass Concept Erasure in Diffusion Models

    arXiv arXiv

    Official implementation of MACE: Mass Concept Erasure in Diffusion Models.


    Our other works on Concept Erasing/Unlearning:

    Set You Straight: Auto-Steering Denoising Trajectories to Sidestep Unwanted Concepts Leyang Li*, Shilin Lu*, Yan Ren, Adams Wai-Kin Kong [arXiv] [code]


    MACE: Mass Concept Erasure in Diffusion Models

    Shilin Lu, Zilan Wang, Leyang Li, Yanzhu Liu, Adams Wai-Kin Kong CVPR 2024

    Abstract: The rapid expansion of large-scale text-to-image diffusion models has raised growing concerns regarding their potential misuse in creating harmful or misleading content. In this paper, we introduce MACE, a finetuning framework for the task of mass concept erasure. This task aims to prevent models from generating images that embody unwanted concepts when prompted. Existing concept erasure methods are typically restricted to handling fewer than five concepts simultaneously and struggle to find a balance between erasing concept synonyms (generality) and maintaining unrelated concepts (specificity). In contrast, MACE differs by successfully scaling the erasure scope up to 100 concepts and by achieving an effective balance between generality and specificity. This is achieved by leveraging closed-form cross-attention refinement along with LoRA finetuning, collectively eliminating the information of undesirable concepts. Furthermore, MACE integrates multiple LoRAs without mutual interference. We conduct extensive evaluations of MACE against prior methods across four different tasks: object erasure, celebrity erasure, explicit content erasure, and artistic style erasure. Our results reveal that MACE surpasses prior methods in all evaluated tasks.

    teaser


    framework

    (a) Our framework focuses on tuning the prompts-related projection matrices within cross-attention (CA) blocks. (b) The pretrained U-Net's CA blocks are refined using a closed-form solution, discouraging the model from embedding the residual information of the target phrase into surrounding words. (c) For each concept targeted for removal, a distinct LoRA module is learned to eliminate its intrinsic information. (d) A closed-form solution is introduced to integrate multiple LoRA modules without interfering with one another while averting catastrophic forgetting.


    Contents

    Setup

    Creating a Conda Environment

    git clone https://github.com/Shilin-LU/MACE.git
    conda create -n mace python=3.10
    conda activate mace
    conda install pytorch==2.0.1 torchvision==0.15.2 pytorch-cuda=11.7 -c pytorch -c nvidia
    

    Install Grounded-SAM (Official Version) to Prepare Masks for LoRA Tuning

    Note: This installation process can be complex. You may skip this section and use the HuggingFace version to prepare data instead. The official version can run on a 24GB GPU, while the Hugging Face version likely requires above 28GB.

    export AM_I_DOCKER=False
    export BUILD_WITH_CUDA=True
    # export CUDA_HOME=/path/to/cuda-11.7/
    
    cd MACE
    git clone https://github.com/IDEA-Research/Grounded-Segment-Anything.git
    cd Grounded-Segment-Anything
    
    # Install Segment Anything:
    python -m pip install -e segment_anything
    
    # Install Grounding DINO:
    pip install --no-build-isolation -e GroundingDINO
    
    # Install osx:
    git submodule update --init --recursive
    cd grounded-sam-osx && bash install.sh
    
    # Install RAM & Tag2Text:
    git clone https://github.com/xinyu1205/recognize-anything.git
    pip install -r ./recognize-anything/requirements.txt
    pip install -e ./recognize-anything/
    

    Download the pretrained weights of Grounded-SAM.

    cd ..    # cd Grounded-Segment-Anything
    
    # Download the pretrained groundingdino-swin-tiny model:
    wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
    
    # Download the pretrained SAM model:
    wget https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth
    

    Install Other Dependencies

    pip install diffusers==0.22.0 transformers==4.46.2 huggingface_hub==0.25.2
    pip install accelerate openai omegaconf opencv-python
    

    LLM Provider for Text Augmentation

    MACE uses an LLM to generate text augmentations (captions) for the concepts being erased. By default it uses OpenAI (gpt-3.5-turbo), but you can switch to MiniMax (M2.7 / M2.5) via environment variables — no code changes required.

    VariableDefaultDescription
    LLM_PROVIDERopenaiLLM backend: openai or minimax
    MINIMAX_API_KEY—Your MiniMax API key
    MINIMAX_MODELMiniMax-M2.7Model: MiniMax-M2.7, MiniMax-M2.7-highspeed, MiniMax-M2.5, MiniMax-M2.5-highspeed
    OPENAI_API_KEY—Your OpenAI API key (when using the default provider)

    Using MiniMax:

    export LLM_PROVIDER=minimax
    export MINIMAX_API_KEY=your_api_key_here
    # Optional: choose a specific model
    export MINIMAX_MODEL=MiniMax-M2.7   # or MiniMax-M2.5-highspeed for faster inference
    
    python training.py configs/object/erase_ship.yaml
    

    MiniMax's API is OpenAI-compatible (base URL https://api.minimax.io/v1), so the same openai Python SDK is reused — no extra dependencies needed.

    Data Preparation for Training MACE

    To erase concepts, 8 images along with their respective segmentation masks should be generated for each concept. To prepare the data for your intended concept, configure your settings in configs/object/erase_ship.yaml and execute the command:

    Grounded SAM (HuggingFace Version) (~28GB RAM)

    In order to ease the configuration of environment, you can also use transformers-based grounded sam from the file data_preparation_transformers.py. It does not require the CUDA version as long as you can run transformers library.

    CUDA_VISIBLE_DEVICES=0 python data_preparation_transformers.py configs/object/erase_ship.yaml
    

    All you need to do is to determine the deterctor_id and segmenter_id, the default value is detector_id = "IDEA-Research/grounding-dino-base" and segmenter_id = "facebook/sam-vit-huge" in the file. You can also change the threshold hyperparameter to get refined mask.

    Grounded SAM (Official Version) (<24GB RAM)

    CUDA_VISIBLE_DEVICES=0 python data_preparation.py configs/object/erase_ship.yaml
    

    Download Pre-cached Files

    Before beginning the mass concept erasing process, ensure that you have pre-cached the prior knowledge (e.g., MSCOCO) and domain-specific knowledge (e.g., certain celebrities, artistic styles, or objects) you wish to retain.

    • You can download our pre-cached files from this OneDrive folder. Once downloaded, place these files in the ./cache/ for use.

    • Alternatively, to preserve additional knowledge of your choice, you can cache the information by modifying the script src/cache_coco.py.

    Training MACE to Erase Concepts

    After preparing the data, you can specify your training parameters in the same configuration file configs/object/erase_ship.yaml and run the following command:

    CUDA_VISIBLE_DEVICES=0 python training.py configs/object/erase_ship.yaml
    

    Sampling from the Finetuned Model

    The finetuned model can be simply tested by running the following command to generate several images:

    CUDA_VISIBLE_DEVICES=0 python inference.py \
              --num_images 3 \
              --prompt 'your_prompt' \
              --model_path /path/to/saved_model/LoRA_fusion_model \
              --save_path /path/to/save/folder
    

    To produce lots of images based on a list of prompts with with predetermined seeds (e.g., from a CSV file ./prompts_csv/celebrity_100_concepts.csv), execute the command below (the hyperparameter step should be set to the same value as num_processes):

    CUDA_VISIBLE_DEVICES=0,1,2,3 accelerate launch \
              --multi_gpu --num_processes=4 --main_process_port 31372 \
              src/sample_images_from_csv.py \
              --prompts_path ./prompts_csv/celebrity_100_concepts.csv \
              --save_path /path/to/save/folder \
              --model_name /path/to/saved_model/LoRA_fusion_model \
              --step 4
    

    MACE Finetuned Model Weights

    We provide several finetuned Stable Diffusion v1.4 with MACE.

    Concept Type to EraseFinetuned Model
    Object ErasureOneDrive link
    Celebrity ErasureOneDrive link
    Artistic Style ErasureOneDrive link
    Explicit Content ErasureOneDrive link

    Metrics Evaluation

    During our evaluation, we employ various metrics including FID, CLIP score, CLIP classification accuracy, GCD accuracy, and NudeNet detection results.

    • Evaluate FID:
    CUDA_VISIBLE_DEVICES=0 python metrics/evaluate_fid.py --dir1 'path/to/generated/image/folder' --dir2 'path/to/coco/GT/folder'
    
    • Evaluate CLIP score:
    CUDA_VISIBLE_DEVICES=0 python metrics/evaluate_clip_score.py --image_dir 'path/to/generated/image/folder' --prompts_path './prompts_csv/coco_30k.csv'
    
    • Evaluate GCD accuracy. When utilizing this script for detection, please ensure that the content within the input directory consists solely of images, without the need to navigate into subdirectories. This precaution helps prevent errors during the process. (please refer to the GCD installation guideline):
    conda activate GCD
    CUDA_VISIBLE_DEVICES=0 python metrics/evaluate_by_GCD.py --image_folder 'path/to/generated/image/folder'
    
    • Evaluate NudeNet detection results (please refer to the NudeNet installation guideline): Please adjust the threshold here to replicate the results presented in the paper.
    CUDA_VISIBLE_DEVICES=0 python metrics/evaluate_by_nudenet.py --folder 'path/to/generated/image/folder'
    
    • Evaluate CLIP classification accuracy:
    CUDA_VISIBLE_DEVICES=0 python metrics/evaluate_clip_accuracy.py --base_folder 'path/to/generated/image/folder'
    

    Acknowledgments

    We thank the following contributors that our code is based on: Diffusers, Concept-Ablation, Forget-Me-Not, UCE.

    Citation

    If you find the repo (or our other works) helpful, please consider citing.

    @inproceedings{lu2024mace,
      title={Mace: Mass concept erasure in diffusion models},
      author={Lu, Shilin and Wang, Zilan and Li, Leyang and Liu, Yanzhu and Kong, Adams Wai-Kin},
      booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
      pages={6430--6440},
      year={2024}
    }
    
    @article{li2025set,
      title={Set you straight: Auto-steering denoising trajectories to sidestep unwanted concepts},
      author={Li, Leyang and Lu, Shilin and Ren, Yan and Kong, Adams Wai-Kin},
      journal={arXiv preprint arXiv:2504.12782},
      year={2025}
    }