Diffusers 文档

ControlNet-XS 与 Stable Diffusion XL

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

ControlNet-XS 与 Stable Diffusion XL

ControlNet-XS 由 Denis Zavadski 和 Carsten Rother 在ControlNet-XS中引入。它的核心思想是,原始 ControlNet中的控制模型可以大大缩小,同时仍然能产生良好的结果。

与原始 ControlNet 模型一样,您可以提供额外的控制图像来条件化和控制 Stable Diffusion 的生成。例如,如果您提供一张深度图,ControlNet 模型将生成一张保留深度图中空间信息的图像。这是一种更灵活、更准确的图像生成控制方式。

ControlNet-XS 生成的图像质量与常规 ControlNet 相当,但速度快 20-25%(参见基准测试),并且内存使用量减少约 45%。

以下是项目页面的概述:

随着计算能力的提高,当前的模型架构似乎遵循了简单地扩大所有组件而不验证其必要性的趋势。在这个项目中,我们研究了 ControlNet [Zhang et al., 2023] 的大小和架构设计,以控制基于 Stable Diffusion 的图像生成过程。我们表明,一个参数量仅为基础模型 1% 的新架构能够实现最先进的结果,在 FID 分数方面明显优于 ControlNet。因此,我们将其命名为 ControlNet-XS。我们提供了用于控制 StableDiffusion-XL [Podell et al., 2023] (模型 B,48M 参数) 和 StableDiffusion 2.1 [Rombach et al. 2022] (模型 B,14M 参数) 的代码,所有这些都遵循 openrail 许可证。

该模型由UmerHA贡献。❤️

🧪 许多 SDXL ControlNet 检查点仍处于实验阶段,还有很大的改进空间。欢迎打开Issue并留下您的反馈,告诉我们如何改进!

务必查看调度器指南,了解如何探索调度器速度和质量之间的权衡,并参阅跨管道重用组件部分,了解如何高效地将相同组件加载到多个管道中。

StableDiffusionXLControlNetXSPipeline

class diffusers.StableDiffusionXLControlNetXSPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.controlnets.controlnet_xs.UNetControlNetXSModel] controlnet: ControlNetXSAdapter scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None )

参数

使用 ControlNet-XS 指导的 Stable Diffusion XL 文本到图像生成管道。

该模型继承自DiffusionPipeline。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等),请查看超类文档。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 control_guidance_start: float = 0.0 control_guidance_end: float = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,您需要传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 发送给 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则在两个文本编码器中都使用 prompt
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): 用于为 unet 提供生成指导的 ControlNet 输入条件。如果类型指定为 torch.Tensor,则直接传递给 ControlNet。PIL.Image.Image 也可以作为图像接受。输出图像的尺寸默认为 image 的尺寸。如果传递了 height 和/或 width,则 image 会相应地调整大小。如果在 init 中指定了多个 ControlNet,则图像必须作为列表传递,以便列表的每个元素可以正确地批量输入到单个 ControlNet。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。任何低于 512 像素的图像对于 stabilityai/stable-diffusion-xl-base-1.0 和未专门针对低分辨率进行微调的检查点都不会很好地工作。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(像素)。任何低于 512 像素的图像对于 stabilityai/stable-diffusion-xl-base-1.0 和未专门针对低分辨率进行微调的检查点都不会很好地工作。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会产生更高质量的图像,但推理速度会变慢。
  • guidance_scale (float, 可选, 默认为 5.0) — 更高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但代价是图像质量较低。当 guidance_scale > 1 时启用引导比例。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不包含内容的提示或提示列表。如果未定义,您需要传递 negative_prompt_embeds。当不使用引导时 (guidance_scale < 1) 忽略。
  • negative_prompt_2 (strList[str], 可选) — 用于引导图像生成中不包含内容的提示或提示列表。这会发送给 tokenizer_2text_encoder_2。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则使用提供的随机 generator 采样生成潜在张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的合并文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从 prompt 输入参数生成合并文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负合并文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从 negative_prompt 输入参数生成合并的 negative_prompt_embeds
  • output_type (str, 可选,默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 self.processor 中定义的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可选,默认为 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,乘以 controlnet_conditioning_scale
  • control_guidance_start (float, 可选,默认为 0.0) — ControlNet 开始应用的步数总百分比。
  • control_guidance_end (float, 可选,默认为 1.0) — ControlNet 停止应用的步数总百分比。
  • original_size (Tuple[int], 可选,默认为 (1024, 1024)) — 如果 original_sizetarget_size 不同,图像将显示为缩小或放大。如果未指定,original_size 默认为 (width, height)。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • crops_coords_top_left (Tuple[int], 可选,默认为 (0, 0)) — crops_coords_top_left 可用于生成一张看起来是从 crops_coords_top_left 位置向下“裁剪”的图像。通常通过将 crops_coords_top_left 设置为 (0, 0) 来获得居中良好、美观的图像。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,它将默认为 (width, height)。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (Tuple[int], 可选,默认为 (1024, 1024)) — 根据特定图像分辨率对生成过程进行负面条件限制。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选,默认为 (0, 0)) — 根据特定裁剪坐标对生成过程进行负面条件限制。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选,默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负面条件限制。在大多数情况下应与 target_size 相同。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • clip_skip (int, 可选) — 计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示将使用预最终层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每次去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类。其参数为:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)callback_kwargs 将包含 callback_on_step_end_tensor_inputs 中指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (List, 可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dictTrue,则返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否则返回包含输出图像的 tuple

用于生成的管道的调用函数。

示例

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetXSPipeline, ControlNetXSAdapter, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> controlnet = ControlNetXSAdapter.from_pretrained(
...     "UmerHA/Testing-ConrolNetXS-SDXL-canny", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
... ).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示
  • prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则在两个文本编码器中都使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1 时),将被忽略。
  • negative_prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_encoder_2 的不引导图像生成的提示。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的合并文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 prompt 输入参数生成合并文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负合并文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 negative_prompt 输入参数生成合并的 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则应用于文本编码器的所有 LoRA 层的 LoRA 缩放。
  • clip_skip (int, 可选) — 计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示将使用预最终层的输出计算提示嵌入。

将提示编码为文本编码器隐藏状态。

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected (List[bool]) — 指示相应生成的图像是否包含“不适合工作”(nsfw) 内容的列表,如果无法执行安全检查,则为 None

Stable Diffusion 管道的输出类。

< > 在 GitHub 上更新