Skip to content

无条件图像生成

无条件图像生成模型在训练过程中不依赖于文本或图像。它仅生成与其训练数据分布相似的图像。

本指南将探讨 train_unconditional.py 训练脚本,帮助你熟悉该脚本,并了解如何根据自己的需求进行调整。

在运行脚本之前,请确保从源代码安装库:

bash
git clone https://github.com/huggingface/diffusers
cd diffusers
pip install .

然后导航到包含训练脚本的示例文件夹并安装所需的依赖项:

bash
cd examples/unconditional_image_generation
pip install -r requirements.txt

初始化一个 🤗 Accelerate 环境:

bash
accelerate config

要设置一个默认的 🤗 Accelerate 环境而不选择任何配置:

bash
accelerate config default

或者,如果你的环境不支持像笔记本这样的交互式 shell,你可以使用:

py
from accelerate.utils import write_basic_config

write_basic_config()

最后,如果你想在自己的数据集上训练模型,请参阅创建用于训练的数据集指南,了解如何创建与训练脚本兼容的数据集。

脚本参数

训练脚本提供了许多参数,帮助你自定义训练过程。所有参数及其描述都在 parse_args() 函数中。该函数为每个参数提供了默认值,例如训练批次大小和学习率,但你也可以在训练命令中设置自己的值。

例如,要使用 bf16 格式通过混合精度加速训练,可以在训练命令中添加 --mixed_precision 参数:

bash
accelerate launch train_unconditional.py \
  --mixed_precision="bf16"

一些基本且重要的参数包括:

  • --dataset_name:Hub 上的数据集名称或训练所用数据集的本地路径
  • --output_dir:保存训练模型的位置
  • --push_to_hub:是否将训练好的模型推送到 Hub
  • --checkpointing_steps:模型训练过程中保存检查点的频率;如果训练中断,可以通过在训练命令中添加 --resume_from_checkpoint 来从该检查点继续训练

带上你的数据集,让训练脚本处理其他所有事情!

训练脚本

数据集预处理和训练循环的代码位于 main() 函数中。如果你需要调整训练脚本,这里是你需要进行修改的地方。

train_unconditional 脚本 初始化一个 UNet2DModel,如果你没有提供模型配置。你可以在需要时在这里配置 UNet。

py
model = UNet2DModel(
    sample_size=args.resolution,
    in_channels=3,
    out_channels=3,
    layers_per_block=2,
    block_out_channels=(128, 128, 256, 256, 512, 512),
    down_block_types=(
        "DownBlock2D",
        "DownBlock2D",
        "DownBlock2D",
        "DownBlock2D",
        "AttnDownBlock2D",
        "DownBlock2D",
    ),
    up_block_types=(
        "UpBlock2D",
        "AttnUpBlock2D",
        "UpBlock2D",
        "UpBlock2D",
        "UpBlock2D",
        "UpBlock2D",
    ),
)

接下来,脚本初始化了一个 调度器优化器

py
# Initialize the scheduler
accepts_prediction_type = "prediction_type" in set(inspect.signature(DDPMScheduler.__init__).parameters.keys())
if accepts_prediction_type:
    noise_scheduler = DDPMScheduler(
        num_train_timesteps=args.ddpm_num_steps,
        beta_schedule=args.ddpm_beta_schedule,
        prediction_type=args.prediction_type,
    )
else:
    noise_scheduler = DDPMScheduler(num_train_timesteps=args.ddpm_num_steps, beta_schedule=args.ddpm_beta_schedule)

# Initialize the optimizer
optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=args.learning_rate,
    betas=(args.adam_beta1, args.adam_beta2),
    weight_decay=args.adam_weight_decay,
    eps=args.adam_epsilon,
)

然后它 加载数据集,你可以指定如何 预处理 它:

py
dataset = load_dataset("imagefolder", data_dir=args.train_data_dir, cache_dir=args.cache_dir, split="train")

augmentations = transforms.Compose(
    [
        transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
        transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
        transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
        transforms.ToTensor(),
        transforms.Normalize([0.5], [0.5]),
    ]
)

最后,训练循环 处理其他所有事情,例如向图像添加噪声、预测噪声残差、计算损失、在指定步骤保存检查点,以及将模型保存并推送到 Hub。如果你想了解更多关于训练循环的工作原理,可以查看 理解管道、模型和调度器 教程,该教程详细介绍了去噪过程的基本模式。

启动脚本

一旦你完成了所有更改或对默认配置满意,就可以启动训练脚本了!🚀

训练脚本会在你的仓库中创建并保存一个检查点文件。现在你可以加载并使用你训练的模型进行推理:

py
from diffusers import DiffusionPipeline
import torch

pipeline = DiffusionPipeline.from_pretrained("anton-l/ddpm-butterflies-128").to("cuda")
image = pipeline().images[0]