SuSung-boy commited on
Commit
5b841cf
1 Parent(s): 649c4af

第二单元校对完成

Browse files
markdown/unit2/01_finetuning_and_guidance_CN_Beta.md ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fine-Tuning and Guidance
2
+
3
+ 在这一节中,我们将讲解基于现有模型实现模型改造的方法,主要实现方法有两种:
4
+
5
+ * **微调(fine-tuning)**:通过在新的数据集上重新训练现有模型,来改变原有模型的生成类型
6
+ * **引导(guidance)**:通过在推理阶段对现有模型加入额外的控制信息,来引导原有模型某些特性的生成过程
7
+
8
+ ## 你将学到:
9
+
10
+ 到本章结束时,你将学会:
11
+
12
+ - 创建一个采样循环,并使用新调度器(scheduler)更快地完成采样
13
+ - 在新数据集上基于现有的扩散模型微调,这包括:
14
+ - 使用梯度累加方法来应对训练硬件条件对 batch size 的限制
15
+ - 上传训练样本和日志(通过附带的脚本程序)至 [Weights and Biases](https://wandb.ai/site) 网站,以此来监控训练过程
16
+ - 保存最终结果管线(pipeline)并上传到 Hub
17
+ - 通过引入损失函数来引导采样过程,以此对现有模型施加控制,这包括:
18
+ - 通过一个简单的基于颜色的损失函数来探索不同的引导方法
19
+ - 使用 CLIP,用文本来引导生成过程
20
+ - 在 Gradio 和 🤗 Spaces 上分享你定制的采样循环方法
21
+
22
+ ❓如果你有任何问题,欢迎在 Hugging Face Discord 的 `#diffusion-models-class` 频道留言。如果你还没有 Discord 账号,可以点击这里注册:https://huggingface.co/join/discord
23
+
24
+ ## 配置过程和需要引入的库
25
+
26
+ 要将微调模型上传到 Hugging Face Hub 上,你需要登录 Hugging Face 账号,获取一个 **具有写入权限的访问令牌**。运行下列代码,你可以登陆账号并跳转到相关页面配置令牌。在模型训练过程中,如果你想使用训练脚本记录样本和日志,你还需要一个 Weights and Biases 账号,同样地,在需要登录账号时,也会有相关代码指引。
27
+
28
+ 除此之外,你还需要安装一些依赖库并在程序中按需引入,以及指定计算设备,这样就配置完成了。代码如下:
29
+
30
+ ```python
31
+ !pip install -qq diffusers datasets accelerate wandb open-clip-torch
32
+ ```
33
+
34
+
35
+ ```python
36
+ # 登录 Hugging Face Hub,分享模型
37
+ # 请确保访问令牌具有写入权限
38
+ from huggingface_hub import notebook_login
39
+
40
+ notebook_login()
41
+ ```
42
+
43
+ Token is valid.
44
+ Your token has been saved in your configured git credential helpers (store).
45
+ Your token has been saved to /root/.huggingface/token
46
+ Login successful
47
+
48
+
49
+
50
+ ```python
51
+ import numpy as np
52
+ import torch
53
+ import torch.nn.functional as F
54
+ import torchvision
55
+ from datasets import load_dataset
56
+ from diffusers import DDIMScheduler, DDPMPipeline
57
+ from matplotlib import pyplot as plt
58
+ from PIL import Image
59
+ from torchvision import transforms
60
+ from tqdm.auto import tqdm
61
+ ```
62
+
63
+
64
+ ```python
65
+ device = (
66
+ "mps"
67
+ if torch.backends.mps.is_available()
68
+ else "cuda"
69
+ if torch.cuda.is_available()
70
+ else "cpu"
71
+ )
72
+ ```
73
+
74
+ ## 载入一个预训练过的管线
75
+
76
+ 首先我们载入一个现有的管线,来看看它能为我们做些什么:
77
+
78
+
79
+
80
+ ```python
81
+ image_pipe = DDPMPipeline.from_pretrained("google/ddpm-celebahq-256")
82
+ image_pipe.to(device);
83
+ ```
84
+
85
+
86
+ Fetching 4 files: 0%| | 0/4 [00:00<?, ?it/s]
87
+
88
+
89
+ 可以非常简单地生成图像。只需调用管线的内置 [`__call__`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddpm/pipeline_ddpm.py#L42) 方法,跟调用函数的方式一样:
90
+
91
+
92
+ ```python
93
+ images = image_pipe().images
94
+ images[0]
95
+ ```
96
+
97
+
98
+ 0%| | 0/1000 [00:00<?, ?it/s]
99
+
100
+
101
+
102
+
103
+
104
+
105
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_9_1.png)
106
+
107
+
108
+
109
+
110
+ 代码非常简洁,但生成速度有点慢!所以,在正式介绍本章内容之前,我们先窥探一下采样循环实际运行起来是什么样的,再探讨一下能不能用更炫酷的采样器来加速这一过程:
111
+
112
+ ## DDIM:更快的采样过程
113
+
114
+ 在生成图像的每一个采样步骤中,模型都会接收一个噪声输入,同时输出预测的噪声残差(以此来估计不含噪声的完整图像是什么样的)。采样初期,模型的预测结果不会特别好,因此我们需要把采样过程更精细地分解成更多步骤。但另一方面,使用更长的采样步骤(如 1000+ 步)也没必要,最近的很多研究已经找到了保证生成图像质量的同时尽可能地减少采样步骤的方法。
115
+
116
+ 在 🤗 Diffusers 库中,这些 **采样方法是通过调度器(scheduler)来控制的**,每次采样通过 `step()` 函数完成。要生成目标图片,我们首先随机化一个初始噪声 $x$,在每个时间步(timestep)的采样中,调度器都会把噪声 $x$ 输入给模型,同时把模型的预测结果再次输入给 `step()` 函数。`step()` 函数返回输出的 `prev_sample` 属性就是下一次采样的输入噪声,之所以叫 “previous”,是因为我们在时间上是 “落后” 的,即从 “高噪声” 到 “低噪声”(这和前向扩散过程是相反的)。
117
+
118
+ 我们来实践一下:先载入一个 scheduler,这里用的是 DDIMScheduler(基于这篇论文:[Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502))。与原版的 DDPM 相比,它可以用少得多的采样步骤来生成效果相当的图像样本。
119
+
120
+
121
+ ```python
122
+ # 创建 DDIM 调度器实例,设置采样步数
123
+ scheduler = DDIMScheduler.from_pretrained("google/ddpm-celebahq-256")
124
+ scheduler.set_timesteps(num_inference_steps=40)
125
+ ```
126
+
127
+ 可以看到,用 DDIM 调度器之后,模型仅采样了 40 步,每一步采样相当于 1000 步调度器的 25 次采样:
128
+
129
+
130
+ ```python
131
+ scheduler.timesteps
132
+ ```
133
+
134
+
135
+
136
+
137
+ tensor([975, 950, 925, 900, 875, 850, 825, 800, 775, 750, 725, 700, 675, 650,
138
+ 625, 600, 575, 550, 525, 500, 475, 450, 425, 400, 375, 350, 325, 300,
139
+ 275, 250, 225, 200, 175, 150, 125, 100, 75, 50, 25, 0])
140
+
141
+
142
+
143
+ 我们来随机初始化 4 张噪声图像,把它们输入给采样循环,观察一下每一步的 $x$ 和预测的去噪图像:
144
+
145
+
146
+ ```python
147
+ # 随机初始化 4 张 噪声图像
148
+ x = torch.randn(4, 3, 256, 256).to(device) # 图像数量 为 4, 分辨率为 256x256, 通道数为 3
149
+
150
+ # 采样循环
151
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
152
+
153
+ # 模型输入
154
+ model_input = scheduler.scale_model_input(x, t)
155
+
156
+ # 预测结果
157
+ with torch.no_grad():
158
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
159
+
160
+ # 查看调度器采样更新的输出
161
+ scheduler_output = scheduler.step(noise_pred, t, x)
162
+
163
+ # 更新 x
164
+ x = scheduler_output.prev_sample
165
+
166
+ # 以一定的采样间隔可视化噪声 x 和去噪图像
167
+ if i % 10 == 0 or i == len(scheduler.timesteps) - 1:
168
+ fig, axs = plt.subplots(1, 2, figsize=(12, 5))
169
+
170
+ grid = torchvision.utils.make_grid(x, nrow=4).permute(1, 2, 0)
171
+ axs[0].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5)
172
+ axs[0].set_title(f"Current x (step {i})")
173
+
174
+ pred_x0 = (
175
+ scheduler_output.pred_original_sample
176
+ ) # 并非适用所有的调度器
177
+ grid = torchvision.utils.make_grid(pred_x0, nrow=4).permute(1, 2, 0)
178
+ axs[1].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5)
179
+ axs[1].set_title(f"Predicted denoised images (step {i})")
180
+ plt.show()
181
+ ```
182
+
183
+
184
+ 0it [00:00, ?it/s]
185
+
186
+
187
+
188
+
189
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_17_1.png)
190
+
191
+
192
+
193
+
194
+
195
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_17_2.png)
196
+
197
+
198
+
199
+
200
+
201
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_17_3.png)
202
+
203
+
204
+
205
+
206
+
207
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_17_4.png)
208
+
209
+
210
+
211
+
212
+
213
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_17_5.png)
214
+
215
+
216
+
217
+ 可以看出,一开始预测结果并不是那么好,但随着采样过程的迭代,预测的结果被一步步改善。如果你想了解 `steps()` 函数内的数学原理,可以通过这行指令查看(带注释的)详细代码:
218
+
219
+
220
+ ```python
221
+ # ??scheduler.step
222
+ ```
223
+
224
+ 你也可以直接用新的调度器替换原有管线(pipeline)中的调度器,然后采样循环试试看。代码如下:
225
+
226
+
227
+ ```python
228
+ image_pipe.scheduler = scheduler
229
+ images = image_pipe(num_inference_steps=40).images
230
+ images[0]
231
+ ```
232
+
233
+
234
+ 0%| | 0/40 [00:00<?, ?it/s]
235
+
236
+
237
+
238
+
239
+
240
+
241
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_21_1.png)
242
+
243
+
244
+
245
+
246
+ 好了!现在我们能在可接受的时间内生成图片了!这样我们在接下来的章节就能更快地学习和实践了:)
247
+
248
+ ## 微调
249
+
250
+ 现在来玩点好玩的!我们已经有了一个预训练过的管线(pipeline),那怎么用新数据重新训模型来生成图片呢?
251
+
252
+ 看起来这和我们从头训练模型是几乎一样的(如 [第一单元](../unit1) 所见),除了一点不同,这里使用现有模型作为初始化(而不是随机初始化)。让我们实践一下,看看有哪些需要额外考虑的因素。
253
+
254
+ 首先数据方面,最好是用一些与上文中人脸生成管线中类似的训练数据,可以尝试用 [Vintage Faces 数据集](https://huggingface.co/datasets/Norod78/Vintage-Faces-FFHQAligned) 或者 [动漫人脸数据集](https://huggingface.co/datasets/huggan/anime-faces)。但我们先浅玩一下,还是用第一单元中使用的的蝴蝶数据集。运行以下代码可以下载蝴蝶数据集,并创建一个能按批(batch)采样图片的 `dataloader` 实例:
255
+
256
+
257
+ ```python
258
+ # @markdown 加载、准备数据集:
259
+ # 如果你不是在 Colab 上运行本书代码,请把带有 #@ 部分的代码(是 Colab 用于调整 UI 界面用的)注释掉,这样你在其他平台上运行也不会报错。
260
+
261
+
262
+ dataset_name = "huggan/smithsonian_butterflies_subset" # @param
263
+ dataset = load_dataset(dataset_name, split="train")
264
+ image_size = 256 # @param
265
+ batch_size = 4 # @param
266
+ preprocess = transforms.Compose(
267
+ [
268
+ transforms.Resize((image_size, image_size)),
269
+ transforms.RandomHorizontalFlip(),
270
+ transforms.ToTensor(),
271
+ transforms.Normalize([0.5], [0.5]),
272
+ ]
273
+ )
274
+
275
+
276
+ def transform(examples):
277
+ images = [preprocess(image.convert("RGB")) for image in examples["image"]]
278
+ return {"images": images}
279
+
280
+
281
+ dataset.set_transform(transform)
282
+
283
+ train_dataloader = torch.utils.data.DataLoader(
284
+ dataset, batch_size=batch_size, shuffle=True
285
+ )
286
+
287
+ print("Previewing batch:")
288
+ batch = next(iter(train_dataloader))
289
+ grid = torchvision.utils.make_grid(batch["images"], nrow=4)
290
+ plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5);
291
+ ```
292
+
293
+ Using custom data configuration huggan--smithsonian_butterflies_subset-7665b1021a37404c
294
+ Found cached dataset parquet (/home/lewis_huggingface_co/.cache/huggingface/datasets/huggan___parquet/huggan--smithsonian_butterflies_subset-7665b1021a37404c/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)
295
+
296
+
297
+ Previewing batch:
298
+
299
+
300
+
301
+
302
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_25_2.png)
303
+
304
+
305
+
306
+ **考虑因素1:** 我们这里使用的 batch size 很小(只有 4),因为输入给模型训练的图片尺寸的较大(256px),同时模型也很大,因此调大 batch size 的话 GPU RAM 可能就不够用了。可以考虑缩小图片尺寸,换取更大的 batch size 来加速训练,不过上文中加载的模型一开始都是基于 256px 尺寸的图片来设计和训练的。
307
+
308
+ 现在我们来看看训练循环。我们把要优化的目标参数设定为 `image_pipe.unet.parameters()`,以此来更新现有模型的权重。除此之外的其它部分代码基本上和第一单元样例中的相同。如果你是在 Colab 上运行这些代码,整个过程大约需要10分钟,你可以趁这个时间间隙喝杯茶休息一下。
309
+
310
+
311
+ ```python
312
+ num_epochs = 2 # @param
313
+ lr = 1e-5 # 2param
314
+ grad_accumulation_steps = 2 # @param
315
+
316
+ optimizer = torch.optim.AdamW(image_pipe.unet.parameters(), lr=lr)
317
+
318
+ losses = []
319
+
320
+ for epoch in range(num_epochs):
321
+ for step, batch in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):
322
+ clean_images = batch["images"].to(device)
323
+ # 生成要加到图片上的随机采样噪声
324
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
325
+ bs = clean_images.shape[0]
326
+
327
+ # 对每张图片设置随机采样时间步
328
+ timesteps = torch.randint(
329
+ 0,
330
+ image_pipe.scheduler.num_train_timesteps,
331
+ (bs,),
332
+ device=clean_images.device,
333
+ ).long()
334
+
335
+ # 根据每个采样时间步的噪声大小,把噪声加到原始图片上
336
+ # (这就是前向扩散过程)
337
+ noisy_images = image_pipe.scheduler.add_noise(clean_images, noise, timesteps)
338
+
339
+ # 预测噪声残差
340
+ noise_pred = image_pipe.unet(noisy_images, timesteps, return_dict=False)[0]
341
+
342
+ # 用预测噪声残差和实际增加的噪声对比来计算损失函数
343
+ loss = F.mse_loss(
344
+ noise_pred, noise
345
+ ) # NB - trying to predict noise (eps) not (noisy_ims-clean_ims) or just (clean_ims)
346
+
347
+ # 保存 loss,用于可视化分析
348
+ losses.append(loss.item())
349
+
350
+ # 根据损失函数反向传播,用优化器更新模型参数
351
+ loss.backward(loss)
352
+
353
+ # 梯度累加:
354
+ if (step + 1) % grad_accumulation_steps == 0:
355
+ optimizer.step()
356
+ optimizer.zero_grad()
357
+
358
+ print(
359
+ f"Epoch {epoch} average loss: {sum(losses[-len(train_dataloader):])/len(train_dataloader)}"
360
+ )
361
+
362
+ # 绘制 loss 可视化图:
363
+ plt.plot(losses)
364
+ ```
365
+
366
+
367
+ 0%| | 0/250 [00:00<?, ?it/s]
368
+
369
+
370
+ Epoch 0 average loss: 0.013324214214226231
371
+
372
+
373
+
374
+ 0%| | 0/250 [00:00<?, ?it/s]
375
+
376
+
377
+ Epoch 1 average loss: 0.014018508377484978
378
+
379
+
380
+
381
+
382
+
383
+ [<matplotlib.lines.Line2D>]
384
+
385
+
386
+
387
+
388
+
389
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_28_5.png)
390
+
391
+
392
+
393
+ **考虑因素2:** 我们的损失值曲线简直像噪声一样混乱!这是因为每一次迭代我们都只用了四个训练图片,而且加到图片上的噪声还都是随机采样的,这对于训练过程不太友好。一种弥补措施是:使用非常小的学习率来限制权重每次更新的幅度。但还有一个更好的方法,既能得到与大 batch size 训练相当的收益,又不会让我们的内存爆掉。
394
+
395
+ 可以点击查看 [gradient accumulation](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 就会把梯度累加(加和)起来,这样多个批次的数据计算的 loss 就会被高效地融合,这样只产出一个单独的(更好的)��度估计用于参数更新。这样做会减少参数更新的总次数,就跟使用更大的 batch size 时的效果是一致的,这是一种时间换空间的思想。目前有很多深度学习框架都实现了梯度累加(比如 🤗 的 [Accelerate](https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation) 库就可以非常简便的调用)。不过在本书,我们会学习从零实现梯度累加,掌握了之后会对你以后训练模型但 GPU 内存受限时非常有帮助。如上述代码(在注释 `# 梯度累加` 之后)可见,其实也写不了几行代码。
396
+
397
+
398
+ ```python
399
+ # 练习:试试你能不能在第一单元的训练循环中实现梯度累加。
400
+ # 思考应该怎么基于梯度累积的次数来调整学习率?
401
+ # 思考为什么需要调整学习率?
402
+ ```
403
+
404
+ **考虑因素3:** 即使这样,我们的训练过程还是太慢了。而且每遍历完一轮数据集才打印出一行更新信息,这样的反馈不足以让我们知道训练的怎么样了。我们还可以:
405
+
406
+ * 训练过程中时不时地生成一些图像,来检查一下模型性能;
407
+ * 训练过程中记录一些信息到日志里,如 loss 值、生成图片等,然后可以使用诸如 Weights and Biases 或 tensorboard 之类的工具来可视化监控。
408
+
409
+ 我创建了一个可以快速上手的脚本程序([`finetune_model.py`](https://github.com/huggingface/diffusion-models-class/blob/main/unit2/finetune_model.py)),实现了在上述的训练代码中加入少量日志记录的功能。可以点击查看 [一次训练日志](https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341):
410
+
411
+
412
+ ```python
413
+ %wandb johnowhitaker/dm_finetune/2upaa341 # 需要一个 W&B 账户,如果不需要登录可跳过此代码
414
+ ```
415
+
416
+
417
+ <iframe src="https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341?jupyter=true" style="border:none;width:100%;height:420px;"></iframe>
418
+
419
+
420
+ 随着训练过程的进展,观察生成的样本图片是如何一步步演变的也挺有意思。即使从损失值的变化看不出模型在进步,从图片上我们仍然能看到一个从原有图像分布(卧室数据集)到新的数据集(wikiart 数据集)逐渐演变的过程。在本章的最后还有一些被注释掉的用于微调的代码,可以使用该脚本程序替代上面的代码块。
421
+
422
+
423
+ ```python
424
+ # 练习:试试你能不能修改第一单元的官方示例训练脚本程序
425
+ # 实现使用现有模型训练,而不是从头开始
426
+ # 对比一下上面链接指向的脚本程序,哪些额外功能是脚本程序里没有的?
427
+ ```
428
+
429
+ 用微调的模型生成一些图片,可以看到这些脸部已经变得非常奇怪了!
430
+
431
+
432
+ ```python
433
+ # 生成图片并可视化:
434
+ x = torch.randn(8, 3, 256, 256).to(device) # Batch of 8
435
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
436
+ model_input = scheduler.scale_model_input(x, t)
437
+ with torch.no_grad():
438
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
439
+ x = scheduler.step(noise_pred, t, x).prev_sample
440
+ grid = torchvision.utils.make_grid(x, nrow=4)
441
+ plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5);
442
+ ```
443
+
444
+
445
+ 0it [00:00, ?it/s]
446
+
447
+
448
+
449
+
450
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_36_1.png)
451
+
452
+
453
+
454
+ **考虑因素4:** 微调的结果很可能是难以预知的。不过如果把训练时间设置的长一些,模型生成的蝴蝶图片会很完美。要是你对艺术风格很感兴趣,你会发现训练的中间过程模型生成的图片演变极其有趣!不妨试试观察一下短期和长期的训练过程,并调整学习率大小,看看这会怎样影响模型的最终输出。
455
+
456
+ ### 代码实战:用上面使用样例脚本程序在 WikiArt 数据集上去微调模型
457
+
458
+ 如果你想训练一个和我在 WikiArt 数据集上训练的类似的模型,你可以去掉下列代码的注释符号并运行代码。不过由于这需要消耗不少的时间和 GPU 内存,我还是建议你学习完本章节内容后再尝试。
459
+
460
+
461
+ ```python
462
+ ## 下载微调用的脚本:
463
+ # !wget https://github.com/huggingface/diffusion-models-class/raw/main/unit2/finetune_model.py
464
+ ```
465
+
466
+
467
+ ```python
468
+ ## 运行脚本,在 Vintage Face 数据集上训练模型
469
+ ## (最好在终端里跑):
470
+ # !python finetune_model.py --image_size 128 --batch_size 8 --num_epochs 16\
471
+ # --grad_accumulation_steps 2 --start_model "google/ddpm-celebahq-256"\
472
+ # --dataset_name "Norod78/Vintage-Faces-FFHQAligned" --wandb_project 'dm-finetune'\
473
+ # --log_samples_every 100 --save_model_every 1000 --model_save_name 'vintageface'
474
+ ```
475
+
476
+ ### 保存和载入微调过的管线
477
+
478
+ 现在我们已经微调好了扩散模型中 U-Net 的权重,接下来可以运行以下代码将它保存到本地文件夹中:
479
+
480
+
481
+ ```python
482
+ image_pipe.save_pretrained("my-finetuned-model")
483
+ ```
484
+
485
+ 与第一单元类似,运行代码后会保存配置文件、模型、调度器。
486
+
487
+
488
+ ```python
489
+ !ls {"my-finetuned-model"}
490
+ ```
491
+
492
+ model_index.json scheduler unet
493
+
494
+
495
+ 接下来你可以参照第一单元的 [Introduction to Diffusers](https://github.com/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) 部分,把模型上传到 Hub 上以备后续使用:
496
+
497
+
498
+ ```python
499
+ # @title: 将本地保存的管线上传至 Hub
500
+
501
+ # 代码: 将本地保存的管线上传至 Hub
502
+ from huggingface_hub import HfApi, ModelCard, create_repo, get_full_repo_name
503
+
504
+ # 配置 Hub 仓库,上传文件
505
+ model_name = "ddpm-celebahq-finetuned-butterflies-2epochs" # @param 给传到 Hub 上的文件命名
506
+ local_folder_name = "my-finetuned-model" # @param 脚本程序生成的名字,你也可以通过 image_pipe.save_pretrained('save_name') 指定
507
+ description = "Describe your model here" # @param
508
+ hub_model_id = get_full_repo_name(model_name)
509
+ create_repo(hub_model_id)
510
+ api = HfApi()
511
+ api.upload_folder(
512
+ folder_path=f"{local_folder_name}/scheduler", path_in_repo="", repo_id=hub_model_id
513
+ )
514
+ api.upload_folder(
515
+ folder_path=f"{local_folder_name}/unet", path_in_repo="", repo_id=hub_model_id
516
+ )
517
+ api.upload_file(
518
+ path_or_fileobj=f"{local_folder_name}/model_index.json",
519
+ path_in_repo="model_index.json",
520
+ repo_id=hub_model_id,
521
+ )
522
+
523
+ # 添加一个模型名片 (可选,建议添加)
524
+ content = f"""
525
+ ---
526
+ license: mit
527
+ tags:
528
+ - pytorch
529
+ - diffusers
530
+ - unconditional-image-generation
531
+ - diffusion-models-class
532
+ ---
533
+
534
+ # Example Fine-Tuned Model for Unit 2 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class)
535
+
536
+ {description}
537
+
538
+ ## Usage
539
+
540
+ ```python
541
+ from diffusers import DDPMPipeline
542
+
543
+ pipeline = DDPMPipeline.from_pretrained('{hub_model_id}')
544
+ image = pipeline().images[0]
545
+ image
546
+ ```
547
+ """
548
+
549
+ card = ModelCard(content)
550
+ card.push_to_hub(hub_model_id)
551
+ ```
552
+
553
+
554
+
555
+
556
+ 'https://huggingface.co/lewtun/ddpm-celebahq-finetuned-butterflies-2epochs/blob/main/README.md'
557
+
558
+
559
+
560
+ 至此,你已经完成了你的第一个微调扩散模型!祝贺!
561
+
562
+ 接下里的部分,我将使用一个在 [LSUM bedrooms 数据集](https://huggingface.co/google/ddpm-bedroom-256) 上训练且在 WikiArt 数据集上微调了大约一轮的 [模型](https://huggingface.co/johnowhitaker/sd-class-wikiart-from-bedrooms)。你可以根据自己偏好来选择是否跳过这部分代码,使用上文中我们微调过的人脸或蝴蝶管线,或者直接从 Hub 上加载一个模型。
563
+
564
+
565
+ ```python
566
+ # 加载预训练管线
567
+ pipeline_name = "johnowhitaker/sd-class-wikiart-from-bedrooms"
568
+ image_pipe = DDPMPipeline.from_pretrained(pipeline_name).to(device)
569
+
570
+ # 使用 DDIM 调度器,设置采样步长不小于 40,采样图片
571
+ scheduler = DDIMScheduler.from_pretrained(pipeline_name)
572
+ scheduler.set_timesteps(num_inference_steps=40)
573
+
574
+ # 随机初始化噪声 (每批次包含 8 张图片)
575
+ x = torch.randn(8, 3, 256, 256).to(device)
576
+
577
+ # 采样循环
578
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
579
+ model_input = scheduler.scale_model_input(x, t)
580
+ with torch.no_grad():
581
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
582
+ x = scheduler.step(noise_pred, t, x).prev_sample
583
+
584
+ # 可视化结果
585
+ grid = torchvision.utils.make_grid(x, nrow=4)
586
+ plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5);
587
+ ```
588
+
589
+
590
+ Downloading: 0%| | 0.00/180 [00:00<?, ?B/s]
591
+
592
+
593
+
594
+ Fetching 4 files: 0%| | 0/4 [00:00<?, ?it/s]
595
+
596
+
597
+
598
+ Downloading: 0%| | 0.00/938 [00:00<?, ?B/s]
599
+
600
+
601
+
602
+ Downloading: 0%| | 0.00/455M [00:00<?, ?B/s]
603
+
604
+
605
+
606
+ Downloading: 0%| | 0.00/288 [00:00<?, ?B/s]
607
+
608
+
609
+
610
+ 0it [00:00, ?it/s]
611
+
612
+
613
+
614
+
615
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_48_6.png)
616
+
617
+
618
+
619
+ **考虑因素5:** 一般而言,很难判断微调的效果到底怎么样,而且 “效果好” 这种表述在不同场景的实际表现也不一样。其中一个例子:如果你想在一个很小的数据集上微调一个文生图 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) 中看不出模型在进步,但从生成样本可视化图中也能很清楚地看出一个从原始图片到更有艺术范图片的演变过程,只是中间过��看着不太协调罢了。
620
+
621
+ 具体细节会在下一部分讲解,包括怎样对这类模型施加额外的引导,从而更好地控制模型输出。
622
+
623
+ ## 引导
624
+
625
+ 如果我们想对生成的图片施加点控制,需要怎么做?例如想让生成的图片整体色调都偏向于某种颜色。这就要用到本节要介绍的 **引导(guidance)**,这是一项可以在生成图片过程中施加额外控制的技术。
626
+
627
+ 第一步,先创建一个控制函数,它需要定义一个优化目标(也就是损失函数)。如果以刚提到的颜色为例,那这个控制函数的功能就是:将生成图片的像素值和目标颜色(下面代码使用浅蓝绿色)的像素值逐一对比,然后返回整张图片的平均误差:
628
+
629
+
630
+ ```python
631
+ def color_loss(images, target_color=(0.1, 0.9, 0.5)):
632
+ """输入 images 为 (R, G, B) 格式,返回与目标颜色的平均像素误差
633
+ 默认目标颜色为浅蓝绿色,像素值为 (0.1, 0.9, 0.5)"""
634
+ target = (
635
+ torch.tensor(target_color).to(images.device) * 2 - 1
636
+ ) # 将图片像素值映射到 (-1, 1)
637
+ target = target[
638
+ None, :, None, None
639
+ ] # 匹配输入 images 的 shape:(b, c, h, w)
640
+ error = torch.abs(
641
+ images - target
642
+ ).mean() # images 和目标颜色的平均像素误差绝对值
643
+ return error
644
+ ```
645
+
646
+ 接下来,我们要修改采样循环。在每一次迭代,我们需要:
647
+ - 创建一个新的噪声 x 变量,设置其 `requires_grad = True`
648
+ - 计算对应的去噪图片(x0)
649
+ - 将 x0 输入给损失函数
650
+ - 计算损失函数对 x 的 **梯度值**
651
+ - 先用得到的梯度值更新 x,再调用 `scheuler.step()`,这样变量 x 就会依据引导函数计算的梯度方向,但是以更小的幅度更新。
652
+
653
+ 下面代码展示了两种实现方法,你可以探索一下哪一种更好。第一种,先从 UNet 得到预测的噪声残差,再给 x 设置 requires_grad,这样对内存来讲更高效一点(因为不需要链式地在整个扩散模型中追踪梯度),但得到的梯度精度会稍低一些。第二种,先给 x 设置requires_grad,然后再输入 UNet 计算预测的 x0。
654
+
655
+
656
+ ```python
657
+ # 实现 1: 先计算 loss 梯度,再设置 x.requires_grad
658
+
659
+ # 引导 scale 值决定了效果强度
660
+ guidance_loss_scale = 40 # 尝试改为 5, 100 试试看
661
+
662
+ x = torch.randn(8, 3, 256, 256).to(device)
663
+
664
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
665
+
666
+ # 准备模型输入
667
+ model_input = scheduler.scale_model_input(x, t)
668
+
669
+ # 预测噪声残差
670
+ with torch.no_grad():
671
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
672
+
673
+ # 设置 x.requires_grad 为 True
674
+ x = x.detach().requires_grad_()
675
+
676
+ # 计算预测 x0
677
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
678
+
679
+ # 计算 loss
680
+ loss = color_loss(x0) * guidance_loss_scale
681
+ if i % 10 == 0:
682
+ print(i, "loss:", loss.item())
683
+
684
+ # 计算梯度
685
+ cond_grad = -torch.autograd.grad(loss, x)[0]
686
+
687
+ # 根据梯度更新 x
688
+ x = x.detach() + cond_grad
689
+
690
+ # 调用 scheduler.step()
691
+ x = scheduler.step(noise_pred, t, x).prev_sample
692
+
693
+ # 可视化输出
694
+ grid = torchvision.utils.make_grid(x, nrow=4)
695
+ im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5
696
+ Image.fromarray(np.array(im * 255).astype(np.uint8))
697
+ ```
698
+
699
+
700
+ 0it [00:00, ?it/s]
701
+
702
+
703
+ 0 loss: 27.279136657714844
704
+ 10 loss: 11.286816596984863
705
+ 20 loss: 10.683112144470215
706
+ 30 loss: 10.942476272583008
707
+
708
+
709
+
710
+
711
+
712
+
713
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_54_2.png)
714
+
715
+
716
+
717
+
718
+ 第二种实现方法资源占用较多,即使把 batch size 从 8 降低到 4,仍然需要几乎第一种两倍的 GPU 内存。试试看你能不能找出两种实现方式的异同,想想为什么这里计算的梯度更精确?
719
+
720
+
721
+ ```python
722
+ # 实现 2: 先设置 x.requires_grad,再计算 loss 梯度
723
+
724
+ guidance_loss_scale = 40
725
+ x = torch.randn(4, 3, 256, 256).to(device)
726
+
727
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
728
+
729
+ # 设置 requires_grad,输入给模型前向计算
730
+ x = x.detach().requires_grad_()
731
+ model_input = scheduler.scale_model_input(x, t)
732
+
733
+ # 预测噪声残差 (含梯度)
734
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
735
+
736
+ # 计算预测 x0:
737
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
738
+
739
+ # 计算 loss
740
+ loss = color_loss(x0) * guidance_loss_scale
741
+ if i % 10 == 0:
742
+ print(i, "loss:", loss.item())
743
+
744
+ # 计算梯度
745
+ cond_grad = -torch.autograd.grad(loss, x)[0]
746
+
747
+ # 根据梯度更新 x
748
+ x = x.detach() + cond_grad
749
+
750
+ # 调用 scheduler.step()
751
+ x = scheduler.step(noise_pred, t, x).prev_sample
752
+
753
+
754
+ grid = torchvision.utils.make_grid(x, nrow=4)
755
+ im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5
756
+ Image.fromarray(np.array(im * 255).astype(np.uint8))
757
+ ```
758
+
759
+
760
+ 0it [00:00, ?it/s]
761
+
762
+
763
+ 0 loss: 30.750328063964844
764
+ 10 loss: 18.550724029541016
765
+ 20 loss: 17.515094757080078
766
+ 30 loss: 17.55681037902832
767
+
768
+
769
+
770
+
771
+
772
+
773
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_56_2.png)
774
+
775
+
776
+
777
+
778
+ 在第二种实现方法中,内存的需求更高了,但颜色迁移的效果却减弱了,这里你可能觉得这种方法不如第一种方法。但是这里生成的图片更接近于原模型的训练数据。通常你可以通过增大 `guidance_loss_scale` 来加强颜色迁移的效果。你可以尝试一下两种方案,视最终效果来决定选择使用哪种方案。
779
+
780
+
781
+ ```python
782
+ # 练习:选一个你最喜欢的颜色,并将它在 RGB 空间中表示出来
783
+ # 修改上面代码的 `color_loss()`,将颜色改成你选的颜色,训练模型并采样检查生成图片,看看是否和你期望的一致。
784
+ ```
785
+
786
+ ## CLIP 引导
787
+
788
+ 给模型增加颜色引导仅只是控制引导的很小的例子。现在我们想要仅通过简单的文字描述 来控制我们想生成图片的引导模式,该怎么做呢?
789
+
790
+ [CLIP](https://openai.com/blog/clip/) 是一个由 OpenAI 开发的模型,它可以度量图片和文字的相似性。这个功能非常强大,因为它能够计算图片和文字相似性的具体量化值。另外由于这个过程是可微分的,我们就可以将它作为损失函数来引导我们的扩散模型!
791
+
792
+ 我不会解释太多其中细节。整体方法如下:
793
+ - 对文字提示语做词汇嵌入(embedding),得到一个 512 维的 CLIP embedding
794
+ - 对于扩散模型的生成过程的每一步:
795
+ - 对预测的去噪图片可以进行多种变体(如重参数化,不同的变体会对应不同的目标监督信号,有的变体会带来更清晰的计算损失函数的方式)。
796
+ - 对每一个预测出的去噪图片,用 CLIP 给图片做嵌入(embedding),并将这个嵌入和文字的嵌入做对比(用一种叫 Great Circle Distance Squared 的方法计算相似度)
797
+ - 计算 loss 对于 x 的梯度并更新 x,再调用 scheduler.step()
798
+
799
+ 如果你想了解关于 CLIP 的详细讲解,可以点击 [这个课程](https://johnowhitaker.github.io/tglcourse/clip.html) 或 [关于 OpenCLIP 的报告](https://wandb.ai/johnowhitaker/openclip-benchmarking/reports/Exploring-OpenCLIP--VmlldzoyOTIzNzIz)。本书使用的 CLIP 就是从 OpenCLIP 载入的,运行下列代码就可以载入一个 CLIP 模型:
800
+
801
+
802
+ ```python
803
+ # @markdown 载入 CLIP 模型,定义损失函数
804
+ import open_clip
805
+
806
+ clip_model, _, preprocess = open_clip.create_model_and_transforms(
807
+ "ViT-B-32", pretrained="openai"
808
+ )
809
+ clip_model.to(device)
810
+
811
+ # 设计一个 transforms,实现 resize、augment、normalize 来匹配 CLIP 的训练数据
812
+ tfms = torchvision.transforms.Compose(
813
+ [
814
+ torchvision.transforms.RandomResizedCrop(224), # 随机裁剪
815
+ torchvision.transforms.RandomAffine(
816
+ 5
817
+ ), # 随机倾斜
818
+ torchvision.transforms.RandomHorizontalFlip(), # 可额外增加数据增强
819
+ torchvision.transforms.Normalize(
820
+ mean=(0.48145466, 0.4578275, 0.40821073),
821
+ std=(0.26862954, 0.26130258, 0.27577711),
822
+ ),
823
+ ]
824
+ )
825
+
826
+ # 定义损失函数:接收两张图片作为输入,计算 CLIP embedding,返回两个 embedding 的 Great Circle 距离
827
+ def clip_loss(image, text_features):
828
+ image_features = clip_model.encode_image(
829
+ tfms(image)
830
+ ) # 注意使用上文的 transforms
831
+ input_normed = torch.nn.functional.normalize(image_features.unsqueeze(1), dim=2)
832
+ embed_normed = torch.nn.functional.normalize(text_features.unsqueeze(0), dim=2)
833
+ dists = (
834
+ input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)
835
+ ) # 计算 Great Circle 距离的平方
836
+ return dists.mean()
837
+ ```
838
+
839
+ 100%|████████████████████████████████████████| 354M/354M [00:02<00:00, 120MiB/s]
840
+
841
+
842
+ 完成了定义损失函数之后,接下里的引导采样循环代码就和前面类似了,仅仅是把 `color_loss()` 换成了上述基于 CLIP 的损失函数:
843
+
844
+
845
+ ```python
846
+ # @markdown 使用 CLIP 引导模型
847
+
848
+ prompt = "Red Rose (still life), red flower painting" # @param
849
+
850
+ # 尝试修改参数值
851
+ guidance_scale = 8 # @param
852
+ n_cuts = 4 # @param
853
+
854
+ # 增大采样步可以得到更好的性能,但也会花费更多训练时间
855
+ scheduler.set_timesteps(50)
856
+
857
+ # 使用 CLIP 对文本做 embedding,作为目标监督信号
858
+ text = open_clip.tokenize([prompt]).to(device)
859
+ with torch.no_grad(), torch.cuda.amp.autocast():
860
+ text_features = clip_model.encode_text(text)
861
+
862
+
863
+ x = torch.randn(4, 3, 256, 256).to(
864
+ device
865
+ ) # 会占用较高的内存,如果你的内存不够可以减小 batch size
866
+
867
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
868
+
869
+ model_input = scheduler.scale_model_input(x, t)
870
+
871
+ # 预测噪声残差
872
+ with torch.no_grad():
873
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
874
+
875
+ cond_grad = 0
876
+
877
+ for cut in range(n_cuts):
878
+
879
+ # 设置 x 的 requires_grad
880
+ x = x.detach().requires_grad_()
881
+
882
+ # 计算预测 x0:
883
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
884
+
885
+ # 计算 loss
886
+ loss = clip_loss(x0, text_features) * guidance_scale
887
+
888
+ # 计算梯度 (使用平均值,这里做了正则化)
889
+ cond_grad -= torch.autograd.grad(loss, x)[0] / n_cuts
890
+
891
+ if i % 25 == 0:
892
+ print("Step:", i, ", Guidance loss:", loss.item())
893
+
894
+ # 根据梯度更新 x
895
+ alpha_bar = scheduler.alphas_cumprod[i]
896
+ x = (
897
+ x.detach() + cond_grad * alpha_bar.sqrt()
898
+ ) # 注意前面的正则化参数
899
+
900
+ # 调用 scheduler.step()
901
+ x = scheduler.step(noise_pred, t, x).prev_sample
902
+
903
+
904
+ grid = torchvision.utils.make_grid(x.detach(), nrow=4)
905
+ im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5
906
+ Image.fromarray(np.array(im * 255).astype(np.uint8))
907
+ ```
908
+
909
+
910
+ 0it [00:00, ?it/s]
911
+
912
+
913
+ Step: 0 , Guidance loss: 7.437869548797607
914
+ Step: 25 , Guidance loss: 7.174620628356934
915
+
916
+
917
+
918
+
919
+
920
+
921
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_62_2.png)
922
+
923
+
924
+
925
+
926
+ 看起来有点像玫瑰!显然模型还不够完美,你可以尝试调整一些参数,多跑几次实验,就能生成一些更令人满意的图片。
927
+
928
+ 如果仔细看上面的代码,你会发现我使用了 `alpha_bar.sqrt()` 作为缩放因子来控制梯度。虽然理论上有所谓正确的缩放梯度的方法,但实际上仍然需要实验验证可行性。对于有些引导来说,你可能希望大部分的引导作用都集中在刚开始的几步里,对于另一些(比如一些关注点在纹理方面的风格损失函数)来讲,你可能希望它仅在生成过程的结束部分加入进来。对此,下面展示一些可能的方案:
929
+
930
+
931
+ ```python
932
+ # @markdown 可视化缩放梯度方案:
933
+ plt.plot([1 for a in scheduler.alphas_cumprod], label="no scaling")
934
+ plt.plot([a for a in scheduler.alphas_cumprod], label="alpha_bar")
935
+ plt.plot([a.sqrt() for a in scheduler.alphas_cumprod], label="alpha_bar.sqrt()")
936
+ plt.plot(
937
+ [(1 - a).sqrt() for a in scheduler.alphas_cumprod], label="(1-alpha_bar).sqrt()"
938
+ )
939
+ plt.legend()
940
+ plt.title("Possible guidance scaling schedules");
941
+ ```
942
+
943
+
944
+
945
+ ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_65_0.png)
946
+
947
+
948
+
949
+ 你可以尝试跑几组实验,例如调整引导的 scale 值(`guidance_scale`),以及任何你能想到的技巧(比如流行的指定范围的梯度截断方法),看看能把生成效果做到多好。你也可以换成其它模型试试,比如本章开头使用的人脸模型。你能以可控的方式来让模型生成男性人脸图片吗?你还可以把 CLIP 引导和前面提到的颜色损失函数结合起来训练,等等。
950
+
951
+ 如果你看过一些 [CLIP 引导的扩散模型代码实战](https://huggingface.co/spaces/EleutherAI/clip-guided-diffusion/blob/main/app.py),你会发现许多库使用更复杂的引导方法来获得更好的性能:更好的随机图像裁剪选取规则,更多损失函数的变体等。在文本条件扩散模型出现之前,这曾经是最好的文本到图像转换系统!本书实现的 “玩具级” 版本有非常大的提升空间,但不管怎样,它仍然抓住了核心要点:借助于引导和 CLIP 惊人的性能,我们可以给非条件扩散模型加上文本条件的控制 🎨
952
+
953
+ ## 分享你制作的自定义采样循环 Gradio 样例
954
+
955
+ 也许你现在已经想出了一个引导生成过程的有趣的损失函数,如果你想把你的微调模型和自定义的采样策略分享给全世界......
956
+
957
+ 点击这里了解 [Gradio](https://gradio.app/)。Gradio 是一个免费的开源工具,可以让用户很方便地通过一个简单的网页界面来创建和分享交互式的机器学习模型应用程序。使用 Gradio,用户能够为自己的机器学习模型应用程序自定义接口,然后通过一个唯一的 URL 分享给他人。Gradio 现已集成到 🤗 Spaces,🤗 用户也可以很方便地创建和分享样例。
958
+
959
+ 我们将把我们需要的核心逻辑集成到一个函数中,这个函数接收一些输入然后输出一张图片,这可以封装成一个简单的接口,让用户能自己定义一些参数(这些参数将输入给图片生成的主函数)。有很多可用的 [组件](https://gradio.app/docs/#components) 来完成封装,本例中我们加入了一个滑块(slider)组件来滑动控制引导参数值(guidance scale),以及一个颜色选择器来定义目标颜色。
960
+
961
+
962
+ ```python
963
+ !pip install -q gradio # 安装 gradio 库
964
+ ```
965
+
966
+
967
+ ```python
968
+ import gradio as gr
969
+ from PIL import Image, ImageColor
970
+
971
+
972
+ # 图片生成主函数
973
+ def generate(color, guidance_loss_scale):
974
+ target_color = ImageColor.getcolor(color, "RGB") # RGB 格式的目标图片
975
+ target_color = [a / 255 for a in target_color] # 归一化至 (0, 1)
976
+ x = torch.randn(1, 3, 256, 256).to(device)
977
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
978
+ model_input = scheduler.scale_model_input(x, t)
979
+ with torch.no_grad():
980
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
981
+ x = x.detach().requires_grad_()
982
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
983
+ loss = color_loss(x0, target_color) * guidance_loss_scale
984
+ cond_grad = -torch.autograd.grad(loss, x)[0]
985
+ x = x.detach() + cond_grad
986
+ x = scheduler.step(noise_pred, t, x).prev_sample
987
+ grid = torchvision.utils.make_grid(x, nrow=4)
988
+ im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5
989
+ im = Image.fromarray(np.array(im * 255).astype(np.uint8))
990
+ im.save("test.jpeg")
991
+ return im
992
+
993
+
994
+ # 查看 gradio 文档来选择输入和输出的可用参数类型
995
+ inputs = [
996
+ gr.ColorPicker(label="color", value="55FFAA"), # 这里可以添加任何输入
997
+ gr.Slider(label="guidance_scale", minimum=0, maximum=30, value=3),
998
+ ]
999
+ outputs = gr.Image(label="result")
1000
+
1001
+ # 定义接口
1002
+ demo = gr.Interface(
1003
+ fn=generate,
1004
+ inputs=inputs,
1005
+ outputs=outputs,
1006
+ examples=[
1007
+ ["#BB2266", 3],
1008
+ ["#44CCAA", 5], # 这里可以添加一些示例
1009
+ ],
1010
+ )
1011
+ demo.launch(debug=True) # 设置 debug=True 以查看程序输出和报错
1012
+ ```
1013
+
1014
+ 当然你也可以制作更复杂的接口,设计你喜欢的风格,以及提供一些默认的输入。这里我们只做基本功能的演示。
1015
+
1016
+ 在 🤗 Spaces 上的演示 demo 默认使用 CPU 运行,所以在你把你的应用程序移植到 🤗 Spaces 之前,最好先在 Colab 上把接口雏形(如上所示)制作完成。然后你需要在 🤗 上创建一个 space,配置好 `requirements.txt`(列出运行程序所需的库),然后把所有运行代码都放在一个名为 `app.py` 的文件里,这个文件就是用来定义相关函数和接口的。
1017
+
1018
+ ![Screenshot from 2022-12-11 10-28-26.png]()
1019
+
1020
+ 当然还有一种简单的方式,你也可以直接复制一个 space。可以点击 [这里](https://huggingface.co/spaces/johnowhitaker/color-guided-wikiart-diffusion) 查看我的 demo(上面的示例),然后点击 “Duplicate this Space” 将我的代码作为模板,用于你后续修改代码来添加你自己的模型和引导函数。
1021
+
1022
+ 在设置选项中,你也可以配置你的 space 的运行环境,让它在更高性能的硬件上运行(会按小时收费)。如果你做出了一些很惊艳的东西并且想在更高性能的硬件上分享和运行,但是囊中羞涩?你可以在 Discord 上告诉我们,看我们能不能提供点帮助。
1023
+
1024
+ ## 总结和下一步工作
1025
+
1026
+ 本章节介绍了非常多的内容。让我们回顾一下核心要点:
1027
+ - 载入一个现有模型并用不同的调度器(scheduler)去采样其实很简单
1028
+ - 微调(fine-tuning)看起来很像从头训练一个模型,唯一不同的是我们用已有的模型做初始化,期望能快点得到更好的效果
1029
+ - 要在大尺寸图片上微调大模型,我们可以用诸如梯度累加(gradient accumulation)的技巧来应对训练硬件条件对 batch size 的限制
1030
+ - 记录采样图片的日志信息对微调很重要,相反,loss 曲线显示的信息可能不太有用
1031
+ - 引导(guidance)可以基于引导损失函数,来实现对非条件扩散模型在生成图片时施加控制。具体做法是:每一次迭代,计算 loss 对噪声 x 的梯度,先根据梯度信息更新 x,再进入下一次迭代
1032
+ - 用 CLIP 引导的模型可以用文字描述来控制非条件扩散模型
1033
+
1034
+
1035
+ 如果你想在实践中运用这些知识,你还可以做这些:
1036
+ - 微调你自己的模型并把它上传到 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) 数据集,或者其他你自己的数据集),然后运行上文的代码或样例脚本程序。
1037
+ - 用你的微调过的模型尝试一下加入引导,你可以用上文中举例的引导函数(颜色损失或 CLIP),也可以自己创造一个。
1038
+ - 使用 Gradio 分享你的 demo,你可以将 [space 样例](https://huggingface.co/spaces/johnowhitaker/color-guided-wikiart-diffusion) 中的模型替换为你自己的模型,也可以创建你专属的有功能更齐全的 space。
1039
+
1040
+ 我们期待在 Discord、Twitter 或其它地方看到你的作品!🤗
1041
+
1042
+
1043
+ ```python
1044
+
1045
+ ```
markdown/unit2/02_class_conditioned_diffusion_model_example_CN_Beta.md ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 创建一个类别条件扩散模型
2
+
3
+ 在本章节中,我们将介绍一种给扩散模型加入条件信息的方法。具体来说,我们将接着第一单元中 [从头训练扩散模型](../unit1/02_diffusion_models_from_scratch_CN.ipynb) 的示例,在 MNIST 上训练一个类别-条件扩散模型,这样我们在推理的时候就能具体指定想要生成那个数字图片。
4
+
5
+ 就像本单元介绍中说的那样,给扩散模型添加额外条件信息的方法有很多种,而这只是其中一种,用它做示例纯粹是因为它比较简单。就像第一单元中 “从头训练扩散模型” 部分一样,本节内容只是为了解释说明的目的,你也可以选择跳过。
6
+
7
+ ## 配置和数据准备
8
+
9
+
10
+ ```python
11
+ !pip install -q diffusers
12
+ ```
13
+
14
+  |████████████████████████████████| 503 kB 7.2 MB/s
15
+  |████████████████████████████████| 182 kB 51.3 MB/s
16
+ [?25h
17
+
18
+
19
+ ```python
20
+ import torch
21
+ import torchvision
22
+ from torch import nn
23
+ from torch.nn import functional as F
24
+ from torch.utils.data import DataLoader
25
+ from diffusers import DDPMScheduler, UNet2DModel
26
+ from matplotlib import pyplot as plt
27
+ from tqdm.auto import tqdm
28
+
29
+ device = 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu'
30
+ print(f'Using device: {device}')
31
+ ```
32
+
33
+ Using device: cuda
34
+
35
+
36
+
37
+ ```python
38
+ # 加载数据集
39
+ dataset = torchvision.datasets.MNIST(root="mnist/", train=True, download=True, transform=torchvision.transforms.ToTensor())
40
+
41
+ # 输入 dataloader (这里 batch_size 设为8,你也可以视情况修改)
42
+ train_dataloader = DataLoader(dataset, batch_size=8, shuffle=True)
43
+
44
+ # 抽样可视化图片
45
+ x, y = next(iter(train_dataloader))
46
+ print('Input shape:', x.shape)
47
+ print('Labels:', y)
48
+ plt.imshow(torchvision.utils.make_grid(x)[0], cmap='Greys');
49
+ ```
50
+
51
+ Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
52
+ Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to mnist/MNIST/raw/train-images-idx3-ubyte.gz
53
+
54
+
55
+
56
+ 0%| | 0/9912422 [00:00<?, ?it/s]
57
+
58
+
59
+ Extracting mnist/MNIST/raw/train-images-idx3-ubyte.gz to mnist/MNIST/raw
60
+
61
+ Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
62
+ Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to mnist/MNIST/raw/train-labels-idx1-ubyte.gz
63
+
64
+
65
+
66
+ 0%| | 0/28881 [00:00<?, ?it/s]
67
+
68
+
69
+ Extracting mnist/MNIST/raw/train-labels-idx1-ubyte.gz to mnist/MNIST/raw
70
+
71
+ Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
72
+ Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to mnist/MNIST/raw/t10k-images-idx3-ubyte.gz
73
+
74
+
75
+
76
+ 0%| | 0/1648877 [00:00<?, ?it/s]
77
+
78
+
79
+ Extracting mnist/MNIST/raw/t10k-images-idx3-ubyte.gz to mnist/MNIST/raw
80
+
81
+ Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
82
+ Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to mnist/MNIST/raw/t10k-labels-idx1-ubyte.gz
83
+
84
+
85
+
86
+ 0%| | 0/4542 [00:00<?, ?it/s]
87
+
88
+
89
+ Extracting mnist/MNIST/raw/t10k-labels-idx1-ubyte.gz to mnist/MNIST/raw
90
+
91
+ Input shape: torch.Size([8, 1, 28, 28])
92
+ Labels: tensor([8, 1, 5, 9, 7, 6, 2, 2])
93
+
94
+
95
+
96
+
97
+ ![png](02_class_conditioned_diffusion_model_example_CN_files/02_class_conditioned_diffusion_model_example_CN_4_9.png)
98
+
99
+
100
+
101
+ ## 创建 类别-条件 UNet
102
+
103
+ 我们输入类别条件的方法流程是:
104
+ - 创建一个标准的 `UNet2DModel`,增加额外的输入通道
105
+ - 通过嵌入(embedding)层把类别标签映射到一个 `(class_emb_size)` 形状的向量
106
+ - 把嵌入向量填充到额外的输入通道,即和原有的输入拼接起来,代码为: `net_input = torch.cat((x, class_cond), 1)`
107
+ - 将拼接的 `net_input` (共有 `class_emb_size+1` 个通道) 输入给 UNet 从而得到最终预测输出
108
+
109
+ 在本例中,我把 class_emb_size 设为 4,不过这个值完全可以修改为任意值,你可以尝试把它设为 1(来看看这有没有用),一直到 10(正好是类别总数),或者把 nn.Embedding 嵌入的向量直接换成简单的类别独热编码(one-hot encoding)。
110
+
111
+ 具体实现代码如下:
112
+
113
+
114
+ ```python
115
+ class ClassConditionedUnet(nn.Module):
116
+ def __init__(self, num_classes=10, class_emb_size=4):
117
+ super().__init__()
118
+
119
+ # embedding 层会把类别标签映射为 class_emb_size 形状的向量
120
+ self.class_emb = nn.Embedding(num_classes, class_emb_size)
121
+
122
+ # Self.model 是一个非条件 UNet,因此并不包含额外的通道,无法拼接条件信息(类别 embedding)
123
+ self.model = UNet2DModel(
124
+ sample_size=28, # 目标图片分辨率
125
+ in_channels=1 + class_emb_size, # 额外的通道数
126
+ out_channels=1, # 输出通道数
127
+ layers_per_block=2, # UNet Block 内的 ResNet 层数
128
+ block_out_channels=(32, 64, 64),
129
+ down_block_types=(
130
+ "DownBlock2D", # 常规 ResNet 下采样 block
131
+ "AttnDownBlock2D", # 带有 2 维自注意力机制的 ResNet 下采样 block
132
+ "AttnDownBlock2D",
133
+ ),
134
+ up_block_types=(
135
+ "AttnUpBlock2D",
136
+ "AttnUpBlock2D", # 带有 2 维自注意力机制的 ResNet 上采样 block
137
+ "UpBlock2D", # 常规 ResNet 上采样 block
138
+ ),
139
+ )
140
+
141
+ # 前向计算函数接收额外的类别参数
142
+ def forward(self, x, t, class_labels):
143
+ # x 的形状:
144
+ bs, ch, w, h = x.shape
145
+
146
+ # 映射类别条件信息与图片信息融合需要形状匹配
147
+ class_cond = self.class_emb(class_labels) # 映射类别条件信息到目标形状
148
+ class_cond = class_cond.view(bs, class_cond.shape[1], 1, 1).expand(bs, class_cond.shape[1], w, h)
149
+ # x 形状为 (bs, 1, 28, 28), class_cond 现在的形状为 (bs, 4, 28, 28)
150
+
151
+ # 沿着维度为 1(从 0 开始)轴拼接 x 和 class_cond
152
+ net_input = torch.cat((x, class_cond), 1) # (bs, 5, 28, 28)
153
+
154
+ # 将 net_input 和 时间步信息一同送入模型预测图片输出
155
+ return self.model(net_input, t).sample # (bs, 1, 28, 28)
156
+ ```
157
+
158
+ 如果你对哪个形或状变换理解的不是很明白,可以在代码中加入 print 来打印相关形状,从而检查它们是否符合你的预期。这里我把一些中间变量的形状都以注释的形式展示了,希望能帮助你理解的透彻点。
159
+
160
+ ## 训练和采样
161
+
162
+ 跟本书前面预测模型输出使用的 `prediction = unet(x, t)` 不同,现在我们增加第 3 个参数,需要使用 `prediction = unet(x, t, y)`。在推理阶段,我们可以输入任何标签,如果一切正常,模型就会输出与之匹配的图片。这里的参数 `y` 就是 MNIST 中的数字标签,参数值的范围为 0 到 9。
163
+
164
+ 训练循环也跟 [第一单元的例子](../unit1/02_diffusion_models_from_scratch_CN.ipynb) 非常相似,这里模型预测的是噪声残差(而不是第一单元去噪图片),以此来匹配 DDPMScheduler 预设的目标形式,在训练阶段去噪和推理阶段的采样需要保持一致。实际训练过程需要一段时间(如何加速训练也是个有趣的课题),但这里我们只是讲解思路,你也可以跳过需要运行代码块的部分。
165
+
166
+
167
+ ```python
168
+ # 创建一个 DDPMScheduler 实例
169
+ noise_scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule='squaredcos_cap_v2')
170
+ ```
171
+
172
+
173
+ ```python
174
+ #@markdown 训练循环 (10 Epochs):
175
+
176
+ # 重定义 dataloader,设置 batch_size (可以比先前 demo 中大得多)
177
+ train_dataloader = DataLoader(dataset, batch_size=128, shuffle=True)
178
+
179
+ # 思考一下设置多少 epoch 比较好?
180
+ n_epochs = 10
181
+
182
+ # 网络架构
183
+ net = ClassConditionedUnet().to(device)
184
+
185
+ # 损失函数
186
+ loss_fn = nn.MSELoss()
187
+
188
+ # 优化器
189
+ opt = torch.optim.Adam(net.parameters(), lr=1e-3)
190
+
191
+ # 记录 loss 以便后续分析 loss 曲线
192
+ losses = []
193
+
194
+ # 训练循环
195
+ for epoch in range(n_epochs):
196
+ for x, y in tqdm(train_dataloader):
197
+
198
+ # 训练数据准备
199
+ x = x.to(device) * 2 - 1 # 转移数据至 GPU 并归一化 (-1, 1)
200
+ y = y.to(device)
201
+ noise = torch.randn_like(x)
202
+ timesteps = torch.randint(0, 999, (x.shape[0],)).long().to(device)
203
+ noisy_x = noise_scheduler.add_noise(x, noise, timesteps)
204
+
205
+ # 获取模型预测输出
206
+ pred = net(noisy_x, timesteps, y) # 注意传入类别标签 y
207
+
208
+ # 计算 loss
209
+ loss = loss_fn(pred, noise) # 度量预测和噪声的相似程度
210
+
211
+ # 反向传播,更新参数
212
+ opt.zero_grad()
213
+ loss.backward()
214
+ opt.step()
215
+
216
+ # 记录 loss
217
+ losses.append(loss.item())
218
+
219
+ # 每 100 个样本打印一次平均 loss,不时查看一下训练进展情况
220
+ avg_loss = sum(losses[-100:])/100
221
+ print(f'Finished epoch {epoch}. Average of the last 100 loss values: {avg_loss:05f}')
222
+
223
+ # 可视化 loss 曲线
224
+ plt.plot(losses)
225
+ ```
226
+
227
+
228
+ 0%| | 0/469 [00:00<?, ?it/s]
229
+
230
+
231
+ Finished epoch 0. Average of the last 100 loss values: 0.052451
232
+
233
+
234
+
235
+ 0%| | 0/469 [00:00<?, ?it/s]
236
+
237
+
238
+ Finished epoch 1. Average of the last 100 loss values: 0.045999
239
+
240
+
241
+
242
+ 0%| | 0/469 [00:00<?, ?it/s]
243
+
244
+
245
+ Finished epoch 2. Average of the last 100 loss values: 0.043344
246
+
247
+
248
+
249
+ 0%| | 0/469 [00:00<?, ?it/s]
250
+
251
+
252
+ Finished epoch 3. Average of the last 100 loss values: 0.042347
253
+
254
+
255
+
256
+ 0%| | 0/469 [00:00<?, ?it/s]
257
+
258
+
259
+ Finished epoch 4. Average of the last 100 loss values: 0.041174
260
+
261
+
262
+
263
+ 0%| | 0/469 [00:00<?, ?it/s]
264
+
265
+
266
+ Finished epoch 5. Average of the last 100 loss values: 0.040736
267
+
268
+
269
+
270
+ 0%| | 0/469 [00:00<?, ?it/s]
271
+
272
+
273
+ Finished epoch 6. Average of the last 100 loss values: 0.040386
274
+
275
+
276
+
277
+ 0%| | 0/469 [00:00<?, ?it/s]
278
+
279
+
280
+ Finished epoch 7. Average of the last 100 loss values: 0.039372
281
+
282
+
283
+
284
+ 0%| | 0/469 [00:00<?, ?it/s]
285
+
286
+
287
+ Finished epoch 8. Average of the last 100 loss values: 0.039056
288
+
289
+
290
+
291
+ 0%| | 0/469 [00:00<?, ?it/s]
292
+
293
+
294
+ Finished epoch 9. Average of the last 100 loss values: 0.039024
295
+
296
+
297
+
298
+
299
+
300
+ [<matplotlib.lines.Line2D>]
301
+
302
+
303
+
304
+
305
+
306
+ ![png](02_class_conditioned_diffusion_model_example_CN_files/02_class_conditioned_diffusion_model_example_CN_10_21.png)
307
+
308
+
309
+
310
+ 训练完成后,我们就可以输入不同的标签条件,来生成图片看看效果了:
311
+
312
+
313
+ ```python
314
+ #@markdown 生成不同数字类别图片:
315
+
316
+ # 随机初始化噪声,以及类别标签
317
+ x = torch.randn(80, 1, 28, 28).to(device)
318
+ y = torch.tensor([[i]*8 for i in range(10)]).flatten().to(device)
319
+
320
+ # 采样循环
321
+ for i, t in tqdm(enumerate(noise_scheduler.timesteps)):
322
+
323
+ # 计算模型输出
324
+ with torch.no_grad():
325
+ residual = net(x, t, y) # 再次提醒传入标签 y
326
+
327
+ # 迭代去噪图片
328
+ x = noise_scheduler.step(residual, t, x).prev_sample
329
+
330
+ # 可视化最终图片
331
+ fig, ax = plt.subplots(1, 1, figsize=(12, 12))
332
+ ax.imshow(torchvision.utils.make_grid(x.detach().cpu().clip(-1, 1), nrow=8)[0], cmap='Greys')
333
+ ```
334
+
335
+
336
+ 0it [00:00, ?it/s]
337
+
338
+
339
+
340
+
341
+
342
+ <matplotlib.image.AxesImage>
343
+
344
+
345
+
346
+
347
+
348
+ ![png](02_class_conditioned_diffusion_model_example_CN_files/02_class_conditioned_diffusion_model_example_CN_12_2.png)
349
+
350
+
351
+
352
+ 就是这么简单!我们现在就能以类别条件控制生成图片了。
353
+
354
+ 希望你喜欢这个样例。一如既往地,如果你有问题,你随时可以在 Discord 上留言。
355
+
356
+
357
+ ```python
358
+ # 练习(选做):用同样方法在 FashionMNIST 数据集上试试,顺带调整学习率、batch size 和训练轮次(epochs)等参数试试。
359
+ # 你能用比上述样例更少的训练时间得到些看起来不错的图片吗?
360
+ ```