Diffusers 是huggingface开源的应用扩散模型的python库,用于生成图像、音频甚至分子的3D结构。Diffusers提供简单的推理解决方案以及训练自己的扩散模型,使用起来具有较好的可用性,同时非常的简单,支持多种diffusion模型以及算法,只需几行代码就可以实现diffusion的效果,同时对于civitai等开源模型可以无缝对接。
网站:https://huggingface.co/docs/diffusers/v0.19.3/en/index
Github:https://github.com/huggingface/diffusers
零、安装
这个自行查看:https://huggingface.co/docs/diffusers/v0.19.3/en/installation
一、如何简单推理diffusion model
- 一个简单的DDPM的例子
1 | from diffusers import DDPMPipeline |
- 一个简单的stable diffusion的例子
1 | import torch |
二、如何加载civitai的模型?
- 如果是civitai提供的checkpoint,可以使用diffusers提供的scripts下面的convert_original_stable_diffusion_to_diffusers.py转换一下,就可以直接用上面的demo加载了。
三、如何加载civitai的lora模型?
- 可以使用diffusers提供的scripts下面的convert_lora_safetensor_to_diffusers.py将下载下来的准换,就可以利用 pipe.unet.load_attn_procs(lora_path),进行加载了。
- 可以直接使用 pipe.load_lora_weights(lora_path),进行加载。推荐
1 | ## lora模型下载地址 wget https://civitai.com/api/download/models/15603 -O light_and_shadow.safetensors |
四、如下实现stable diffusion lora的训练
- 数据集的准备(数据集需要有图像和文本),如下形式:
1 | # 文件夹如下: |
- 准备好数据后,就可以使用example\text_to_image\train_text_to_image_lora.py 脚本进行训练了。
- 训练好后,会保存lora的weight,然后就可以使用前面加载lora的方法,进行测试了。
备注一些基础知识:
1、训练:
优化器还是adamw
DDPMScheduler,# 这个东西比较重要,这个是加噪声的方式,如下这样
1 | noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) |
训练的主要步骤就是:
- 取图像
- 生成noise, torch.randn()
- 生成迭代次数
- 加噪声
- 模型前向预测噪声
- 预测噪声与噪声做loss
- backward
- diffusers提供了很多的管道类
1 | from diffusers import DiffusionPipeline |
2、Safety checker
模型默认会带一个nsfw的检测,所以使用safety_checker=None就不会使用这个checker了
1 | stable_diffusion = DiffusionPipeline.from_pretrained(repo_id, safety_checker=None) |
3、组件重用
1 | from StableDiffusionPipeline,StableDiffusionImg2ImgPipeline |