Chapter 53
4.评估一个扩散模型 Evaluating a Diffusion Model
Notebookgpt25 cells
第四章 评估一个扩散模型
在本次实验中,我们将从之前训练的扩散模型中进行采样。
- 我们将比较 DDPM 和 DDIM 采样器的样本
- 使用条件扩散模型可视化混合样品
一、初始化
In [1]python · cell 4
python
from pathlib import Path
from types import SimpleNamespace #是一种简单的命名空间来存储和访问数据的库
import torch
import torch.nn.functional as F
import numpy as np
from utilities import * #实现DDPM、DDIM的一些库
import wandbIn [2]python · cell 5
python
#登录wb网站
wandb.login(anonymous="allow")Output
Failed to detect the name of this notebook, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable to enable code saving. [34m[1mwandb[0m: Currently logged in as: [33mxiaopan[0m. Use [1m`wandb login --relogin`[0m to force relogin
True
使用wb的账户的api key就可以链接到wb官网
设置 DDPM 噪声调度器和采样器(与扩散课程中的相同)。
- perturb_input:在时间表上相应的时间步长向输入图像添加噪声
- Sample_ddpm_context:使用 DDPM 采样器生成图像,我们将在训练期间使用此函数定期从模型中采样并查看训练进展情况
In [3]python · cell 8
python
# Wandb 参数
MODEL_ARTIFACT = "dlai-course/model-registry/SpriteGen:latest"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
config = SimpleNamespace(
# 超参数
num_samples = 30,
# ddpm 采样层参数
timesteps = 500,#采样的步长,步长越大,采样时间越长,步长和图片质量没有直接联系
beta1 = 1e-4,#采样因子
beta2 = 0.02,#采样因子
# ddim sampler hp
ddim_n = 25,
# 网络超参数
height = 16,# 16x16 image
)在上一个notebook中,我们将最佳模型保存为 wandb Artifact(我们在运行期间存储文件的方式)。 我们现在将从 wandb 加载模型并设置采样循环。
In [4]python · cell 10
python
def load_model(model_artifact_name):
"下载模型"
api = wandb.Api()
artifact = api.artifact(model_artifact_name, type="model")
model_path = Path(artifact.download())
# 从wb恢复model历史信息
producer_run = artifact.logged_by()
# 加载模型训练历史
model_weights = torch.load(model_path/"context_model.pth",
map_location="cpu")
# 创建模型
model = ContextUnet(in_channels=3,
n_feat=producer_run.config["n_feat"],
n_cfeat=producer_run.config["n_cfeat"],
height=producer_run.config["height"])
# 加载模型权重
model.load_state_dict(model_weights)
# 评估模型
model.eval()
return model.to(DEVICE)In [5]python · cell 11
python
nn_model = load_model(MODEL_ARTIFACT)Output
[34m[1mwandb[0m: 1 of 1 files downloaded.
二、采样
在diffusion过程中,模型从数据分布上采样出一个噪声,然后在去噪过程中预测这个噪声,这样就能把梯度传递到了高斯分布的均值和方差中,使得模型在预测噪声的过程中习得真实图片的分布。我们将采样并将生成的样本记录到 wandb。
In [6]python · cell 13
python
#设置 ddpm 采样器功能
_, sample_ddpm_context = setup_ddpm(config.beta1, #采样因子
config.beta2, #采样因子
config.timesteps, #时间步
DEVICE)让我们定义一组噪声和一个上下文向量作为条件。
In [7]python · cell 15
python
# Noise向量
# x_T ~ N(0, 1), 样本初始噪声
noises = torch.randn(config.num_samples, 3,
config.height, config.height).to(DEVICE)
# 用于采样的固定上下文向量,不同的样本进行扩散
ctx_vector = F.one_hot(torch.tensor([0,0,0,0,0,0, # hero
1,1,1,1,1,1, # non-hero
2,2,2,2,2,2, # food
3,3,3,3,3,3, # spell
4,4,4,4,4,4]), # side-facing
5).to(DEVICE).float()In [8]python · cell 16
python
#设置 ddpm 采样器功能
sample_ddim_context = setup_ddim(config.beta1, #采样因子
config.beta2, #采样因子
config.timesteps, #时间步
DEVICE)三、DDPM和DDIM对比:
分别使用DDPM和DDIM的方式进行扩散,对比两者的效果
In [9]python · cell 18
python
#数组来跟踪生成的绘图步骤,记录不同噪声添加过程的上下文采样结果
'''
nn_model:评估噪声、时间步、上下文关系的模型
noises:添加的高斯噪声
ctx_vector:上下文向量
'''
ddpm_samples, _ = sample_ddpm_context(nn_model, noises, ctx_vector)Output
0%| | 0/500 [00:00<?, ?it/s]
In [10]python · cell 19
python
#对于 DDIM,我们可以通过 n 参数控制步长
'''
nn_model:评估噪声、时间步、上下文关系的模型
noises:添加的高斯噪声
ctx_vector:上下文向量
'''
ddim_samples, _ = sample_ddim_context(nn_model, #评估噪声、时间步、上下文关系的模型
noises, #噪声
ctx_vector, #上下文向量
n=config.ddim_n)Output
0%| | 0/25 [00:00<?, ?it/s]
在表格上可视化 让我们创建一个 wandb.Table 来存储我们的相关数据
In [11]python · cell 21
python
table = wandb.Table(columns=["input_noise", "ddpm", "ddim", "class"])我们可以将行一一添加到表中,我们还将图像投射到 wandb.Image 中,以便我们可以在 UI 中正确渲染它们
In [12]python · cell 23
python
#分别添加DDPM和DDIM的采样结果
for noise, ddpm_s, ddim_s, c in zip(noises, #高斯噪声
ddpm_samples, #DDPM的采样结果
ddim_samples, #DDIM的采样结果
to_classes(ctx_vector)):
# 逐行添加数据到表中
table.add_data(wandb.Image(noise),
wandb.Image(ddpm_s),
wandb.Image(ddim_s),
c)In [13]python · cell 24
python
# 初始化wb
with wandb.init(project="dlai_sprite_diffusion",
job_type="samplers_battle",
config=config):
wandb.log({"samplers_table":table})Output
VBox(children=(Label(value='Waiting for wandb.init()...\r'), FloatProgress(value=0.016751898599999985, max=1.0…
<IPython.core.display.HTML object>
Tracking run with wandb version 0.15.8
<IPython.core.display.HTML object>
Run data is saved locally in
/Users/wisdom-pan/Downloads/deep_learning/projects/prompt-engineering-for-developers-1/content/Building Generative AI Applications with Gradio/wandb/run-20230816_235448-djssykjw<IPython.core.display.HTML object>
<IPython.core.display.HTML object>
View project at https://wandb.ai/xiaopan/dlai_sprite_diffusion
<IPython.core.display.HTML object>
<IPython.core.display.HTML object>
Waiting for W&B process to finish... (success).
wandb: WARNING Source type is set to 'repo' but some required information is missing from the environment. A job will not be created from this run. See https://docs.wandb.ai/guides/launch/create-job
<IPython.core.display.HTML object>
View run true-water-3 at: https://wandb.ai/xiaopan/dlai_sprite_diffusion/runs/djssykjw
Synced 5 W&B file(s), 1 media file(s), 91 artifact file(s) and 0 other file(s)
Synced 5 W&B file(s), 1 media file(s), 91 artifact file(s) and 0 other file(s)
<IPython.core.display.HTML object>
Find logs at:
./wandb/run-20230816_235448-djssykjw/logs在wb官网就能看到相关的可视化信息,分别看到DDPM和DDIM两者的扩散结果
