作者: András Béres
创建日期 2022/06/24
上次修改日期 2022/06/24
描述:使用基于隐式模型的去噪扩散生成花朵图像。
最近,基于去噪的扩散模型,包括基于分数的生成模型,作为一种强大的生成模型类别而受到欢迎,它可以在图像合成质量方面与甚至生成对抗网络 (GAN)相媲美。它们倾向于生成更多样化的样本,同时训练稳定且易于扩展。最近的大型扩散模型,如DALL-E 2 和Imagen,展示了令人难以置信的文本到图像生成能力。然而,它们的缺点之一是,从它们中采样速度较慢,因为它们需要多次前向传递才能生成图像。
扩散指的是逐步将结构化信号(图像)转换为噪声的过程。通过模拟扩散,我们可以从训练图像生成噪声图像,并可以训练神经网络尝试对其进行去噪。使用训练好的网络,我们可以模拟扩散的反过程,即反向扩散,它是图像从噪声中出现的过程。
一句话总结:扩散模型经过训练可以对噪声图像进行去噪,并且可以通过迭代去噪纯噪声来生成图像。
此代码示例旨在成为扩散模型的一个最小但功能完整的(具有生成质量指标)实现,具有适度的计算需求和合理的性能。我的实现选择和超参数调整都是为了实现这些目标。
由于目前扩散模型的文献在数学上相当复杂,具有多种理论框架(分数匹配、微分方程、马尔可夫链),有时甚至存在冲突的符号(参见附录 C.2),因此尝试理解它们可能会让人望而生畏。在本示例中,我对这些模型的看法是,它们学习将噪声图像分离成其图像和高斯噪声分量。
在本示例中,我努力将所有冗长的数学表达式分解成易于理解的部分,并为所有变量提供了解释性名称。我还包含了许多指向相关文献的链接,以帮助感兴趣的读者更深入地了解该主题,希望此代码示例能成为学习扩散模型的从业人员的良好起点。
在接下来的部分中,我们将实现基于隐式模型的去噪扩散 (DDIM)的连续时间版本,并使用确定性采样。
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import math
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
import keras
from keras import layers
from keras import ops
# data
dataset_name = "oxford_flowers102"
dataset_repetitions = 5
num_epochs = 1 # train for at least 50 epochs for good results
image_size = 64
# KID = Kernel Inception Distance, see related section
kid_image_size = 75
kid_diffusion_steps = 5
plot_diffusion_steps = 20
# sampling
min_signal_rate = 0.02
max_signal_rate = 0.95
# architecture
embedding_dims = 32
embedding_max_frequency = 1000.0
widths = [32, 64, 96, 128]
block_depth = 2
# optimization
batch_size = 64
ema = 0.999
learning_rate = 1e-3
weight_decay = 1e-4
我们将使用牛津花卉 102数据集生成花朵图像,这是一个包含大约 8,000 张图像的多样化自然数据集。不幸的是,官方分割不平衡,因为大多数图像都包含在测试分割中。我们使用Tensorflow 数据集切片 API创建新的分割(80% 训练,20% 验证)。我们应用中心裁剪作为预处理,并多次重复数据集(原因在下一节中给出)。
def preprocess_image(data):
# center crop image
height = ops.shape(data["image"])[0]
width = ops.shape(data["image"])[1]
crop_size = ops.minimum(height, width)
image = tf.image.crop_to_bounding_box(
data["image"],
(height - crop_size) // 2,
(width - crop_size) // 2,
crop_size,
crop_size,
)
# resize and clip
# for image downsampling it is important to turn on antialiasing
image = tf.image.resize(image, size=[image_size, image_size], antialias=True)
return ops.clip(image / 255.0, 0.0, 1.0)
def prepare_dataset(split):
# the validation dataset is shuffled as well, because data order matters
# for the KID estimation
return (
tfds.load(dataset_name, split=split, shuffle_files=True)
.map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
.cache()
.repeat(dataset_repetitions)
.shuffle(10 * batch_size)
.batch(batch_size, drop_remainder=True)
.prefetch(buffer_size=tf.data.AUTOTUNE)
)
# load dataset
train_dataset = prepare_dataset("train[:80%]+validation[:80%]+test[:80%]")
val_dataset = prepare_dataset("train[80%:]+validation[80%:]+test[80%:]")
核感知距离 (KID) 是一种图像质量指标,被提议作为流行的弗雷谢感知距离 (FID)的替代品。我更喜欢 KID 而不是 FID,因为它实现更简单,可以逐批估计,并且计算量更轻。更多详细信息请点击此处。
在本示例中,图像以 Inception 网络的最小可能分辨率(75x75 而不是 299x299)进行评估,并且出于计算效率的考虑,指标仅在验证集上测量。出于同样的原因,我们还将评估时的采样步数限制为 5。
由于数据集相对较小,因此我们每个时期都会多次遍历训练和验证分割,因为 KID 估计存在噪声且计算密集,因此我们希望仅在多次迭代后进行评估,但需要进行多次迭代。
@keras.saving.register_keras_serializable()
class KID(keras.metrics.Metric):
def __init__(self, name, **kwargs):
super().__init__(name=name, **kwargs)
# KID is estimated per batch and is averaged across batches
self.kid_tracker = keras.metrics.Mean(name="kid_tracker")
# a pretrained InceptionV3 is used without its classification layer
# transform the pixel values to the 0-255 range, then use the same
# preprocessing as during pretraining
self.encoder = keras.Sequential(
[
keras.Input(shape=(image_size, image_size, 3)),
layers.Rescaling(255.0),
layers.Resizing(height=kid_image_size, width=kid_image_size),
layers.Lambda(keras.applications.inception_v3.preprocess_input),
keras.applications.InceptionV3(
include_top=False,
input_shape=(kid_image_size, kid_image_size, 3),
weights="imagenet",
),
layers.GlobalAveragePooling2D(),
],
name="inception_encoder",
)
def polynomial_kernel(self, features_1, features_2):
feature_dimensions = ops.cast(ops.shape(features_1)[1], dtype="float32")
return (
features_1 @ ops.transpose(features_2) / feature_dimensions + 1.0
) ** 3.0
def update_state(self, real_images, generated_images, sample_weight=None):
real_features = self.encoder(real_images, training=False)
generated_features = self.encoder(generated_images, training=False)
# compute polynomial kernels using the two sets of features
kernel_real = self.polynomial_kernel(real_features, real_features)
kernel_generated = self.polynomial_kernel(
generated_features, generated_features
)
kernel_cross = self.polynomial_kernel(real_features, generated_features)
# estimate the squared maximum mean discrepancy using the average kernel values
batch_size = real_features.shape[0]
batch_size_f = ops.cast(batch_size, dtype="float32")
mean_kernel_real = ops.sum(kernel_real * (1.0 - ops.eye(batch_size))) / (
batch_size_f * (batch_size_f - 1.0)
)
mean_kernel_generated = ops.sum(
kernel_generated * (1.0 - ops.eye(batch_size))
) / (batch_size_f * (batch_size_f - 1.0))
mean_kernel_cross = ops.mean(kernel_cross)
kid = mean_kernel_real + mean_kernel_generated - 2.0 * mean_kernel_cross
# update the average KID estimate
self.kid_tracker.update_state(kid)
def result(self):
return self.kid_tracker.result()
def reset_state(self):
self.kid_tracker.reset_state()
这里我们指定我们将用于去噪的神经网络的架构。我们构建了一个U-Net,其输入和输出维度相同。U-Net 是一种流行的语义分割架构,其主要思想是它逐步对输入图像进行下采样,然后进行上采样,并在具有相同分辨率的层之间添加跳跃连接。这些有助于梯度流动并避免引入表示瓶颈,这与通常的自动编码器不同。基于此,可以将扩散模型视为没有瓶颈的去噪自动编码器。
该网络有两个输入,即噪声图像及其噪声分量的方差。后者是必需的,因为对信号进行去噪需要在不同噪声水平下执行不同的操作。我们使用正弦嵌入变换噪声方差,类似于在transformer和NeRF中使用的位置编码。这有助于网络对噪声水平高度敏感,这对获得良好的性能至关重要。我们使用Lambda 层实现正弦嵌入。
其他一些注意事项
@keras.saving.register_keras_serializable()
def sinusoidal_embedding(x):
embedding_min_frequency = 1.0
frequencies = ops.exp(
ops.linspace(
ops.log(embedding_min_frequency),
ops.log(embedding_max_frequency),
embedding_dims // 2,
)
)
angular_speeds = ops.cast(2.0 * math.pi * frequencies, "float32")
embeddings = ops.concatenate(
[ops.sin(angular_speeds * x), ops.cos(angular_speeds * x)], axis=3
)
return embeddings
def ResidualBlock(width):
def apply(x):
input_width = x.shape[3]
if input_width == width:
residual = x
else:
residual = layers.Conv2D(width, kernel_size=1)(x)
x = layers.BatchNormalization(center=False, scale=False)(x)
x = layers.Conv2D(width, kernel_size=3, padding="same", activation="swish")(x)
x = layers.Conv2D(width, kernel_size=3, padding="same")(x)
x = layers.Add()([x, residual])
return x
return apply
def DownBlock(width, block_depth):
def apply(x):
x, skips = x
for _ in range(block_depth):
x = ResidualBlock(width)(x)
skips.append(x)
x = layers.AveragePooling2D(pool_size=2)(x)
return x
return apply
def UpBlock(width, block_depth):
def apply(x):
x, skips = x
x = layers.UpSampling2D(size=2, interpolation="bilinear")(x)
for _ in range(block_depth):
x = layers.Concatenate()([x, skips.pop()])
x = ResidualBlock(width)(x)
return x
return apply
def get_network(image_size, widths, block_depth):
noisy_images = keras.Input(shape=(image_size, image_size, 3))
noise_variances = keras.Input(shape=(1, 1, 1))
e = layers.Lambda(sinusoidal_embedding, output_shape=(1, 1, 32))(noise_variances)
e = layers.UpSampling2D(size=image_size, interpolation="nearest")(e)
x = layers.Conv2D(widths[0], kernel_size=1)(noisy_images)
x = layers.Concatenate()([x, e])
skips = []
for width in widths[:-1]:
x = DownBlock(width, block_depth)([x, skips])
for _ in range(block_depth):
x = ResidualBlock(widths[-1])(x)
for width in reversed(widths[:-1]):
x = UpBlock(width, block_depth)([x, skips])
x = layers.Conv2D(3, kernel_size=1, kernel_initializer="zeros")(x)
return keras.Model([noisy_images, noise_variances], x, name="residual_unet")
这展示了函数式 API 的强大功能。请注意,我们如何在 80 行代码中构建了一个具有跳跃连接、残差块、多个输入和正弦嵌入的相对复杂的 U-Net!
假设一个扩散过程从时间 = 0 开始,到时间 = 1 结束。此变量将称为扩散时间,可以是离散的(在扩散模型中常见)或连续的(在基于分数的模型中常见)。我选择后者,以便可以在推理时更改采样步数。
我们需要一个函数,它可以在扩散过程的每个点告诉我们与实际扩散时间相对应的高斯噪声图像的噪声水平和信号水平。这将被称为扩散调度(参见 diffusion_schedule()
)。
此调度输出两个量:noise_rate
和 signal_rate
(分别对应于 DDIM 论文中的 sqrt(1 - alpha) 和 sqrt(alpha))。我们通过对其相应速率加权随机噪声和训练图像并将其加在一起生成噪声图像。
由于(标准正态)随机噪声和(归一化)图像都具有零均值和单位方差,因此噪声率和信号率可以解释为其在噪声图像中分量的标准差,而其率的平方可以解释为其方差(或在信号处理意义上的功率)。这些速率将始终设置为其平方和为 1,这意味着噪声图像将始终具有单位方差,就像其未缩放的分量一样。
我们将使用文献中常用的余弦调度(第 3.2 节)的简化连续版本。此调度是对称的,在扩散过程的开始和结束时缓慢,并且它还具有很好的几何解释,使用单位圆的三角特性
降噪扩散模型的训练过程(参见 train_step()
和 denoise()
)如下:我们统一地采样随机扩散时间,并根据扩散时间以随机高斯噪声的速率混合训练图像。然后,我们训练模型将噪声图像分离成其两个分量。
通常,神经网络被训练用于预测未缩放的噪声分量,可以使用信号和噪声率从该分量计算预测的图像分量。理论上应该使用逐像素均方误差,但是我建议改为使用平均绝对误差(类似于此实现),这在该数据集上产生了更好的结果。
在采样(参见 reverse_diffusion()
)时,在每个步骤中,我们取噪声图像的上一步估计,并使用我们的网络将其分离成图像和噪声。然后,我们使用下一步的信号和噪声率重新组合这些分量。
虽然DDIM 的公式 12中显示了类似的观点,但我认为上述采样公式的解释并不广为人知。
此示例仅实现了来自 DDIM 的确定性采样过程,这对应于论文中的eta = 0。也可以使用随机采样(在这种情况下,模型成为降噪扩散概率模型 (DDPM)),其中预测噪声的一部分被相同或更大的随机噪声替换(参见公式 16 及其以下内容)。
随机采样可以在不重新训练网络的情况下使用(因为这两个模型的训练方式相同),并且可以提高样本质量,而另一方面通常需要更多采样步骤。
@keras.saving.register_keras_serializable()
class DiffusionModel(keras.Model):
def __init__(self, image_size, widths, block_depth):
super().__init__()
self.normalizer = layers.Normalization()
self.network = get_network(image_size, widths, block_depth)
self.ema_network = keras.models.clone_model(self.network)
def compile(self, **kwargs):
super().compile(**kwargs)
self.noise_loss_tracker = keras.metrics.Mean(name="n_loss")
self.image_loss_tracker = keras.metrics.Mean(name="i_loss")
self.kid = KID(name="kid")
@property
def metrics(self):
return [self.noise_loss_tracker, self.image_loss_tracker, self.kid]
def denormalize(self, images):
# convert the pixel values back to 0-1 range
images = self.normalizer.mean + images * self.normalizer.variance**0.5
return ops.clip(images, 0.0, 1.0)
def diffusion_schedule(self, diffusion_times):
# diffusion times -> angles
start_angle = ops.cast(ops.arccos(max_signal_rate), "float32")
end_angle = ops.cast(ops.arccos(min_signal_rate), "float32")
diffusion_angles = start_angle + diffusion_times * (end_angle - start_angle)
# angles -> signal and noise rates
signal_rates = ops.cos(diffusion_angles)
noise_rates = ops.sin(diffusion_angles)
# note that their squared sum is always: sin^2(x) + cos^2(x) = 1
return noise_rates, signal_rates
def denoise(self, noisy_images, noise_rates, signal_rates, training):
# the exponential moving average weights are used at evaluation
if training:
network = self.network
else:
network = self.ema_network
# predict noise component and calculate the image component using it
pred_noises = network([noisy_images, noise_rates**2], training=training)
pred_images = (noisy_images - noise_rates * pred_noises) / signal_rates
return pred_noises, pred_images
def reverse_diffusion(self, initial_noise, diffusion_steps):
# reverse diffusion = sampling
num_images = initial_noise.shape[0]
step_size = 1.0 / diffusion_steps
# important line:
# at the first sampling step, the "noisy image" is pure noise
# but its signal rate is assumed to be nonzero (min_signal_rate)
next_noisy_images = initial_noise
for step in range(diffusion_steps):
noisy_images = next_noisy_images
# separate the current noisy image to its components
diffusion_times = ops.ones((num_images, 1, 1, 1)) - step * step_size
noise_rates, signal_rates = self.diffusion_schedule(diffusion_times)
pred_noises, pred_images = self.denoise(
noisy_images, noise_rates, signal_rates, training=False
)
# network used in eval mode
# remix the predicted components using the next signal and noise rates
next_diffusion_times = diffusion_times - step_size
next_noise_rates, next_signal_rates = self.diffusion_schedule(
next_diffusion_times
)
next_noisy_images = (
next_signal_rates * pred_images + next_noise_rates * pred_noises
)
# this new noisy image will be used in the next step
return pred_images
def generate(self, num_images, diffusion_steps):
# noise -> images -> denormalized images
initial_noise = keras.random.normal(
shape=(num_images, image_size, image_size, 3)
)
generated_images = self.reverse_diffusion(initial_noise, diffusion_steps)
generated_images = self.denormalize(generated_images)
return generated_images
def train_step(self, images):
# normalize images to have standard deviation of 1, like the noises
images = self.normalizer(images, training=True)
noises = keras.random.normal(shape=(batch_size, image_size, image_size, 3))
# sample uniform random diffusion times
diffusion_times = keras.random.uniform(
shape=(batch_size, 1, 1, 1), minval=0.0, maxval=1.0
)
noise_rates, signal_rates = self.diffusion_schedule(diffusion_times)
# mix the images with noises accordingly
noisy_images = signal_rates * images + noise_rates * noises
with tf.GradientTape() as tape:
# train the network to separate noisy images to their components
pred_noises, pred_images = self.denoise(
noisy_images, noise_rates, signal_rates, training=True
)
noise_loss = self.loss(noises, pred_noises) # used for training
image_loss = self.loss(images, pred_images) # only used as metric
gradients = tape.gradient(noise_loss, self.network.trainable_weights)
self.optimizer.apply_gradients(zip(gradients, self.network.trainable_weights))
self.noise_loss_tracker.update_state(noise_loss)
self.image_loss_tracker.update_state(image_loss)
# track the exponential moving averages of weights
for weight, ema_weight in zip(self.network.weights, self.ema_network.weights):
ema_weight.assign(ema * ema_weight + (1 - ema) * weight)
# KID is not measured during the training phase for computational efficiency
return {m.name: m.result() for m in self.metrics[:-1]}
def test_step(self, images):
# normalize images to have standard deviation of 1, like the noises
images = self.normalizer(images, training=False)
noises = keras.random.normal(shape=(batch_size, image_size, image_size, 3))
# sample uniform random diffusion times
diffusion_times = keras.random.uniform(
shape=(batch_size, 1, 1, 1), minval=0.0, maxval=1.0
)
noise_rates, signal_rates = self.diffusion_schedule(diffusion_times)
# mix the images with noises accordingly
noisy_images = signal_rates * images + noise_rates * noises
# use the network to separate noisy images to their components
pred_noises, pred_images = self.denoise(
noisy_images, noise_rates, signal_rates, training=False
)
noise_loss = self.loss(noises, pred_noises)
image_loss = self.loss(images, pred_images)
self.image_loss_tracker.update_state(image_loss)
self.noise_loss_tracker.update_state(noise_loss)
# measure KID between real and generated images
# this is computationally demanding, kid_diffusion_steps has to be small
images = self.denormalize(images)
generated_images = self.generate(
num_images=batch_size, diffusion_steps=kid_diffusion_steps
)
self.kid.update_state(images, generated_images)
return {m.name: m.result() for m in self.metrics}
def plot_images(self, epoch=None, logs=None, num_rows=3, num_cols=6):
# plot random generated images for visual evaluation of generation quality
generated_images = self.generate(
num_images=num_rows * num_cols,
diffusion_steps=plot_diffusion_steps,
)
plt.figure(figsize=(num_cols * 2.0, num_rows * 2.0))
for row in range(num_rows):
for col in range(num_cols):
index = row * num_cols + col
plt.subplot(num_rows, num_cols, index + 1)
plt.imshow(generated_images[index])
plt.axis("off")
plt.tight_layout()
plt.show()
plt.close()
# create and compile the model
model = DiffusionModel(image_size, widths, block_depth)
# below tensorflow 2.9:
# pip install tensorflow_addons
# import tensorflow_addons as tfa
# optimizer=tfa.optimizers.AdamW
model.compile(
optimizer=keras.optimizers.AdamW(
learning_rate=learning_rate, weight_decay=weight_decay
),
loss=keras.losses.mean_absolute_error,
)
# pixelwise mean absolute error is used as loss
# save the best model based on the validation KID metric
checkpoint_path = "checkpoints/diffusion_model.weights.h5"
checkpoint_callback = keras.callbacks.ModelCheckpoint(
filepath=checkpoint_path,
save_weights_only=True,
monitor="val_kid",
mode="min",
save_best_only=True,
)
# calculate mean and variance of training dataset for normalization
model.normalizer.adapt(train_dataset)
# run training and plot generated images periodically
model.fit(
train_dataset,
epochs=num_epochs,
validation_data=val_dataset,
callbacks=[
keras.callbacks.LambdaCallback(on_epoch_end=model.plot_images),
checkpoint_callback,
],
)
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
87910968/87910968 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
511/511 ━━━━━━━━━━━━━━━━━━━━ 0s 48ms/step - i_loss: 0.6896 - n_loss: 0.2961
511/511 ━━━━━━━━━━━━━━━━━━━━ 110s 138ms/step - i_loss: 0.6891 - n_loss: 0.2959 - kid: 0.0000e+00 - val_i_loss: 2.5650 - val_kid: 2.0372 - val_n_loss: 0.7914
<keras.src.callbacks.history.History at 0x7f521b149870>
# load the best model and generate images
model.load_weights(checkpoint_path)
model.plot_images()
通过运行至少 50 个 epoch 的训练(在 T4 GPU 上需要 2 个小时,在 A100 GPU 上需要 30 分钟),可以使用此代码示例获得高质量的图像生成。
80 个 epoch 训练中一批图像的演变(颜色伪影是由于 GIF 压缩造成的)
使用相同初始噪声的 1 到 20 个采样步骤生成的图像
初始噪声样本之间的(球面)插值
确定性采样过程(顶部为噪声图像,底部为预测图像,40 步)
随机采样过程(顶部为噪声图像,底部为预测图像,80 步)
在准备此代码示例期间,我使用此存储库运行了许多实验。在本节中,我列出了我根据主观重要性排序的经验教训和建议。
有关 GAN 的类似列表,请查看此 Keras 教程。
如果您想更深入地了解该主题,我建议查看我在准备此代码示例时创建的此存储库,它以类似的风格实现了更广泛的功能,例如