Skip to content

DeepCache

DeepCache 通过战略性地缓存和重用高级特征,同时利用 U-Net 架构有效地更新低级特征,从而加速 [StableDiffusionPipeline] 和 [StableDiffusionXLPipeline]。

首先安装 DeepCache

bash
pip install DeepCache

然后加载并启用 DeepCacheSDHelper

diff
  import torch
  from diffusers import StableDiffusionPipeline
  pipe = StableDiffusionPipeline.from_pretrained('stable-diffusion-v1-5/stable-diffusion-v1-5', torch_dtype=torch.float16).to("cuda")

+ from DeepCache import DeepCacheSDHelper
+ helper = DeepCacheSDHelper(pipe=pipe)
+ helper.set_params(
+     cache_interval=3,
+     cache_branch_id=0,
+ )
+ helper.enable()

  image = pipe("a photo of an astronaut on a moon").images[0]

set_params 方法接受两个参数:cache_intervalcache_branch_idcache_interval 表示特征缓存的频率,以每次缓存操作之间的步数来指定。cache_branch_id 用于识别网络中哪个分支(从最浅层到最深层排序)负责执行缓存过程。

选择较低的 cache_branch_id 或较大的 cache_interval 可以提高推理速度,但会降低图像质量(这两个超参数的消融实验可以在 论文 中找到)。设置好这些参数后,可以使用 enabledisable 方法来激活或停用 DeepCacheSDHelper

基准测试

我们测试了 DeepCache 在 NVIDIA RTX A5000 上使用 50 个推理步骤加速 Stable Diffusion v2.1 的速度,使用了不同的配置,包括分辨率、批次大小、缓存间隔 (I) 和缓存分支 (B)。

ResolutionBatch sizeOriginalDeepCache(I=3, B=0)DeepCache(I=5, B=0)DeepCache(I=5, B=1)
512815.966.88(2.32x)5.03(3.18x)7.27(2.20x)
48.393.60(2.33x)2.62(3.21x)3.75(2.24x)
12.611.12(2.33x)0.81(3.24x)1.11(2.35x)
768843.5818.99(2.29x)13.96(3.12x)21.27(2.05x)
422.249.67(2.30x)7.10(3.13x)10.74(2.07x)
16.332.72(2.33x)1.97(3.21x)2.98(2.12x)
10248101.9545.57(2.24x)33.72(3.02x)53.00(1.92x)
449.2521.86(2.25x)16.19(3.04x)25.78(1.91x)
113.836.07(2.28x)4.43(3.12x)7.15(1.93x)