首页 > 其他分享 >【diffusers 极速入门(二)】如何得到扩散去噪的中间结果?Pipeline callbacks 管道回调函数

【diffusers 极速入门(二)】如何得到扩散去噪的中间结果?Pipeline callbacks 管道回调函数

时间:2024-06-19 20:31:08浏览次数:11  
标签:Pipeline prompt tensor callback image latents diffusers callbacks step

本文是对 Hugging Face Diffusers 文档中关于回调函数的翻译与总结,:


管道回调函数

在管道的去噪循环中,可以使用callback_on_step_end参数添加自定义回调函数。该回调函数在每一步结束时执行,并修改管道属性和变量,以供下一步使用。这在动态调整某些管道属性或修改张量变量时非常有用。利用回调函数,你可以实现新的功能而无需修改底层代码。

目前,Diffusers 仅支持callback_on_step_end,如果你有其他执行点的回调需求,可以在 github 上提出功能请求。

官方回调函数

官方提供了一些可用于修改去噪循环的回调函数列表:

  • SDCFGCutoffCallback:在一定步数后禁用 CFG。对于 SD 1.5 pipelines 适用, 包括 text-to-image, image-to-image, inpaint, controlnet。
  • SDXLCFGCutoffCallback:在一定步数后禁用 CFG。对于 SDXL pipelines 适用, 包括 text-to-image, image-to-image, inpaint, controlnet。
  • IPAdapterScaleCutoffCallback:在一定步数后禁用 IP Adapter。对所有支持 IP-Adapter 的 pipelines 适用。

要设置回调函数,可以指定cutoff_step_ratiocutoff_step_index参数。

  • cutoff_step_ratio:带有步长比的浮点数。
  • cutoff_step_index:一个整数,包含步数的确切编号。

示例代码

import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionXLPipeline
from diffusers.callbacks import SDXLCFGCutoffCallback

callback = SDXLCFGCutoffCallback(cutoff_step_ratio=0.4)
# 也可以用 cutoff_step_index
# callback = SDXLCFGCutoffCallback(cutoff_step_ratio=None, cutoff_step_index=10)


pipeline = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
).to("cuda")
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, use_karras_sigmas=True)

prompt = "a sports car at the road, best quality, high quality, high detail, 8k resolution"
generator = torch.Generator(device="cpu").manual_seed(2628670641)

out = pipeline(
    prompt=prompt,
    negative_prompt="",
    guidance_scale=6.5,
    num_inference_steps=25,
    generator=generator,
    callback_on_step_end=callback,
)

out.images[0].save("official_callback.png")

在这里插入图片描述

动态无分类器引导

动态无分类器引导(classifier-free guidance,CFG)允许在一定步数后禁用 CFG,从而节省计算成本。回调函数应包含以下参数:

  • pipeline:访问管道实例属性(如num_timesteps和guidance_scale)。
  • step_indextimestep:当前步骤索引和时间步。在达到num_timesteps的40%后,使用step_index关闭CFG。
  • callback_kwargs:包含在去噪循环中可以修改的张量变量。是一个dict,包含可以在去噪循环中修改的张量变量。
    • 它只包括callback_on_step_end_tensor_inputs参数中指定的变量,该参数被传递给管道的__call__方法。
    • 不同的管道可能使用不同的变量集,因此请检查管道的_callback_tensor_inputs属性以获取可以修改的变量列表。一些常见的变量包括latents和prompt_embeds。
    • 对于此函数,请在将guidance_scale设置为0.0后更改prompt_embeds的批处理大小,以使其正常工作。

示例回调函数:

def callback_dynamic_cfg(pipe, step_index, timestep, callback_kwargs):
# adjust the batch_size of prompt_embeds according to guidance_scale
    if step_index == int(pipeline.num_timesteps * 0.4):
        prompt_embeds = callback_kwargs["prompt_embeds"]
        prompt_embeds = prompt_embeds.chunk(2)[-1]

# update guidance_scale and prompt_embeds
        pipeline._guidance_scale = 0.0
        callback_kwargs["prompt_embeds"] = prompt_embeds
    return callback_kwargs

每步生成后显示图像(中间结果)

通过访问并转换潜在空间,可以在每步生成后显示图像。以下函数将 SDXL 的潜在空间(4 通道)转换为 RGB 张量(3 通道)。

  1. 使用以下函数将SDXL潜伏时间(4个通道)转换为RGB张量(3个通道)
def latents_to_rgb(latents):
    weights = (
        (60, -60, 25, -70),
        (60,  -5, 15, -50),
        (60,  10, -5, -35)
    )

    weights_tensor = torch.t(torch.tensor(weights, dtype=latents.dtype).to(latents.device))
    biases_tensor = torch.tensor((150, 140, 130), dtype=latents.dtype).to(latents.device)
    rgb_tensor = torch.einsum("...lxy,lr -> ...rxy", latents, weights_tensor) + biases_tensor.unsqueeze(-1).unsqueeze(-1)
    image_array = rgb_tensor.clamp(0, 255)[0].byte().cpu().numpy()
    image_array = image_array.transpose(1, 2, 0)

    return Image.fromarray(image_array)
  1. 使用该函数在每步生成后解码并保存潜在空间为图像。
