Custom Diffusion 项目使用教程
1. 项目介绍
Custom Diffusion 是一个用于多概念定制文本到图像扩散模型的开源项目,由 Adobe Research 开发。该项目在 CVPR 2023 上发布,旨在通过少量图像(约4-20张)对预训练的文本到图像扩散模型(如 Stable Diffusion)进行微调,从而生成新的概念图像。Custom Diffusion 通过仅微调模型中的关键和值投影矩阵,显著减少了计算时间和存储需求,同时支持多概念的组合使用,如新对象与新艺术风格的结合。
2. 项目快速启动
2.1 环境准备
首先,确保你已经安装了必要的依赖项。你可以使用以下命令克隆项目并设置环境:
git clone https://github.com/adobe-research/custom-diffusion.git
cd custom-diffusion
git clone https://github.com/CompVis/stable-diffusion.git
cd stable-diffusion
conda env create -f environment.yaml
conda activate ldm
pip install clip-retrieval tqdm
2.2 下载预训练模型
下载 Stable Diffusion 的预训练模型:
wget https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt
2.3 单概念微调
使用真实图像作为正则化样本进行微调:
# 下载数据集
wget https://www.cs.cmu.edu/~custom-diffusion/assets/data.zip
unzip data.zip
# 运行训练(需要2个GPU,每个30GB)
bash scripts/finetune_real.sh "cat" data/cat real_reg/samples_cat cat finetune_addtoken.yaml <pretrained-model-path>
# 保存更新后的模型权重
python src/get_deltas.py --path logs/<folder-name> --newtoken 1
# 生成样本
python sample.py --prompt "<new1> cat playing with a ball" --delta_ckpt logs/<folder-name>/checkpoints/delta_epoch\=000004.ckpt --ckpt <pretrained-model-path>
3. 应用案例和最佳实践
3.1 单概念定制
通过提供少量图像(如4-20张),用户可以微调 Stable Diffusion 模型,生成特定概念的新图像。例如,用户可以提供几张猫的图像,微调模型后生成不同背景和场景下的猫的图像。
3.2 多概念定制
Custom Diffusion 支持多概念的组合使用。例如,用户可以同时微调一个新对象(如猫)和一个新艺术风格(如木雕),生成具有木雕风格的猫的图像。
3.3 优化权重合并
用户可以通过优化权重合并两个微调后的模型,生成结合两个概念的图像。例如,合并一个微调后的猫模型和一个微调后的木雕模型,生成具有木雕风格的猫的图像。
4. 典型生态项目
4.1 Stable Diffusion
Stable Diffusion 是一个开源的文本到图像扩散模型,Custom Diffusion 基于此模型进行微调。Stable Diffusion 提供了强大的图像生成能力,Custom Diffusion 在此基础上进一步扩展了定制化的功能。
4.2 Diffusers
Diffusers 是一个用于扩散模型的库,支持多种扩散模型的训练和推理。Custom Diffusion 的训练和推理代码也基于 Diffusers 库,用户可以通过 Diffusers 进行更高级的定制和优化。
4.3 Hugging Face Transformers
Hugging Face Transformers 是一个广泛使用的自然语言处理库,支持多种预训练模型的加载和使用。Custom Diffusion 的预训练模型可以通过 Hugging Face Transformers 进行加载和管理。
通过结合这些生态项目,用户可以更灵活地使用 Custom Diffusion,实现更复杂的图像生成任务。