微信对接网站群,怎么做抽奖网站,phpwind 做企业网站,网络营销做得好的企业小伙伴们好#xff0c;咱们今天演绎一个使用KerasCV的StableDiffusion模型生成新的图像的示例。
考虑计算机性能的因素#xff0c;这次咱们在Colab上进行#xff0c;Colab您可以理解为在线版的Jupyter Notebook#xff0c;还不熟悉Jupyter的的小伙伴可以去看一下我以前的文…小伙伴们好咱们今天演绎一个使用KerasCV的StableDiffusion模型生成新的图像的示例。
考虑计算机性能的因素这次咱们在Colab上进行Colab您可以理解为在线版的Jupyter Notebook还不熟悉Jupyter的的小伙伴可以去看一下我以前的文章
政安晨的机器学习笔记——示例讲解机器学习工具Jupyter Notebook入门超级详细https://blog.csdn.net/snowdenkeke/article/details/135880886
概述
在本篇中我们将展示如何使用stability.ai的text-to-image模型Stable Diffusion基于文本提示生成新图像咱们这里使用的是KerasCV的实现。
Stable Diffusion是一个强大的开源文本到图像生成模型。虽然存在多个开源实现可以轻松地从文本提示创建图像但KerasCV的实现具有一些明显的优势。其中包括XLA编译和混合精度支持这两者共同实现了最先进的生成速度。
在本指南中我们将探索KerasCV的Stable Diffusion实现展示如何使用这些强大的性能提升并探索它们所提供的性能优势。
开始前咱们安装一些依赖项并整理一些导入模块
pip install tensorflow keras_cv --upgrade --quiet
注意要在torch后端上运行此指南请在所有地方将设置jit_compileFalse。目前Stable Diffusion的XLA编译无法与torch一起使用。
我这里因为使用的是Colab所以我跳过上述的tensorflow依赖安装(colab自带) 安装好依赖后咱们导入
import time
import keras_cv
from tensorflow import keras
import matplotlib.pyplot as plt 稍微罗嗦一下
与大多数讲解文章不同的是一般讲解都是首先解释一个主题然后展示如何实现它但是对于文本到图像生成展示比讲解更简单。
现在快来看看 keras_cv.models.StableDiffusion() 的强大之处。
首先我们构建一个模型
model keras_cv.models.StableDiffusion(img_width512, img_height512) 这里有一段提示
By using this model checkpoint, you acknowledge that its usage is subject to the terms of the CreativeML Open RAIL-M license at https://raw.githubusercontent.com/CompVis/stable-diffusion/main/LICENSE 说明模型咱们创建成功。 接下来我们给它一个提示词
images model.text_to_image(photograph of an astronaut riding a horse, batch_size3)def plot_images(images):plt.figure(figsize(20, 20))for i in range(len(images)):ax plt.subplot(1, len(images), i 1)plt.imshow(images[i])plt.axis(off)plot_images(images)
我在Colab上运行了差不多6分钟 真的特别棒
但这种模型能做的远不止如此。让我们尝试一个更复杂的提示
images model.text_to_image(cute magical flying dog, fantasy art, golden color, high quality, highly detailed, elegant, sharp focus, concept art, character concepts, digital painting, mystery, adventure,batch_size3,
)
plot_images(images) 这个可能性真的是无穷无尽的至少Stable Diffusion潜力挖掘是无穷无尽的。
这一切是如何工作的
StableDiffusion 实际上当然并不依靠魔法运行它是一种扩散模型。我们来深入了解一下这是什么意思。
你可能对超分辨率的概念比较熟悉可以训练一个深度学习模型来去噪输入图像从而将其转变为更高分辨率的版本。这个深度学习模型并不是通过神奇地恢复从噪声、低分辨率输入中丢失的信息来实现的而是利用其训练数据分布来幻觉出在给定输入下最可能存在的视觉细节。
要了解更多关于超分辨率的内容你可以查看以下 Keras.io 教程
Image Super-Resolution using an Efficient Sub-Pixel CNNKeras documentationhttps://keras.io/examples/vision/super_resolution_sub_pixel/Enhanced Deep Residual Networks for single-image super-resolutionKeras documentationhttps://keras.io/examples/vision/edsr/
当你将这个想法推向极限时你可能会开始问自己——如果我们只在纯噪声上运行这样的模型会怎样模型将会去除噪声并开始产生全新的图像。通过多次重复这个过程你可以将一个小块噪声转化为越来越清晰和高分辨率的人工图片。
这是2020年《使用潜在扩散模型进行高分辨率图像合成》中提出的潜在扩散的关键思想。
https://arxiv.org/abs/2112.10752https://arxiv.org/abs/2112.10752要深入了解扩散您可以查看Keras.io教程《去噪扩散隐式模型》。
Denoising Diffusion Implicit ModelsKeras documentationhttps://keras.io/examples/generative/ddim/ 现在要从潜在的扩散转变为文本到图像系统仍然需要添加一个关键特性通过提示关键词控制生成的视觉内容的能力。这通过条件化实现这是一种经典的深度学习技术它包括将表示一小段文本的向量连接到噪声图像块上然后在一个{图像:标题}对的数据集上训练模型。
这就产生了稳定扩散架构。稳定扩散由三部分组成
文本编码器将您的提示转换为潜在向量。 扩散模型反复对一个64x64的潜在图像块进行去噪。 解码器将最终的64x64潜在图块转换为更高分辨率的512x512图像。 首先您的文本提示通过文本编码器投影到潜在向量空间中这只是一个预训练的、冻结的语言模型。然后该提示向量与随机生成的噪声图像块连接在一起通过扩散模型在一系列步骤上反复进行去噪步骤越多图像越清晰、更好 - 默认值为50步。
最后64x64的潜在图像被发送到解码器中以正确地渲染出高分辨率的图像。 总的来说这是一个相当简单的系统——Keras实现仅包含四个文件总共不到500行代码
text_encoder.py87行代码
diffusion_model.py181行代码
decoder.py86行代码
stable_diffusion.py106行代码
但是一旦你在数十亿张图片及其标题上进行训练这个相对简单的系统就会变得像魔术一样。正如费曼所说的关于宇宙的事物“它并不复杂只是有很多而已
KerasCV的好处
为什么应该使用keras_cv.models.StableDiffusion
除了易于使用的API之外KerasCV的稳定扩散模型具有一些强大的优势包括
图模式执行通过jit_compileTrue进行XLA编译支持混合精度计算
当这些优势结合在一起时KerasCV稳定扩散模型的运行速度比朴素实现快上数个数量级。本节介绍如何启用所有这些功能并展示使用它们所带来的性能提升。
为了进行比较我们进行了基准测试比较了HuggingFace diffusers实现的StableDiffusion与KerasCV实现之间的运行时间。两种实现都被要求为每个图像生成50个步骤的3个图像。在这个基准测试中我们使用了一个Tesla T4 GPU。
咱们所有的基准测试都是在GitHub上公开的开源项目并且可以在Colab上重新运行以复现结果。以下表格显示了基准测试的结果
GPUModelRuntimeTesla T4KerasCV (Warm Start)28.97sTesla T4diffusers (Warm Start)41.33sTesla V100KerasCV (Warm Start)12.45Tesla V100diffusers (Warm Start)12.72
在Tesla T4上的执行时间提升了30尽管在V100上的改进要小得多但我们通常预计基准测试结果在所有NVIDIA GPU上都会持续支持KerasCV。
为了完整起见我们报告了冷启动和热启动的生成时间。冷启动执行时间包括模型创建和编译的一次性成本因此在生产环境中可以忽略不计在该环境中您会多次重用同一模型实例。无论如何这是冷启动的数据
GPUModelRuntimeTesla T4KerasCV (Cold Start)83.47sTesla T4diffusers (Cold Start)46.27sTesla V100KerasCV (Cold Start)76.43Tesla V100diffusers (Cold Start)13.90
尽管运行此指南的运行时结果可能会有所不同但在我们的测试中使用KerasCV实现的Stable Diffusion比其PyTorch版本要快得多。这可能主要归因于XLA编译。
注意每个优化的性能增益在不同的硬件设置之间可能存在显著差异。
未优化模型的基准测试
在继续开始之前让我们首先对我们的未优化模型进行基准测试
benchmark_result []
start time.time()
images model.text_to_image(A cute otter in a rainbow whirlpool holding shells, watercolor,batch_size3,
)
end time.time()
benchmark_result.append([Standard, end - start])
plot_images(images)print(fStandard model: {(end - start):.2f} seconds)
keras.backend.clear_session() # Clear session to preserve memory.
这次咱们用了一分钟 混合精度
“混合精度”是指使用float16精度进行计算同时使用float32格式存储权重。这样做是为了利用现代NVIDIA GPU上float16操作背后比其float32对应操作更快的内核。
在Keras中启用混合精度计算因此也适用于keras_cv.models.StableDiffusion只需要调用
keras.mixed_precision.set_global_policy(mixed_float16) 就这样开箱即用。
model keras_cv.models.StableDiffusion()print(Compute dtype:, model.diffusion_model.compute_dtype)
print(Variable dtype:,model.diffusion_model.variable_dtype,
) By using this model checkpoint, you acknowledge that its usage is subject to the terms of the CreativeML Open RAIL-M license at https://raw.githubusercontent.com/CompVis/stable-diffusion/main/LICENSE
Compute dtype: float16
Variable dtype: float32 正如您所看到的上面构建的模型现在使用了混合精度计算利用float16操作的速度进行计算同时以float32精度存储变量。
# Warm up model to run graph tracing before benchmarking.
model.text_to_image(warming up the model, batch_size3)start time.time()
images model.text_to_image(a cute magical flying dog, fantasy art, golden color, high quality, highly detailed, elegant, sharp focus, concept art, character concepts, digital painting, mystery, adventure,batch_size3,
)
end time.time()
benchmark_result.append([Mixed Precision, end - start])
plot_images(images)print(fMixed precision model: {(end - start):.2f} seconds)
keras.backend.clear_session() XLA编译
TensorFlow内置了XLA加速线性代数编译器。 keras_cv.models.StableDiffusion在开箱即用时支持jit_compile参数。将此参数设置为True可以启用XLA编译从而实现显著加速。
使用如下
# Set back to the default for benchmarking purposes.
keras.mixed_precision.set_global_policy(float32)model keras_cv.models.StableDiffusion(jit_compileTrue)
# Before we benchmark the model, we run inference once to make sure the TensorFlow
# graph has already been traced.
images model.text_to_image(An avocado armchair, batch_size3)
plot_images(images) 这次咱们用了2分多钟。
让我们来对我们的 XLA 模型进行基准测试
start time.time()
images model.text_to_image(A cute otter in a rainbow whirlpool holding shells, watercolor,batch_size3,
)
end time.time()
benchmark_result.append([XLA, end - start])
plot_images(images)print(fWith XLA: {(end - start):.2f} seconds)
keras.backend.clear_session() 在A100 GPU上我们获得了大约2倍的加速。太棒了
融合一起
现在咱们将所有这些都放在一起。
现在咱们看看如何组装世界上性能最佳的StableDiffusion推理流程
执行下述代码
keras.mixed_precision.set_global_policy(mixed_float16)
model keras_cv.models.StableDiffusion(jit_compileTrue) 接下来可以自己尝试一下我这里就不赘述了
# Lets make sure to warm up the model
images model.text_to_image(Teddy bears conducting machine learning research,batch_size3,
)
plot_images(images)
start time.time()
images model.text_to_image(A mysterious dark stranger visits the great pyramids of egypt, high quality, highly detailed, elegant, sharp focus, concept art, character concepts, digital painting,batch_size3,
)
end time.time()
benchmark_result.append([XLA Mixed Precision, end - start])
plot_images(images)print(fXLA mixed precision: {(end - start):.2f} seconds)
可以这样查看结果
print({:22} {:22}.format(Model, Runtime))
for result in benchmark_result:name, runtime resultprint({:22} {:22}.format(name, runtime)) 这里咱们受限于资源没有执行优化其实经过全面优化的模型只需要几秒钟就能够在A100 GPU上从一个文本提示中生成一组图像。
结论
KerasCV提供了Stable Diffusion的先进实现并通过使用XLA和混合精度。
如果您拥有自己的NVIDIA GPU或最新的MacBookPro等您也可以在本地计算机上运行模型。请注意在MacBookPro上运行时不应启用混合精度因为它有可能未得到苹果的良好支持。