def decode_tensors(pipe, step, timestep, callback_kwargs):
    latents = callback_kwargs["latents"]
    image = latents_to_rgb(latents)
    image.save(f"{step}.png")
    return callback_kwargs
  1. decode_tensors函数传递给callback_on_step_end参数,以在每一步之后对张量进行解码。还需要在callback_on_step_end_tensor_inputs参数中指定要修改的内容,在本例中为 latents。
from diffusers import AutoPipelineForText2Image
import torch
from PIL import Image

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True
).to("cuda")

image = pipeline(
    prompt="A croissant shaped like a cute bear.",
    negative_prompt="Deformed, ugly, bad anatomy",
    callback_on_step_end=decode_tensors,
    callback_on_step_end_tensor_inputs=["latents"],
).images[0]

在这里插入图片描述

详细内容请参见Hugging Face Diffusers 官方文档

标签:Pipeline,prompt,tensor,callback,image,latents,diffusers,callbacks,step
From: https://blog.csdn.net/weixin_44212848/article/details/139811933

相关文章

  • 欢迎 Stable Diffusion 3 加入 Diffusers
    作为StabilityAI的StableDiffusion家族最新的模型,StableDiffusion3(SD3)现已登陆HuggingFaceHub,并且可用在......
  • Diffusers代码学习:LCM 图生图
    要将LCM用于图像到图像,需要将支持的LCM模型的Checkpoint加载到[UNet2DConditionModel]中,并用[LCMscheduler]替换scheduler程序。然后,可以像往常一样使用管道,并传递文本提示和初始图像,只需4个步骤即可生成图像。# 以下代码为程序运行进行设置importosos.environ["HF_ENDP......
  • DockerCompose+Jenkins+Pipeline流水线打包Vue项目(解压安装配置Node)入门
    场景DockerCompose+Jenkins+Pipeline流水线打包SpringBoot项目(解压安装配置JDK、Maven等)入门:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/139631755以上使用流水线配置和打包springboot后台项目,如果要使用流水线和配置node打包vue项目,可按如下步骤。注:博......
  • DockerCompose+Jenkins+Pipeline流水线打包SpringBoot项目(解压安装配置JDK、Maven等)
    场景DockerCompose中部署Jenkins(DockerDesktop在windows上数据卷映射):https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/139491855Docker+Jenkins+Gitee+Maven项目配置jdk、maven、gitee等拉取代码并自动构建以及遇到的那些坑:https://blog.csdn.net/BADAO_LIUMANG_......
  • Diffusers代码学习: T2I Adapter
    T2IAdapter是一款轻量级适配器,用于控制文本到图像模型并为其提供更准确的结构指导。它通过学习文本到图像模型的内部知识与外部控制信号(如边缘检测或深度估计)之间的对齐来工作。T2IAdapter的设计很简单,条件被传递到四个特征提取块和三个下采样块。这使得针对不同的条件快速......
  • Diffusers代码学习: IP-Adapter(续)
    但是IP-Adapter不仅可以通过文生图的方式,也可以通过图生图的方式生成目标图片,就无需使用提示词。只不过同上一篇所述,底层的逻辑和图生图是完全不同的。# 以下代码为程序运行进行设置,使用图生图的自动管道,importosos.environ["HF_ENDPOINT"]="https://hf-mirror.com" ......
  • 云原生时代:从 Jenkins 到 Argo Workflows,构建高效 CI Pipeline
    作者:蔡靖ArgoWorkflowsArgoWorkflows[1]是用于在Kubernetes上编排Job的开源的云原生工作流引擎。可以轻松自动化和管理Kubernetes上的复杂工作流程。适用于各种场景,包括定时任务、机器学习、ETL和数据分析、模型训练、数据流pipline、CI/CD等。KubernetesJobs......
  • DevOps生命周期的8个阶段和DevOps pipeline 详解
    您可能也在探索DevOpspipeline或工作流的概念,这些术语可能会根据不同的解释者而有所交替使用。尽管如此,DevOps生命周期和DevOpspipeline这两个术语更常被提及。本文将首先阐述DevOps生命周期的概念,然后深入介绍DevOpspipeline。DevOps生命周期和DevOpspipeline的概述DevOps......
  • python 通过 subprocess 运行的代码 exit(1) 不能使得pipeline fail
    在使用Python的subprocess模块运行外部命令时,如果你希望子进程的退出状态码能够影响Python脚本的执行结果,尤其是在使用管道(pipeline)时,你需要手动检查子进程的返回码并采取相应的措施。简单地使用subprocess.run或subprocess.call运行子进程并不会自动使Python脚......
  • pipeline的执行顺序
    假设pipeline里面有这样的handler顺序OutBoundHandler1InBoundHandler1OutBoundHandler2InBoundHandler2*当在【InBoundHandler1】里面执行【ctx.write()】时*向上执行触发【OutBoundHandler1.write()】方法*由于【OutBoundHandler2】在【InBoundHandler1】的......