| # 第五章 微调和引导 | |
| ## 5.1 章节概述 | |
| 在这一章节中,我们将讲解基于现有模型实现**模型改造**的方法,主要实现方法有两种: | |
| * **微调(fine-tuning)**:通过在新的数据集上重新训练现有模型,来改变原有模型的生成类型 | |
| * **引导(guidance)**:通过在推理阶段对现有模型加入额外的控制信息,来引导原有模型某些特性的生成过程 | |
| #### 你将学到: | |
| 到本章结束时,你将学会: | |
| - 创建一个采样循环,并使用新调度器(scheduler)更快地完成采样 | |
| - 在新数据集上基于现有的扩散模型微调,具体包括: | |
| - 使用梯度累加(gradient accumulation)方法来应对训练硬件条件不足对 batch size 的限制 | |
| - 上传训练样本和日志(通过附带的脚本程序)至 [Weights and Biases](https://wandb.ai/site) 网站,以此来监控训练过程 | |
| - 保存最终结果管线(pipeline)并上传到 Hub | |
| - 通过引入损失函数来引导采样过程,以此来对现有的扩散模型施加控制,具体包括: | |
| - 从一个简单的基于颜色的损失函数开始,进而探索多种不同的引导方法 | |
| - 使用 CLIP,用文本来引导生成过程 | |
| - 在 Gradio 和 🤗 Spaces 上分享你定制的采样循环方法 | |
| ❓ 如果你有任何问题,欢迎在 Hugging Face Discord 的 `#diffusion-models-class` 频道留言。如果你还没有 Discord 账号,可以点击这里注册:https://huggingface.co/join/discord | |
| ## 5.2 环境准备 | |
| #### 配置过程和需要引入的库 | |
| 模型训练完成后,如果要将改造过的模型上传到 Hugging Face Hub 上,你需要先登录 Hugging Face 账号,获取一个 **具有写入权限的访问令牌**。运行下列代码可以帮助你登录账号并跳转到相关页面配置令牌。 | |
| 同样地,在模型训练过程中,如果你想记录样本和日志来监控训练过程,你还需要一个 Weights and Biases 账号。不用担心,在需要登录账号时,也会有相应代码指引。 | |
| 除此之外,你还需要安装一些依赖库并在程序中按需引入,以及指定计算设备,这样就全部配置完成了。代码如下: | |
| ```python | |
| !pip install -qq diffusers datasets accelerate wandb open-clip-torch | |
| ``` | |
| ```python | |
| # 登录 Hugging Face Hub,分享模型 | |
| # 请确保访问令牌具有写入权限 | |
| from huggingface_hub import notebook_login | |
| notebook_login() | |
| ``` | |
| Token is valid. | |
| Your token has been saved in your configured git credential helpers (store). | |
| Your token has been saved to /root/.huggingface/token | |
| Login successful | |
| ```python | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| import torchvision | |
| from datasets import load_dataset | |
| from diffusers import DDIMScheduler, DDPMPipeline | |
| from matplotlib import pyplot as plt | |
| from PIL import Image | |
| from torchvision import transforms | |
| from tqdm.auto import tqdm | |
| ``` | |
| ```python | |
| device = ( | |
| "mps" | |
| if torch.backends.mps.is_available() | |
| else "cuda" | |
| if torch.cuda.is_available() | |
| else "cpu" | |
| ) | |
| ``` | |
| ## 5.3 载入一个预训练过的管线 | |
| 首先我们载入一个现有的管线,来看看它能为我们做些什么: | |
| ```python | |
| image_pipe = DDPMPipeline.from_pretrained("google/ddpm-celebahq-256") | |
| image_pipe.to(device); | |
| ``` | |
| Fetching 4 files: 0%| | 0/4 [00:00<?, ?it/s] | |
| 我们可以用它来生成图像,非常简单!只需调用管线的内置 [`__call__`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddpm/pipeline_ddpm.py#L42) 方法,跟调用函数的方式一样: | |
| ```python | |
| images = image_pipe().images | |
| images[0] | |
| ``` | |
| 0%| | 0/1000 [00:00<?, ?it/s] | |
|  | |
| 代码非常简洁!但如果你实际运行了这些代码,你会发现生成速度还是有点慢的!所以为了在后面正式介绍微调和引导的时候,我们能够更快地看到生成图像的效果,我们首先探讨一下如何加速采样循环(也就是生成过程)。 | |
| ## 5.4 DDIM调度器-更快的采样过程 | |
| 采样循环可以使用调度器(scheduler)来实现。在这一小节中,我们先窥探一下采样循环实际运行起来是什么样的,再介绍一些能够大幅加速采样的调度器。 | |
| 采样循环运行原理:在生成图像的每一个采样步骤中,模型都会接收一个噪声输入,同时输出预测的噪声残差(以此来估计不含噪声的完整图像是什么样的)。采样初期,模型的预测结果不会特别好,因此我们需要把采样过程更精细地分解成更多步骤。但另一方面,使用更长的采样步骤(如 1000+ 步)也没必要,最近的很多研究已经找到了保证生成图像质量的同时尽可能地减少采样步骤的方法。 | |
| 在 🤗 Diffusers 库中,这些 **采样方法是通过调度器类(scheduler)来控制的**,每次采样通过 `step()` 函数完成。要生成目标图片,我们首先随机化一个初始噪声 $x$,在每个时间步(timestep)的采样中,调度器都会把噪声 $x$ 输入给模型,同时把模型的预测结果再次输入给 `step()` 函数。`step()` 函数返回输出的 `prev_sample` 属性就是下一次采样的输入噪声,之所以叫 “previous”,是因为我们在时间上是 “落后” 的,即从 “高噪声” 到 “低噪声”(这和前向扩散过程是相反的)。 | |
| 我们来实践一下:先载入一个 scheduler,这里用的是 DDIMScheduler(基于这篇论文:[Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502))。与原版的 DDPM 相比,它可以用少得多的采样步骤来生成效果相当的图像样本。 | |
| ```python | |
| # 创建 DDIM 调度器实例,设置采样步数 | |
| scheduler = DDIMScheduler.from_pretrained("google/ddpm-celebahq-256") | |
| scheduler.set_timesteps(num_inference_steps=40) | |
| ``` | |
| 可以看到,用 DDIM 调度器之后,模型仅需采样 40 步,每一步采样相当于 1000 步普通调度器的 25 次采样: | |
| ```python | |
| scheduler.timesteps | |
| ``` | |
| tensor([975, 950, 925, 900, 875, 850, 825, 800, 775, 750, 725, 700, 675, 650, | |
| 625, 600, 575, 550, 525, 500, 475, 450, 425, 400, 375, 350, 325, 300, | |
| 275, 250, 225, 200, 175, 150, 125, 100, 75, 50, 25, 0]) | |
| 我们来随机初始化 4 张噪声图像,把它们输入给采样循环,观察一下每一步的噪声 $x$ 和预测的去噪图像: | |
| ```python | |
| # 随机初始化 4 张 噪声图像 | |
| x = torch.randn(4, 3, 256, 256).to(device) # 图像数量 为 4, 分辨率为 256x256, 通道数为 3 | |
| # 采样循环 | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| # 模型输入 | |
| model_input = scheduler.scale_model_input(x, t) | |
| # 预测结果 | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| # 查看调度器采样更新的输出 | |
| scheduler_output = scheduler.step(noise_pred, t, x) | |
| # 更新 x | |
| x = scheduler_output.prev_sample | |
| # 以一定的采样间隔可视化噪声 x 和去噪图像 | |
| if i % 10 == 0 or i == len(scheduler.timesteps) - 1: | |
| fig, axs = plt.subplots(1, 2, figsize=(12, 5)) | |
| grid = torchvision.utils.make_grid(x, nrow=4).permute(1, 2, 0) | |
| axs[0].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5) | |
| axs[0].set_title(f"Current x (step {i})") | |
| pred_x0 = ( | |
| scheduler_output.pred_original_sample | |
| ) # 并非适用所有的调度器 | |
| grid = torchvision.utils.make_grid(pred_x0, nrow=4).permute(1, 2, 0) | |
| axs[1].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5) | |
| axs[1].set_title(f"Predicted denoised images (step {i})") | |
| plt.show() | |
| ``` | |
| 0it [00:00, ?it/s] | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 可以看出,采样初期的预测结果并不是那么好,但随着采样循环的迭代,预测的结果被一步步改善。如果你想了解 `steps()` 函数内的数学原理,可以通过下面这行指令查看(运行时请去掉注释符)详细代码: | |
| ```python | |
| # ??scheduler.step | |
| ``` | |
| 你也可以直接把原有管线(pipeline)中的调度器替换为新的调度器,然后采样循环试试看。代码如下: | |
| ```python | |
| image_pipe.scheduler = scheduler | |
| images = image_pipe(num_inference_steps=40).images | |
| images[0] | |
| ``` | |
| 0%| | 0/40 [00:00<?, ?it/s] | |
|  | |
| 好了!现在我们能在可接受的时间内生成图片了!这样我们在接下来的章节就能更快地学习和实践了:) | |
| ## 5.5 扩散模型-微调 | |
| 现在来玩点好玩的--用我们自己的数据来训练模型,让模型生成我们想要的图片类型!我们将使用 5.3 小节中已经载入好的预训练管线,来让模型学习我们的新数据。这就要使用到本小节将介绍的一项技术:微调。 | |
| 具体应该怎么做呢?看起来和从零训练模型(如第三章示例)几乎是一样的,仅有一点不同:**微调模型使用现有模型作为初始化,而从零训练模型则使用随机初始化。** | |
| 实际上还有一些额外的因素要考虑,接下来让我们在代码实战中看看都有哪些要注意的。 | |
| ### 5.5.1 实战:微调 | |
| 首先我们要准备自己的数据集。数据方面,最好是用一些与 5.3 小节中人脸生成管线中类似的训练数据,可以尝试用 [Vintage Faces 数据集](https://huggingface.co/datasets/Norod78/Vintage-Faces-FFHQAligned) 或者 [动漫人脸数据集](https://huggingface.co/datasets/huggan/anime-faces)。 | |
| 不过这里我们先浅尝一下,仍然用第三章中使用过的蝴蝶数据集训练。如果你还没有下载过该数据集,可以运行以下代码来获取,同时创建一个能按批次(batch)选取训练图片的 `dataloader` 实例,以及可视化查看蝴蝶图片: | |
| ```python | |
| # @markdown 加载、准备数据集: | |
| # 如果你不是在 Colab 上运行本书代码,请把带有 #@ 部分的代码(是 Colab 用于调整 UI 界面用的)注释掉,这样你在其他平台上运行也不会报错。 | |
| dataset_name = "huggan/smithsonian_butterflies_subset" # @param | |
| dataset = load_dataset(dataset_name, split="train") | |
| image_size = 256 # @param | |
| batch_size = 4 # @param | |
| preprocess = transforms.Compose( | |
| [ | |
| transforms.Resize((image_size, image_size)), | |
| transforms.RandomHorizontalFlip(), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.5], [0.5]), | |
| ] | |
| ) | |
| def transform(examples): | |
| images = [preprocess(image.convert("RGB")) for image in examples["image"]] | |
| return {"images": images} | |
| dataset.set_transform(transform) | |
| train_dataloader = torch.utils.data.DataLoader( | |
| dataset, batch_size=batch_size, shuffle=True | |
| ) | |
| print("Previewing batch:") | |
| batch = next(iter(train_dataloader)) | |
| grid = torchvision.utils.make_grid(batch["images"], nrow=4) | |
| plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5); | |
| ``` | |
| Using custom data configuration huggan--smithsonian_butterflies_subset-7665b1021a37404c | |
| Found cached dataset parquet (/home/lewis_huggingface_co/.cache/huggingface/datasets/huggan___parquet/huggan--smithsonian_butterflies_subset-7665b1021a37404c/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec) | |
| Previewing batch: | |
|  | |
| > **考虑因素1:** batch size 大小。 | |
| > | |
| > 本书中加载的管线都是基于 256x256 px 尺寸的图片来设计和训练的,同时模型的参数量也非常多,再加上 GPU RAM 有限,因此这里设置的 batch size 很小(只有 4)。如果你想加速模型训练过程,可以考虑缩小图片尺寸来换取更大的 batch size。 | |
| 其次我们要设计训练过程。由于仅需要现有模型额外学习到准备的新数据即可,因此我们把要优化的目标参数设置为现有模型的 UNet 部分的权重:`image_pipe.unet.parameters()`,并且设置较小的学习率,以此来小幅度地更新现有模型的 UNet 权重。除此之外的其它训练代码基本上和第三章中的样例相同。 | |
| 训练部分相关代码如下。如果你是在 Colab 上运行这些代码,整个过程大约需要 10 分钟,你可以趁这个时间间隙喝杯茶休息一下。 | |
| ```python | |
| num_epochs = 2 # @param | |
| lr = 1e-5 # @param | |
| grad_accumulation_steps = 2 # @param | |
| optimizer = torch.optim.AdamW(image_pipe.unet.parameters(), lr=lr) | |
| losses = [] | |
| for epoch in range(num_epochs): | |
| for step, batch in tqdm(enumerate(train_dataloader), total=len(train_dataloader)): | |
| clean_images = batch["images"].to(device) | |
| # 生成要加到图片上的随机采样噪声 | |
| noise = torch.randn(clean_images.shape).to(clean_images.device) | |
| bs = clean_images.shape[0] | |
| # 对每张图片设置随机采样时间步 | |
| timesteps = torch.randint( | |
| 0, | |
| image_pipe.scheduler.num_train_timesteps, | |
| (bs,), | |
| device=clean_images.device, | |
| ).long() | |
| # 根据每个采样时间步的噪声大小,把噪声加到原始图片上 | |
| # (这就是前向扩散过程) | |
| noisy_images = image_pipe.scheduler.add_noise(clean_images, noise, timesteps) | |
| # 预测噪声残差 | |
| noise_pred = image_pipe.unet(noisy_images, timesteps, return_dict=False)[0] | |
| # 用预测噪声残差和实际增加的噪声对比来计算损失函数 | |
| loss = F.mse_loss( | |
| noise_pred, noise | |
| ) # NB - trying to predict noise (eps) not (noisy_ims-clean_ims) or just (clean_ims) | |
| # 保存 loss,用于可视化分析 | |
| losses.append(loss.item()) | |
| # 根据损失函数反向传播,用优化器更新模型参数 | |
| loss.backward(loss) | |
| # 梯度累加: | |
| if (step + 1) % grad_accumulation_steps == 0: | |
| optimizer.step() | |
| optimizer.zero_grad() | |
| print( | |
| f"Epoch {epoch} average loss: {sum(losses[-len(train_dataloader):])/len(train_dataloader)}" | |
| ) | |
| # 绘制 loss 可视化图: | |
| plt.plot(losses) | |
| ``` | |
| 0%| | 0/250 [00:00<?, ?it/s] | |
| Epoch 0 average loss: 0.013324214214226231 | |
| 0%| | 0/250 [00:00<?, ?it/s] | |
| Epoch 1 average loss: 0.014018508377484978 | |
| [<matplotlib.lines.Line2D>] | |
|  | |
| > **考虑因素2:** 梯度累加。 | |
| > | |
| > 从上图可以看出,训练过程的 loss 曲线简直像噪声一样混乱!这是因为设置了 batch size 为 4,在每一次迭代从训练集中仅随机选取 4 张图片,而且加到这些图片上的噪声也都是随机采样的,因此每次迭代由不同的 4 张图片计算得到的 loss 波动就非常大。而这对训练过程不太友好,其中一种弥补措施是:使用非常小的学习率来限制每次反向传播中权重更新的幅度。但还有一个更好的方法--梯度累加,既能得到与大 batch size 训练相当的收益,又不会让我们的 GPU 内存爆掉。梯度累加是一种 “增大 batch size” 的等效技巧,可以点击查看 [梯度累加](https://kozodoi.me/python/deep%20learning/pytorch/tutorial/2021/02/19/gradient-accumulation.html#:~:text=Simply%20speaking%2C%20gradient%20accumulation%20means,might%20find%20this%20tutorial%20useful.) 的详细信息。 | |
| 具体来说,梯度累加的实现原理为:如果我们先调用多次 `loss.backward()` 函数,再调用 `optimizer.step()` 和 `optimizer.zero_grad()`,PyTorch 就会把这几次计算得到的梯度累加(加和)起来,这样多个 batch 的数据计算的 loss 就会被高效地融合,从而只产出一个单独的(更好的)梯度估计用于参数更新。 | |
| 通过梯度累加,模型训练过程会减少参数更新的总次数,这样实际上就跟使用更大的 batch size 时的训练效果一致,如上图中的 loss 曲线,梯度累加会起到平滑曲线的作用。这是一种时间换空间的思想,在 GPU 内存受限时非常有帮助。目前许多深度学习框架都实现了梯度累加(比如 🤗 的 [Accelerate](https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation) 库就可以非常方便地调用),不过在本书,我们会学习如何从零实现梯度累加技巧。如上述代码(在注释 `# 梯度累加` 之后)可见,其实代码量非常短(仅两三行)。 | |
| ```python | |
| # 练习:试试你能不能在第三章的训练循环中实现梯度累加。 | |
| # 思考应该怎么基于梯度累加的次数来调整学习率? | |
| # 思考为什么需要调整学习率? | |
| ``` | |
| > **考虑因素3:** 监控训练过程。 | |
| > | |
| > 使用了梯度累加技巧后,训练时间会变得很慢,而且每遍历完一轮数据集才打印出一行更新信息,这样的反馈不足以让我们知道训练过程进行的怎么样了,所以我们需要进一步监控训练过程。为此,在训练过程中,我们可以: | |
| > | |
| > * 时不时地生成一些图片,来检查一下模型性能 | |
| > * 记录一些信息到日志里,如 loss 值、生成图片等,然后可以使用诸如 Weights and Biases 或 tensorboard 之类的工具来可视化 | |
| 然后就是实现上述的训练过程监控功能。我已经预创建好了一个可以快速上手的脚本程序,可以点击 [此处](https://github.com/huggingface/diffusion-models-class/blob/main/unit2/finetune_model.py) 查看和下载 `finetune_model.py` 。同时也已经上传了单次训练的日志信息,可以点击 [此处](https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341) 查看使用示例,也可以运行以下指令查看: | |
| ```python | |
| %wandb johnowhitaker/dm_finetune/2upaa341 # 需要一个 W&B 账户,如果不需要登录可跳过此代码 | |
| ``` | |
| <iframe src="https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341?jupyter=true" style="border:none;width:100%;height:420px;"></iframe> | |
| 随着训练过程的进展,观察生成的样本图片是如何一步步演变的也挺有意思。即使从 loss 曲线的走势看不出模型在进步,不过从训练期间不断生成的图片中,我们仍然能看到从原始图片分布(卧室数据集)到新的数据集(wikiart 数据集)逐渐演变的过程。在本章的最后还有一些被注释掉的用于微调的代码,可以使用该脚本程序替代上面的代码块。 | |
| ```python | |
| # 练习:试试你能不能修改第四章的官方示例训练脚本程序 | |
| # 实现使用现有模型训练,而不是从头开始 | |
| # 对比一下上面链接指向的脚本程序,哪些额外功能是脚本程序里没有的? | |
| ``` | |
| 接下来我们待模型训练完成之后,就可以用最终微调的模型来生成一些图片了,运行下列代码就能看到模型效果了。可以看到,生成的脸部图片已经变得非常奇怪了! | |
| ```python | |
| # 生成图片并可视化: | |
| x = torch.randn(8, 3, 256, 256).to(device) # Batch of 8 | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| model_input = scheduler.scale_model_input(x, t) | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| grid = torchvision.utils.make_grid(x, nrow=4) | |
| plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5); | |
| ``` | |
| 0it [00:00, ?it/s] | |
|  | |
| > **考虑因素4:** 超参数实验。 | |
| > | |
| > 微调模型的生成效果是难以预知的。如果你想要得到一个满意的微调模型,很可能需要尝试调节一些预设的超参数值,进行多组训练实验。例如设置更长的训练时间会更可能生成完美的蝴蝶图片。不妨亲自尝试一下调节训练时间、学习率等超参数,看看这会怎样影响模型的最终输出。要是你对图片艺术风格很感兴趣,你会发现不同超参数实验的训练中间过程中,模型生成图片的演变过程也极其有趣! | |
| ### 5.5.2 使用最小化样例脚本微调模型 | |
| #### 使用 5.5.1 中的样例脚本程序在 WikiArt 数据集上去微调模型 | |
| 上文中我们介绍了模型微调过程中各部分的代码块。如果你想仅使用一个脚本程序来运行完整的微调任务,可以去掉下列代码的注释符,来下载我已经创建完成的脚本程序,并在终端运行。该脚本程序实现的是在 WikiArt 数据集上微调模型,你也可以根据个人喜好来更改一些训练条件。不过由于这需要消耗不少的时间和 GPU 内存,我还是建议你在完整学习本章节内容之后再做尝试。 | |
| ```python | |
| ## 下载微调用的脚本: | |
| # !wget https://github.com/huggingface/diffusion-models-class/raw/main/unit2/finetune_model.py | |
| ``` | |
| ```python | |
| ## 运行脚本,在 Vintage Face 数据集上训练模型 | |
| ## (最好在终端中运行): | |
| # !python finetune_model.py --image_size 128 --batch_size 8 --num_epochs 16\ | |
| # --grad_accumulation_steps 2 --start_model "google/ddpm-celebahq-256"\ | |
| # --dataset_name "Norod78/Vintage-Faces-FFHQAligned" --wandb_project 'dm-finetune'\ | |
| # --log_samples_every 100 --save_model_every 1000 --model_save_name 'vintageface' | |
| ``` | |
| ### 5.5.3 保存和上传微调过的管线 | |
| 现在我们已经微调好了扩散模型中 U-Net 的权重,接下来就可以将它保存到本地文件夹中了,相关代码如下: | |
| ```python | |
| image_pipe.save_pretrained("my-finetuned-model") | |
| ``` | |
| 跟第三章一样,运行代码后会同时保存配置文件、模型、调度器。 | |
| ```python | |
| !ls {"my-finetuned-model"} | |
| ``` | |
| model_index.json scheduler unet | |
| 接下来你可以参照第四章的 [Introduction to Diffusers](https://github.com/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) 部分,把模型上传到 Hub 上以备后续使用。代码如下: | |
| ```python | |
| # @title: 将本地保存的管线上传至 Hub | |
| # 代码: 将本地保存的管线上传至 Hub | |
| from huggingface_hub import HfApi, ModelCard, create_repo, get_full_repo_name | |
| # 配置 Hub 仓库,上传文件 | |
| model_name = "ddpm-celebahq-finetuned-butterflies-2epochs" # @param 给传到 Hub 上的文件命名 | |
| local_folder_name = "my-finetuned-model" # @param 脚本程序生成的名字,你也可以通过 image_pipe.save_pretrained('save_name') 指定 | |
| description = "Describe your model here" # @param | |
| hub_model_id = get_full_repo_name(model_name) | |
| create_repo(hub_model_id) | |
| api = HfApi() | |
| api.upload_folder( | |
| folder_path=f"{local_folder_name}/scheduler", path_in_repo="", repo_id=hub_model_id | |
| ) | |
| api.upload_folder( | |
| folder_path=f"{local_folder_name}/unet", path_in_repo="", repo_id=hub_model_id | |
| ) | |
| api.upload_file( | |
| path_or_fileobj=f"{local_folder_name}/model_index.json", | |
| path_in_repo="model_index.json", | |
| repo_id=hub_model_id, | |
| ) | |
| # 添加一个模型名片 (可选,建议添加) | |
| content = f""" | |
| --- | |
| license: mit | |
| tags: | |
| - pytorch | |
| - diffusers | |
| - unconditional-image-generation | |
| - diffusion-models-class | |
| --- | |
| # Example Fine-Tuned Model for Unit 2 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class) | |
| {description} | |
| ## Usage | |
| ```python | |
| from diffusers import DDPMPipeline | |
| pipeline = DDPMPipeline.from_pretrained('{hub_model_id}') | |
| image = pipeline().images[0] | |
| image | |
| ``` | |
| """ | |
| card = ModelCard(content) | |
| card.push_to_hub(hub_model_id) | |
| ``` | |
| 'https://huggingface.co/lewtun/ddpm-celebahq-finetuned-butterflies-2epochs/blob/main/README.md' | |
| 至此,你已经完成了你的第一个微调扩散模型!祝贺! | |
| ### 5.5.4 加载微调模型生成图片 | |
| 在这一小节中,我们将介绍如何加载现有的微调模型来生成图片。我将使用一个在 [LSUM bedrooms 数据集](https://huggingface.co/google/ddpm-bedroom-256) 上训练且在 WikiArt 数据集上微调了大约一轮的 [模型](https://huggingface.co/johnowhitaker/sd-class-wikiart-from-bedrooms)。你可以根据个人偏好来选择加载其他的微调模型,例如使用上文中我们微调过的人脸或蝴蝶模型,也可以直接从 Hub 上加载一个现有的微调模型。 | |
| ```python | |
| # 加载预训练管线 | |
| pipeline_name = "johnowhitaker/sd-class-wikiart-from-bedrooms" | |
| image_pipe = DDPMPipeline.from_pretrained(pipeline_name).to(device) | |
| # 使用 DDIM 调度器,设置采样步长不小于 40,采样图片 | |
| scheduler = DDIMScheduler.from_pretrained(pipeline_name) | |
| scheduler.set_timesteps(num_inference_steps=40) | |
| # 随机初始化噪声 (每批次包含 8 张图片) | |
| x = torch.randn(8, 3, 256, 256).to(device) | |
| # 采样循环 | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| model_input = scheduler.scale_model_input(x, t) | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| # 可视化结果 | |
| grid = torchvision.utils.make_grid(x, nrow=4) | |
| plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5); | |
| ``` | |
| Downloading: 0%| | 0.00/180 [00:00<?, ?B/s] | |
| Fetching 4 files: 0%| | 0/4 [00:00<?, ?it/s] | |
| Downloading: 0%| | 0.00/938 [00:00<?, ?B/s] | |
| Downloading: 0%| | 0.00/455M [00:00<?, ?B/s] | |
| Downloading: 0%| | 0.00/288 [00:00<?, ?B/s] | |
| 0it [00:00, ?it/s] | |
|  | |
| > **考虑因素5:** 如何判断微调模型效果的好坏? | |
| > | |
| > 一般而言,很难判断微调的效果到底怎么样,因为很难使用 loss 曲线来对应地描述效果,而且测试集也非常不固定,“效果好” 这种表述在不同场景的实际表现也不一样。其中一个例子:如果你想在一个很小的数据集上微调一个文生图 stable diffusion 模型,那么你会希望微调模型尽最大程度 **保留** 原始模型学习到的东西。也就是说,这时候你输入任意的文本提示语,如果它没有在小数据集中覆盖到,你会希望微调模型以原有模型学习到的东西来生成这些提示语对应的内容,同时又能 **适配** 小数据集的风格。这可能意味着你需要使用很小的学习率以及指数平均技巧,具体实现可以参考这篇 [微调一个宝可梦版 stable diffusion 模型的博客](https://lambdalabs.com/blog/how-to-fine-tune-stable-diffusion-how-we-made-the-text-to-pokemon-model-at-lambda)。相反的另一个例子:如果你想在一个新数据上完全重新训练一个模型(如上文中的从卧室数据集到 wikiart 数据集),那这时候就需要更大的学习率和更长的训练时间了。即便从 [损失值曲线](https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341) 中看不出模型在进步,但从生成样本可视化图中也能很清楚地看出一个从原始图片到更有艺术范图片的演变过程,只是中间过程看着不太协调罢了。 | |
| 具体细节会在下面的小节中讲解,包括怎样对这类模型施加额外的引导,从而更好地控制模型输出。 | |
| ## 5.6 扩散模型-引导 | |
| 如果我们想对生成的图片施加点控制,需要怎么做?例如想让生成的图片整体色调都偏向于某种颜色。这就要用到本节要介绍的 **引导(guidance)**,这是一项可以在生成图片过程中施加额外控制信息的技术。 | |
| ### 5.6.1 实战:引导 | |
| 第一步,先创建一个控制函数,它需要定义一个优化目标(也就是损失函数)。如果以刚提到的颜色为例,那这个控制函数的功能就是:将生成图片的像素值和目标颜色(下面代码使用浅蓝绿色)的像素值逐一对比,然后返回整张图片的平均像素值误差: | |
| ```python | |
| def color_loss(images, target_color=(0.1, 0.9, 0.5)): | |
| """输入 images 为 (R, G, B) 格式,返回与目标颜色的平均像素误差 | |
| 默认目标颜色为浅蓝绿色,像素值为 (0.1, 0.9, 0.5)""" | |
| target = ( | |
| torch.tensor(target_color).to(images.device) * 2 - 1 | |
| ) # 将图片像素值映射到 (-1, 1) | |
| target = target[ | |
| None, :, None, None | |
| ] # 匹配输入 images 的 shape:(b, c, h, w) | |
| error = torch.abs( | |
| images - target | |
| ).mean() # images 和目标颜色的平均像素误差绝对值 | |
| return error | |
| ``` | |
| 接下来,我们要修改采样循环。在每一次迭代,我们需要: | |
| - 创建一个新的噪声 $x$ 变量,设置其 `requires_grad = True` | |
| - 计算对应的去噪图片 $x0$ | |
| - 将 $x0$ 输入给损失函数 | |
| - 计算损失函数对 $x$ 的 **梯度值** | |
| - 先用得到的梯度值更新 $x$,再调用 `scheuler.step()`,这样变量 $x$ 就会依据引导函数计算的梯度方向,但是以更小的幅度更新。 | |
| 下面代码展示了两种实现方法,你可以探索一下哪一种更好。第一种,先从 UNet 得到预测的噪声残差,再给 $x$ 设置 requires_grad,这样对内存来讲更高效一点(因为不需要链式地在整个扩散模型中追踪梯度),但得到的梯度精度会稍低一些。第二种,先给 $x$ 设置 requires_grad,然后再输入 UNet 计算预测的 $x0$。 | |
| ```python | |
| # 实现 1: 先计算 loss 梯度,再设置 x.requires_grad | |
| # 引导 scale 值决定了效果强度 | |
| guidance_loss_scale = 40 # 尝试改为 5, 100 试试看 | |
| x = torch.randn(8, 3, 256, 256).to(device) | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| # 准备模型输入 | |
| model_input = scheduler.scale_model_input(x, t) | |
| # 预测噪声残差 | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| # 设置 x.requires_grad 为 True | |
| x = x.detach().requires_grad_() | |
| # 计算预测 x0 | |
| x0 = scheduler.step(noise_pred, t, x).pred_original_sample | |
| # 计算 loss | |
| loss = color_loss(x0) * guidance_loss_scale | |
| if i % 10 == 0: | |
| print(i, "loss:", loss.item()) | |
| # 计算梯度 | |
| cond_grad = -torch.autograd.grad(loss, x)[0] | |
| # 根据梯度更新 x | |
| x = x.detach() + cond_grad | |
| # 调用 scheduler.step() | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| # 可视化输出 | |
| grid = torchvision.utils.make_grid(x, nrow=4) | |
| im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5 | |
| Image.fromarray(np.array(im * 255).astype(np.uint8)) | |
| ``` | |
| 0it [00:00, ?it/s] | |
| 0 loss: 27.279136657714844 | |
| 10 loss: 11.286816596984863 | |
| 20 loss: 10.683112144470215 | |
| 30 loss: 10.942476272583008 | |
|  | |
| 第二种实现方法资源占用较多,即使把 batch size 从 8 降低到 4,仍然需要几乎第一种两倍的 GPU 内存。试试看你能不能找出两种实现方式的异同,想想为什么这里计算的梯度更精确? | |
| ```python | |
| # 实现 2: 先设置 x.requires_grad,再计算 loss 梯度 | |
| guidance_loss_scale = 40 | |
| x = torch.randn(4, 3, 256, 256).to(device) | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| # 设置 requires_grad,输入给模型前向计算 | |
| x = x.detach().requires_grad_() | |
| model_input = scheduler.scale_model_input(x, t) | |
| # 预测噪声残差 (含梯度) | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| # 计算预测 x0: | |
| x0 = scheduler.step(noise_pred, t, x).pred_original_sample | |
| # 计算 loss | |
| loss = color_loss(x0) * guidance_loss_scale | |
| if i % 10 == 0: | |
| print(i, "loss:", loss.item()) | |
| # 计算梯度 | |
| cond_grad = -torch.autograd.grad(loss, x)[0] | |
| # 根据梯度更新 x | |
| x = x.detach() + cond_grad | |
| # 调用 scheduler.step() | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| grid = torchvision.utils.make_grid(x, nrow=4) | |
| im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5 | |
| Image.fromarray(np.array(im * 255).astype(np.uint8)) | |
| ``` | |
| 0it [00:00, ?it/s] | |
| 0 loss: 30.750328063964844 | |
| 10 loss: 18.550724029541016 | |
| 20 loss: 17.515094757080078 | |
| 30 loss: 17.55681037902832 | |
|  | |
| 在第二种实现方法中,内存的需求更高了,但颜色迁移的效果却减弱了,这里你可能觉得这种方法不如第一种方法。但是这里生成的图片更接近于原模型的训练数据。通常你可以通过增大 `guidance_loss_scale` 来加强颜色迁移的效果。你可以尝试一下两种方案,视最终效果来决定选择使用哪种方案。 | |
| ```python | |
| # 练习:选一个你最喜欢的颜色,并将它在 RGB 空间中表示出来 | |
| # 修改上面代码的 `color_loss()`,将颜色改成你选的颜色,训练模型并采样检查生成图片,看看是否和你期望的一致。 | |
| ``` | |
| ### 5.6.2 CLIP 引导 | |
| 给模型增加颜色引导仅只是控制引导的很小的例子。现在我们想要仅通过简单的文字描述来控制我们想生成图片的引导模式,该怎么做呢? | |
| 我们需要一项连接文字和图片的技术。[CLIP](https://openai.com/blog/clip/) 是一个由 OpenAI 开发的模型,它可以度量图片和文字的相似性。这个功能非常强大,因为它能够计算图片和文字相似性的具体量化值。另外由于这个过程是可微分的,我们就可以将它作为损失函数来引导我们的扩散模型! | |
| 我不会解释太多其中细节。整体方法如下: | |
| - 对文字提示语做词汇嵌入(embedding),得到一个 512 维的 CLIP embedding | |
| - 对于扩散模型的生成过程的每一步: | |
| - 对预测的去噪图片可以进行多种变体(如重参数化,不同的变体会对应不同的目标监督信号,有的变体会带来更清晰的计算损失函数的方式)。 | |
| - 对每一个预测出的去噪图片,用 CLIP 给图片做嵌入(embedding),并将这个嵌入和文字的嵌入做对比(用一种叫 Great Circle Distance Squared 的方法计算相似度) | |
| - 计算 loss 对于 x 的梯度并更新 x,再调用 scheduler.step() | |
| 如果你想了解关于 CLIP 的详细讲解,可以点击 [这个课程](https://johnowhitaker.github.io/tglcourse/clip.html) 或 [关于 OpenCLIP 的报告](https://wandb.ai/johnowhitaker/openclip-benchmarking/reports/Exploring-OpenCLIP--VmlldzoyOTIzNzIz)。本书使用的 CLIP 就是从 OpenCLIP 载入的,运行下列代码就可以载入一个 CLIP 模型: | |
| ```python | |
| # @markdown 载入 CLIP 模型,定义损失函数 | |
| import open_clip | |
| clip_model, _, preprocess = open_clip.create_model_and_transforms( | |
| "ViT-B-32", pretrained="openai" | |
| ) | |
| clip_model.to(device) | |
| # 设计一个 transforms,实现 resize、augment、normalize 来匹配 CLIP 的训练数据 | |
| tfms = torchvision.transforms.Compose( | |
| [ | |
| torchvision.transforms.RandomResizedCrop(224), # 随机裁剪 | |
| torchvision.transforms.RandomAffine( | |
| 5 | |
| ), # 随机倾斜 | |
| torchvision.transforms.RandomHorizontalFlip(), # 可额外增加数据增强 | |
| torchvision.transforms.Normalize( | |
| mean=(0.48145466, 0.4578275, 0.40821073), | |
| std=(0.26862954, 0.26130258, 0.27577711), | |
| ), | |
| ] | |
| ) | |
| # 定义损失函数:接收两张图片作为输入,计算 CLIP embedding,返回两个 embedding 的 Great Circle 距离 | |
| def clip_loss(image, text_features): | |
| image_features = clip_model.encode_image( | |
| tfms(image) | |
| ) # 注意使用上文的 transforms | |
| input_normed = torch.nn.functional.normalize(image_features.unsqueeze(1), dim=2) | |
| embed_normed = torch.nn.functional.normalize(text_features.unsqueeze(0), dim=2) | |
| dists = ( | |
| input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2) | |
| ) # 计算 Great Circle 距离的平方 | |
| return dists.mean() | |
| ``` | |
| 100%|████████████████████████████████████████| 354M/354M [00:02<00:00, 120MiB/s] | |
| 完成了定义损失函数之后,接下里的引导采样循环代码就和前面类似了,仅仅是把 `color_loss()` 换成了上述基于 CLIP 的损失函数: | |
| ```python | |
| # @markdown 使用 CLIP 引导模型 | |
| prompt = "Red Rose (still life), red flower painting" # @param | |
| # 尝试修改参数值 | |
| guidance_scale = 8 # @param | |
| n_cuts = 4 # @param | |
| # 增大采样步可以得到更好的性能,但也会花费更多训练时间 | |
| scheduler.set_timesteps(50) | |
| # 使用 CLIP 对文本做 embedding,作为目标监督信号 | |
| text = open_clip.tokenize([prompt]).to(device) | |
| with torch.no_grad(), torch.cuda.amp.autocast(): | |
| text_features = clip_model.encode_text(text) | |
| x = torch.randn(4, 3, 256, 256).to( | |
| device | |
| ) # 会占用较高的内存,如果你的内存不够可以减小 batch size | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| model_input = scheduler.scale_model_input(x, t) | |
| # 预测噪声残差 | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| cond_grad = 0 | |
| for cut in range(n_cuts): | |
| # 设置 x 的 requires_grad | |
| x = x.detach().requires_grad_() | |
| # 计算预测 x0: | |
| x0 = scheduler.step(noise_pred, t, x).pred_original_sample | |
| # 计算 loss | |
| loss = clip_loss(x0, text_features) * guidance_scale | |
| # 计算梯度 (使用平均值,这里做了正则化) | |
| cond_grad -= torch.autograd.grad(loss, x)[0] / n_cuts | |
| if i % 25 == 0: | |
| print("Step:", i, ", Guidance loss:", loss.item()) | |
| # 根据梯度更新 x | |
| alpha_bar = scheduler.alphas_cumprod[i] | |
| x = ( | |
| x.detach() + cond_grad * alpha_bar.sqrt() | |
| ) # 注意前面的正则化参数 | |
| # 调用 scheduler.step() | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| grid = torchvision.utils.make_grid(x.detach(), nrow=4) | |
| im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5 | |
| Image.fromarray(np.array(im * 255).astype(np.uint8)) | |
| ``` | |
| 0it [00:00, ?it/s] | |
| Step: 0 , Guidance loss: 7.437869548797607 | |
| Step: 25 , Guidance loss: 7.174620628356934 | |
|  | |
| 看起来有点像玫瑰!显然模型还不够完美,你可以尝试调整一些参数,多跑几次实验,就能生成一些更令人满意的图片。 | |
| 如果仔细看上面的代码,你会发现我使用了 `alpha_bar.sqrt()` 作为缩放因子来控制梯度。虽然理论上有所谓正确的缩放梯度的方法,但实际上仍然需要实验验证可行性。对于有些引导来说,你可能希望大部分的引导作用都集中在刚开始的几步里,对于另一些(比如一些关注点在纹理方面的风格损失函数)来讲,你可能希望它仅在生成过程的结束部分加入进来。对此,下面展示一些可能的方案: | |
| ```python | |
| # @markdown 可视化缩放梯度方案: | |
| plt.plot([1 for a in scheduler.alphas_cumprod], label="no scaling") | |
| plt.plot([a for a in scheduler.alphas_cumprod], label="alpha_bar") | |
| plt.plot([a.sqrt() for a in scheduler.alphas_cumprod], label="alpha_bar.sqrt()") | |
| plt.plot( | |
| [(1 - a).sqrt() for a in scheduler.alphas_cumprod], label="(1-alpha_bar).sqrt()" | |
| ) | |
| plt.legend() | |
| plt.title("Possible guidance scaling schedules"); | |
| ``` | |
|  | |
| 你可以尝试跑几组实验,例如调整引导的 scale 值(`guidance_scale`),以及任何你能想到的技巧(比如流行的指定范围的梯度截断方法),看看能把生成效果做到多好。你也可以换成其它模型试试,比如本章开头使用的人脸模型。你能以可控的方式来让模型生成男性人脸图片吗?你还可以把 CLIP 引导和前面提到的颜色损失函数结合起来训练,等等。 | |
| 如果你看过一些 [CLIP 引导的扩散模型代码实战](https://huggingface.co/spaces/EleutherAI/clip-guided-diffusion/blob/main/app.py),你会发现许多库使用更复杂的引导方法来获得更好的性能:更好的随机图像裁剪选取规则,更多损失函数的变体等。在文本条件扩散模型出现之前,这曾经是最好的文本到图像转换系统!本书实现的 “玩具级” 版本有非常大的提升空间,但不管怎样,它仍然抓住了核心要点:借助于引导和 CLIP 惊人的性能,我们可以给非条件扩散模型加上文本条件的控制 🎨 | |
| ## 5.7 分享你的自定义采样训练 | |
| #### 自定义采样循环 Gradio 样例 | |
| 也许你现在已经想出了一个引导生成过程的有趣的损失函数,如果你想把你的微调模型和自定义的采样策略分享给全世界...... | |
| ### 5.7.1 环境准备 | |
| 点击这里了解 [Gradio](https://gradio.app/)。Gradio 是一个免费的开源工具,可以让用户很方便地通过一个简单的网页界面来创建和分享交互式的机器学习模型应用程序。使用 Gradio,用户能够为自己的机器学习模型应用程序自定义接口,然后通过一个唯一的 URL 分享给他人。Gradio 现已集成到 🤗 Spaces,🤗 用户也可以很方便地创建和分享样例。 | |
| 我们将把我们需要的核心逻辑集成到一个函数中,这个函数接收一些输入然后输出一张图片,这可以封装成一个简单的接口,让用户能自己定义一些参数(这些参数将输入给图片生成的主函数)。有很多可用的 [组件](https://gradio.app/docs/#components) 来完成封装,本例中我们加入了一个滑块(slider)组件来滑动控制引导参数值(guidance scale),以及一个颜色选择器来定义目标颜色。 | |
| ```python | |
| !pip install -q gradio # 安装 gradio 库 | |
| ``` | |
| ```python | |
| import gradio as gr | |
| from PIL import Image, ImageColor | |
| # 图片生成主函数 | |
| def generate(color, guidance_loss_scale): | |
| target_color = ImageColor.getcolor(color, "RGB") # RGB 格式的目标图片 | |
| target_color = [a / 255 for a in target_color] # 归一化至 (0, 1) | |
| x = torch.randn(1, 3, 256, 256).to(device) | |
| for i, t in tqdm(enumerate(scheduler.timesteps)): | |
| model_input = scheduler.scale_model_input(x, t) | |
| with torch.no_grad(): | |
| noise_pred = image_pipe.unet(model_input, t)["sample"] | |
| x = x.detach().requires_grad_() | |
| x0 = scheduler.step(noise_pred, t, x).pred_original_sample | |
| loss = color_loss(x0, target_color) * guidance_loss_scale | |
| cond_grad = -torch.autograd.grad(loss, x)[0] | |
| x = x.detach() + cond_grad | |
| x = scheduler.step(noise_pred, t, x).prev_sample | |
| grid = torchvision.utils.make_grid(x, nrow=4) | |
| im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5 | |
| im = Image.fromarray(np.array(im * 255).astype(np.uint8)) | |
| im.save("test.jpeg") | |
| return im | |
| # 查看 gradio 文档来选择输入和输出的可用参数类型 | |
| inputs = [ | |
| gr.ColorPicker(label="color", value="55FFAA"), # 这里可以添加任何输入 | |
| gr.Slider(label="guidance_scale", minimum=0, maximum=30, value=3), | |
| ] | |
| outputs = gr.Image(label="result") | |
| # 定义接口 | |
| demo = gr.Interface( | |
| fn=generate, | |
| inputs=inputs, | |
| outputs=outputs, | |
| examples=[ | |
| ["#BB2266", 3], | |
| ["#44CCAA", 5], # 这里可以添加一些示例 | |
| ], | |
| ) | |
| demo.launch(debug=True) # 设置 debug=True 以查看程序输出和报错 | |
| ``` | |
| 当然你也可以制作更复杂的接口,设计你喜欢的风格,以及提供一些默认的输入。这里我们只做基本功能的演示。 | |
| 在 🤗 Spaces 上的演示 demo 默认使用 CPU 运行,所以在你把你的应用程序移植到 🤗 Spaces 之前,最好先在 Colab 上把接口雏形(如上所示)制作完成。然后你需要在 🤗 上创建一个 space,配置好 `requirements.txt`(列出运行程序所需的库),然后把所有运行代码都放在一个名为 `app.py` 的文件里,这个文件就是用来定义相关函数和接口的。 | |
| ![Screenshot from 2022-12-11 10-28-26.png]() | |
| 当然还有一种简单的方式,你也可以直接复制一个 space。可以点击 [这里](https://huggingface.co/spaces/johnowhitaker/color-guided-wikiart-diffusion) 查看我的 demo(上面的示例),然后点击 “Duplicate this Space” 将我的代码作为模板,用于你后续修改代码来添加你自己的模型和引导函数。 | |
| 在设置选项中,你也可以配置你的 space 的运行环境,让它在更高性能的硬件上运行(会按小时收费)。如果你做出了一些很惊艳的东西并且想在更高性能的硬件上分享和运行,但是囊中羞涩?你可以在 Discord 上告诉我们,看我们能不能提供点帮助。 | |
| ## 5.8 本章小结 | |
| 本章节介绍了非常多的内容。让我们回顾一下核心要点: | |
| - 载入一个现有模型并用不同的调度器(scheduler)去采样其实很简单 | |
| - 微调(fine-tuning)看起来很像从头训练一个模型,唯一不同的是我们用已有的模型做初始化,期望能快点得到更好的效果 | |
| - 要在大尺寸图片上微调大模型,我们可以用诸如梯度累加(gradient accumulation)的技巧来应对训练硬件条件对 batch size 的限制 | |
| - 记录采样图片的日志信息对微调很重要,相反,loss 曲线显示的信息可能不太有用 | |
| - 引导(guidance)可以基于引导损失函数,来实现对非条件扩散模型在生成图片时施加控制。具体做法是:每一次迭代,计算 loss 对噪声 x 的梯度,先根据梯度信息更新 x,再进入下一次迭代 | |
| - 用 CLIP 引导的模型可以用文字描述来控制非条件扩散模型 | |
| 如果你想在实践中运用这些知识,你还可以做这些: | |
| - 微调你自己的模型并把它上传到 Hub。这包括:首先载入一个现有模型(例如 [人脸](https://huggingface.co/google/ddpm-celebahq-256)、[家居](https://huggingface.co/fusing/ddpm-lsun-bedroom)、[猫咪](https://huggingface.co/fusing/ddpm-lsun-cat) 或 [wikiart](https://huggingface.co/johnowhitaker/sd-class-wikiart-from-bedrooms) 数据集上训练的模型,以及一个新的数据集(例如 [动物脸部](https://huggingface.co/datasets/huggan/AFHQv2) 数据集,或者其他你自己的数据集),然后运行上文的代码或样例脚本程序。 | |
| - 用你的微调过的模型尝试一下加入引导,你可以用上文中举例的引导函数(颜色损失或 CLIP),也可以自己创造一个。 | |
| - 使用 Gradio 分享你的 demo,你可以将 [space 样例](https://huggingface.co/spaces/johnowhitaker/color-guided-wikiart-diffusion) 中的模型替换为你自己的模型,也可以创建你专属的有功能更齐全的 space。 | |
| 我们期待在 Discord、Twitter 或其它地方看到你的作品!🤗 | |
| ```python | |
| ``` | |
| ### 5.7.2 创建一个以类别为条件的 UNet | |
| 在这一小节中,我们将介绍一种给扩散模型加入条件信息的方法。具体来说,我们将接着第一单元中 [从头训练扩散模型](../unit1/02_diffusion_models_from_scratch_CN.ipynb) 的示例,在 MNIST 上训练一个以类别为条件的基于 UNet 的扩散模型,这样我们在推理的时候就能具体指定想要生成那个数字图片。 | |
| 就像本章中介绍中说的那样,给扩散模型添加额外条件信息的方法有很多种,而这只是其中一种,用它做示例纯粹是因为它比较简单。就像第一单元中 “从头训练扩散模型” 部分一样,本节内容只是为了解释说明的目的,你也可以选择跳过。 | |
| ## 配置和数据准备 | |
| ```python | |
| !pip install -q diffusers | |
| ``` | |
| [K |████████████████████████████████| 503 kB 7.2 MB/s | |
| [K |████████████████████████████████| 182 kB 51.3 MB/s | |
| [?25h | |
| ```python | |
| import torch | |
| import torchvision | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from torch.utils.data import DataLoader | |
| from diffusers import DDPMScheduler, UNet2DModel | |
| from matplotlib import pyplot as plt | |
| from tqdm.auto import tqdm | |
| device = 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu' | |
| print(f'Using device: {device}') | |
| ``` | |
| Using device: cuda | |
| ```python | |
| # 加载数据集 | |
| dataset = torchvision.datasets.MNIST(root="mnist/", train=True, download=True, transform=torchvision.transforms.ToTensor()) | |
| # 输入 dataloader (这里 batch_size 设为8,你也可以视情况修改) | |
| train_dataloader = DataLoader(dataset, batch_size=8, shuffle=True) | |
| # 抽样可视化图片 | |
| x, y = next(iter(train_dataloader)) | |
| print('Input shape:', x.shape) | |
| print('Labels:', y) | |
| plt.imshow(torchvision.utils.make_grid(x)[0], cmap='Greys'); | |
| ``` | |
| Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz | |
| Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to mnist/MNIST/raw/train-images-idx3-ubyte.gz | |
| 0%| | 0/9912422 [00:00<?, ?it/s] | |
| Extracting mnist/MNIST/raw/train-images-idx3-ubyte.gz to mnist/MNIST/raw | |
| Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz | |
| Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to mnist/MNIST/raw/train-labels-idx1-ubyte.gz | |
| 0%| | 0/28881 [00:00<?, ?it/s] | |
| Extracting mnist/MNIST/raw/train-labels-idx1-ubyte.gz to mnist/MNIST/raw | |
| Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz | |
| Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to mnist/MNIST/raw/t10k-images-idx3-ubyte.gz | |
| 0%| | 0/1648877 [00:00<?, ?it/s] | |
| Extracting mnist/MNIST/raw/t10k-images-idx3-ubyte.gz to mnist/MNIST/raw | |
| Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz | |
| Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to mnist/MNIST/raw/t10k-labels-idx1-ubyte.gz | |
| 0%| | 0/4542 [00:00<?, ?it/s] | |
| Extracting mnist/MNIST/raw/t10k-labels-idx1-ubyte.gz to mnist/MNIST/raw | |
| Input shape: torch.Size([8, 1, 28, 28]) | |
| Labels: tensor([8, 1, 5, 9, 7, 6, 2, 2]) | |
|  | |
| #### 以类别为条件的 UNet 创建方法 | |
| 我们输入类别条件的方法流程是: | |
| - 创建一个标准的 `UNet2DModel`,增加额外的输入通道 | |
| - 通过嵌入(embedding)层把类别标签映射到一个 `(class_emb_size)` 形状的向量 | |
| - 把嵌入向量填充到额外的输入通道,即和原有的输入拼接起来,代码为: `net_input = torch.cat((x, class_cond), 1)` | |
| - 将拼接的 `net_input` (共有 `class_emb_size+1` 个通道) 输入给 UNet 从而得到最终预测输出 | |
| 在本例中,我把 class_emb_size 设为 4,不过这个值完全可以修改为任意值,你可以尝试把它设为 1(来看看这有没有用),一直到 10(正好是类别总数),或者把 nn.Embedding 嵌入的向量直接换成简单的类别独热编码(one-hot encoding)。 | |
| 具体实现代码如下: | |
| ```python | |
| class ClassConditionedUnet(nn.Module): | |
| def __init__(self, num_classes=10, class_emb_size=4): | |
| super().__init__() | |
| # embedding 层会把类别标签映射为 class_emb_size 形状的向量 | |
| self.class_emb = nn.Embedding(num_classes, class_emb_size) | |
| # Self.model 是一个非条件 UNet,因此并不包含额外的通道,无法拼接条件信息(类别 embedding) | |
| self.model = UNet2DModel( | |
| sample_size=28, # 目标图片分辨率 | |
| in_channels=1 + class_emb_size, # 额外的通道数 | |
| out_channels=1, # 输出通道数 | |
| layers_per_block=2, # UNet Block 内的 ResNet 层数 | |
| block_out_channels=(32, 64, 64), | |
| down_block_types=( | |
| "DownBlock2D", # 常规 ResNet 下采样 block | |
| "AttnDownBlock2D", # 带有 2 维自注意力机制的 ResNet 下采样 block | |
| "AttnDownBlock2D", | |
| ), | |
| up_block_types=( | |
| "AttnUpBlock2D", | |
| "AttnUpBlock2D", # 带有 2 维自注意力机制的 ResNet 上采样 block | |
| "UpBlock2D", # 常规 ResNet 上采样 block | |
| ), | |
| ) | |
| # 前向计算函数接收额外的类别参数 | |
| def forward(self, x, t, class_labels): | |
| # x 的形状: | |
| bs, ch, w, h = x.shape | |
| # 映射类别条件信息与图片信息融合需要形状匹配 | |
| class_cond = self.class_emb(class_labels) # 映射类别条件信息到目标形状 | |
| class_cond = class_cond.view(bs, class_cond.shape[1], 1, 1).expand(bs, class_cond.shape[1], w, h) | |
| # x 形状为 (bs, 1, 28, 28), class_cond 现在的形状为 (bs, 4, 28, 28) | |
| # 沿着维度为 1(从 0 开始)轴拼接 x 和 class_cond | |
| net_input = torch.cat((x, class_cond), 1) # (bs, 5, 28, 28) | |
| # 将 net_input 和 时间步信息一同送入模型预测图片输出 | |
| return self.model(net_input, t).sample # (bs, 1, 28, 28) | |
| ``` | |
| 如果你对哪个形或状变换理解的不是很明白,可以在代码中加入 print 来打印相关形状,从而检查它们是否符合你的预期。这里我把一些中间变量的形状都以注释的形式展示了,希望能帮助你理解的透彻点。 | |
| ### 5.7.3 训练和采样 | |
| 跟本书前面预测模型输出使用的 `prediction = unet(x, t)` 不同,现在我们增加第 3 个参数,需要使用 `prediction = unet(x, t, y)`。在推理阶段,我们可以输入任何标签,如果一切正常,模型就会输出与之匹配的图片。这里的参数 `y` 就是 MNIST 中的数字标签,参数值的范围为 0 到 9。 | |
| 训练循环也跟 [第一单元的例子](../unit1/02_diffusion_models_from_scratch_CN.ipynb) 非常相似,这里模型预测的是噪声残差(而不是第一单元去噪图片),以此来匹配 DDPMScheduler 预设的目标形式,在训练阶段去噪和推理阶段的采样需要保持一致。实际训练过程需要一段时间(如何加速训练也是个有趣的课题),但这里我们只是讲解思路,你也可以跳过需要运行代码块的部分。 | |
| ```python | |
| # 创建一个 DDPMScheduler 实例 | |
| noise_scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule='squaredcos_cap_v2') | |
| ``` | |
| ```python | |
| #@markdown 训练循环 (10 Epochs): | |
| # 重定义 dataloader,设置 batch_size (可以比先前 demo 中大得多) | |
| train_dataloader = DataLoader(dataset, batch_size=128, shuffle=True) | |
| # 思考一下设置多少 epoch 比较好? | |
| n_epochs = 10 | |
| # 网络架构 | |
| net = ClassConditionedUnet().to(device) | |
| # 损失函数 | |
| loss_fn = nn.MSELoss() | |
| # 优化器 | |
| opt = torch.optim.Adam(net.parameters(), lr=1e-3) | |
| # 记录 loss 以便后续分析 loss 曲线 | |
| losses = [] | |
| # 训练循环 | |
| for epoch in range(n_epochs): | |
| for x, y in tqdm(train_dataloader): | |
| # 训练数据准备 | |
| x = x.to(device) * 2 - 1 # 转移数据至 GPU 并归一化 (-1, 1) | |
| y = y.to(device) | |
| noise = torch.randn_like(x) | |
| timesteps = torch.randint(0, 999, (x.shape[0],)).long().to(device) | |
| noisy_x = noise_scheduler.add_noise(x, noise, timesteps) | |
| # 获取模型预测输出 | |
| pred = net(noisy_x, timesteps, y) # 注意传入类别标签 y | |
| # 计算 loss | |
| loss = loss_fn(pred, noise) # 度量预测和噪声的相似程度 | |
| # 反向传播,更新参数 | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| # 记录 loss | |
| losses.append(loss.item()) | |
| # 每 100 个样本打印一次平均 loss,不时查看一下训练进展情况 | |
| avg_loss = sum(losses[-100:])/100 | |
| print(f'Finished epoch {epoch}. Average of the last 100 loss values: {avg_loss:05f}') | |
| # 可视化 loss 曲线 | |
| plt.plot(losses) | |
| ``` | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 0. Average of the last 100 loss values: 0.052451 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 1. Average of the last 100 loss values: 0.045999 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 2. Average of the last 100 loss values: 0.043344 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 3. Average of the last 100 loss values: 0.042347 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 4. Average of the last 100 loss values: 0.041174 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 5. Average of the last 100 loss values: 0.040736 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 6. Average of the last 100 loss values: 0.040386 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 7. Average of the last 100 loss values: 0.039372 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 8. Average of the last 100 loss values: 0.039056 | |
| 0%| | 0/469 [00:00<?, ?it/s] | |
| Finished epoch 9. Average of the last 100 loss values: 0.039024 | |
| [<matplotlib.lines.Line2D>] | |
|  | |
| 训练完成后,我们就可以输入不同的标签条件,来生成图片看看效果了: | |
| ```python | |
| #@markdown 生成不同数字类别图片: | |
| # 随机初始化噪声,以及类别标签 | |
| x = torch.randn(80, 1, 28, 28).to(device) | |
| y = torch.tensor([[i]*8 for i in range(10)]).flatten().to(device) | |
| # 采样循环 | |
| for i, t in tqdm(enumerate(noise_scheduler.timesteps)): | |
| # 计算模型输出 | |
| with torch.no_grad(): | |
| residual = net(x, t, y) # 再次提醒传入标签 y | |
| # 迭代去噪图片 | |
| x = noise_scheduler.step(residual, t, x).prev_sample | |
| # 可视化最终图片 | |
| fig, ax = plt.subplots(1, 1, figsize=(12, 12)) | |
| ax.imshow(torchvision.utils.make_grid(x.detach().cpu().clip(-1, 1), nrow=8)[0], cmap='Greys') | |
| ``` | |
| 0it [00:00, ?it/s] | |
| <matplotlib.image.AxesImage> | |
|  | |
| 就是这么简单!我们现在就能以类别条件控制生成图片了。 | |
| 希望你喜欢这个样例。一如既往地,如果你有问题,你随时可以在 Discord 上留言。 | |
| ```python | |
| # 练习(选做):用同样方法在 FashionMNIST 数据集上试试,顺带调整学习率、batch size 和训练轮次(epochs)等参数试试。 | |
| # 你能用比上述样例更少的训练时间得到些看起来不错的图片吗? | |
| ``` | |