Diffusers 文档

ControlNet-XS

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

ControlNet-XS

ControlNet-XS 由 Denis Zavadski 和 Carsten Rother 在 ControlNet-XS 中提出。它基于以下观察:原始 ControlNet 中的控制模型可以做得更小,并且仍然产生良好的结果。

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

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

以下是来自 项目页面 的概述

随着计算能力的提升,当前的模型架构似乎遵循简单地放大所有组件的趋势,而没有验证这样做的必要性。在这个项目中,我们研究了 ControlNet [Zhang et al., 2023] 的尺寸和架构设计,以在使用基于稳定扩散的模型时控制图像生成过程。我们表明,一种参数量仅为基础模型 1% 的新架构实现了最先进的结果,在 FID 分数方面明显优于 ControlNet。因此,我们称之为 ControlNet-XS。我们提供了用于控制 StableDiffusion-XL [Podell et al., 2023] (模型 B,48M 参数) 和 StableDiffusion 2.1 [Rombach et al. 2022] (模型 B,14M 参数) 的代码,所有代码均在 openrail 许可下发布。

此模型由 UmerHA 贡献。 ❤️

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

StableDiffusionControlNetXSPipeline

class diffusers.StableDiffusionControlNetXSPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.controlnets.controlnet_xs.UNetControlNetXSModel] controlnet: ControlNetXSAdapter scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码为图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 一个 UNet2DConditionModel,用于创建 UNetControlNetXSModel 以对编码后的图像潜在空间进行去噪。
  • controlnet (ControlNetXSAdapter) — 一个 ControlNetXSAdapter,与 unet 结合使用以对编码后的图像潜在空间进行去噪。
  • scheduler (SchedulerMixin) — 一个调度器,与 unet 结合使用以对编码后的图像潜在空间进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于估计生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅 模型卡
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用带有 ControlNet-XS 指导的 Stable Diffusion 进行文本到图像生成的 Pipeline。

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

该 pipeline 还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = 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 = 7.5 negative_prompt: 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 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 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'] ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则需要传递 prompt_embeds
  • 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]]): ControlNet 输入条件,为 unet 生成提供指导。如果类型指定为 torch.Tensor,则按原样传递给 ControlNet。PIL.Image.Image 也可以接受作为图像。输出图像的尺寸默认为 image 的尺寸。如果传递了高度和/或宽度,则会相应地调整 image 的大小。如果在 init 中指定了多个 ControlNet,则必须将图像作为列表传递,以便可以正确批处理列表中的每个元素,以输入到单个 ControlNet。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲较低的图像质量。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • eta (float, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成过程具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的、从高斯分布中采样的噪声潜变量,用作图像生成的输入。可用于使用不同的 prompt 微调相同的生成结果。如果未提供,则会使用提供的随机 generator 采样生成潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 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。如果在 init 中指定了多个 ControlNet,则可以将相应的比例设置为列表。
  • control_guidance_start (floatList[float], 可选,默认为 0.0) — ControlNet 开始应用的占总步数的百分比。
  • control_guidance_end (floatList[float], 可选,默认为 1.0) — ControlNet 停止应用的占总步数的百分比。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。
  • 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 属性中列出的变量。

返回值

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回 tuple,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。

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

示例

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetXSPipeline, ControlNetXSAdapter
>>> 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

>>> controlnet = ControlNetXSAdapter.from_pretrained(
...     "UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1-base", 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 device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

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

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

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 上更新