Diffusers documentation

Stable Diffusion XL 的 ControlNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Stable Diffusion XL 的 ControlNet

LoRA

ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 中提出。

使用 ControlNet 模型,您可以提供一张额外的控制图像,以调节并控制 Stable Diffusion 的生成过程。例如,如果您提供一张深度图,ControlNet 模型将生成一张保留深度图中空间信息的图像。这是一种更灵活、更精确地控制图像生成过程的方式。

该论文的摘要如下:

我们提出了 ControlNet,一种用于为大型预训练文本到图像扩散模型添加空间条件控制的神经网络架构。ControlNet 锁定生产就绪的大型扩散模型,并复用其使用数十亿张图像预训练得到的深层且鲁棒的编码层作为强大的骨干网络,以学习多样化的条件控制。该神经架构通过“零卷积”(零初始化的卷积层)进行连接,这些层使参数从零开始逐步增长,并确保在微调过程中不会产生有害噪声。我们使用 Stable Diffusion 测试了多种条件控制,例如边缘、深度、分割、人体姿态等,支持使用单一或多个条件,以及有或无提示词的情况。我们展示了 ControlNet 的训练在小规模(<50k)和大规模(>1m)数据集上均具有鲁棒性。大量结果表明,ControlNet 有助于将图像扩散模型的应用扩展到更广泛的领域。

您可以在 🤗 Diffusers Hub 组织中找到更多较小的 Stable Diffusion XL (SDXL) ControlNet 检查点,并可在 Hub 上浏览社区训练的检查点。

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

如果您没有看到感兴趣的检查点,可以使用我们的训练脚本自行训练 SDXL ControlNet。

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

StableDiffusionXLControlNetPipeline

类 diffusers.StableDiffusionXLControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

参数

  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • text_encoder_2 (CLIPTextModelWithProjection) — 第二个冻结的文本编码器 (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)。
  • tokenizer (CLIPTokenizer) — 用于对文本进行分词的 CLIPTokenizer。
  • tokenizer_2 (CLIPTokenizer) — 用于对文本进行分词的 CLIPTokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的 UNet2DConditionModel。
  • controlnet(ControlNetModel 或 list[ControlNetModel])— 在去噪过程中为 unet 提供额外的条件信息。如果以列表形式设置多个 ControlNet,则会将每个 ControlNet 的输出相加,以生成一个合并的额外条件。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool,可选,默认为 "True") — 是否始终将负提示嵌入设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool,可选) — 是否使用 invisible_watermark 库为输出图像添加水印。如果未定义,且该包已安装,则默认为 True;否则不使用水印。

使用 Stable Diffusion XL 和 ControlNet 引导进行文本到图像生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_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) — 生成图像的高度(以像素为单位)。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点,低于 512 像素的效果通常不佳。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点,低于 512 像素的宽度效果不佳。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (list[float],可选) — 用于在支持 sigmas 参数的调度器的 set_timesteps 方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • denoising_end (float, 可选) — 如果指定,将确定在有意提前终止之前需要完成的去噪过程的总比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留相当多的噪声,具体程度由调度器选择的离散时间步决定。理想情况下,当此流水线作为“去噪器混合”多流水线设置的一部分时,应使用 denoising_end 参数,详见 优化图像输出
  • guidance_scale (float,可选,默认值为 5.0) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时,启用 guidance scale。
  • negative_prompt (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • negative_prompt_2 (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词。该内容会发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器都会使用 negative_prompt。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[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。
  • ip_adapter_image — (PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • guess_mode(bool,可选,默认为 False)— 即使移除所有提示词,ControlNet 编码器也会尝试识别输入图像的内容。建议将 guidance_scale 的值设置在 3.0 到 5.0 之间。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。
  • original_size (tuple[int],可选,默认为 (1024, 1024)) — 如果 original_size 与 target_size 不同,图像将看起来像是被下采样或上采样了。 如果未指定,original_size 默认为 (height, width)。这是 SDXL 微条件的一部分, 如 https://huggingface.co/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.co/papers/2307.01952 中的第 2.2 节。
  • target_size (tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,则默认为 (height, width)。这是 SDXL 微条件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (tuple[int],可选,默认为 (1024, 1024)) — 根据特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 的第 2.2 节。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int],可选,默认为 (0, 0)) — 根据特定的裁剪坐标对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 第 2.2 节的说明。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int],可选,默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负向条件控制。在大多数情况下,它应与 target_size 相同。这是 SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、可选) — 在推理过程中,每个去噪步骤结束时调用的函数,或 PipelineCallback 或 MultiPipelineCallbacks 的子类,其参数如下: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 属性中列出的变量。

返回值

StableDiffusionPipelineOutput 或 tuple

如果 return_dict 为 True,则返回 StableDiffusionPipelineOutput,否则返回一个包含输出图像的 tuple。

用于生成的 pipeline 的调用函数。

示例:

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, 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://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, 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: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • 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。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
  • embedding_dim (int,可选,默认为 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype,可选,默认为 torch.float32) — 生成嵌入的数据类型。

返回值

torch.Tensor

形状为 (len(w), embedding_dim) 的嵌入向量。

参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLControlNetImg2ImgPipeline

类 diffusers.StableDiffusionXLControlNetImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersrequires_aesthetics_score: bool = Falseforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

参数

  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器。Stable Diffusion 使用 CLIP 的文本部分,具体为 clip-vit-large-patch14 变体。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二个冻结的文本编码器。Stable Diffusion XL 使用 CLIP 的文本和池化部分, 具体为 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — 第二个 CLIPTokenizer 类的 Tokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
  • controlnet(ControlNetModel 或 list[ControlNetModel])— 在去噪过程中为 unet 提供额外的条件。如果以列表形式设置多个 ControlNet,则会将每个 ControlNet 的输出相加,以生成一个合并的额外条件。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
  • requires_aesthetics_score (bool,可选,默认为 "False") — unet 在推理期间是否需要传入 aesthetic_score 条件。另请参阅 stabilityai/stable-diffusion-xl-refiner-1-0 的配置。
  • force_zeros_for_empty_prompt (bool,可选,默认为 "True") — 是否强制将负提示嵌入始终设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 为输出图像添加水印。如果未定义,则当该包已安装时默认为 True,否则不使用水印。
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;作为 safety_checker 的输入。

使用 Stable Diffusion XL 并结合 ControlNet 引导进行图像到图像生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonestrength: float = 0.8num_inference_steps: int = 50guidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 0.8guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneaesthetic_score: float = 6.0negative_aesthetic_score: float = 2.5clip_skip: int | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_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]]): 初始图像将作为图像生成过程的起点。也可以接受图像潜变量作为 image,如果直接传入潜变量,则不会再次进行编码。
  • control_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 的输入条件。ControlNet 使用该输入条件生成对 Unet 的引导。如果类型指定为 torch.Tensor,则按原样传递给 ControlNet。也可以接受 PIL.Image.Image 作为图像。输出图像的默认尺寸与 image 的尺寸相同。如果传入了高度和/或宽度,image 将根据它们进行缩放。如果在初始化中指定了多个 ControlNet,则必须以列表形式传入图像,以便列表中的每个元素都能被正确批处理,作为单个 controlnet 的输入。
  • height (int,可选,默认为 control_image 的尺寸) — 生成图像的高度(以像素为单位)。低于 512 像素的值在 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点上效果不佳。
  • width (int,可选,默认为 control_image 的尺寸) — 生成图像的宽度(以像素为单位)。低于 512 像素的宽度在 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点上效果不佳。
  • strength (float, 可选,默认为 0.8) — 指示对参考 image 进行变换的程度。取值必须在 0 到 1 之间。image 用作起始点,strength 越高,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。值为 1 时,基本上会忽略 image。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认值为 7.5) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • 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。
  • ip_adapter_image — (PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在初始化时指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • guess_mode(bool,可选,默认为 False)— 在此模式下,即使您移除了所有提示词,ControlNet 编码器也会尽力识别输入图像的内容。建议将 guidance_scale 设置在 3.0 到 5.0 之间。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认为 1.0) — ControlNet 停止应用所占总步数的百分比。
  • original_size (tuple[int],可选,默认为 (1024, 1024)) — 如果 original_size 与 target_size 不同,图像将看起来像是被下采样或上采样了。 如果未指定,original_size 默认为 (height, width)。这是 SDXL 微条件的一部分, 如 https://huggingface.co/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.co/papers/2307.01952 中的第 2.2 节。
  • target_size (tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,则默认为 (height, width)。这是 SDXL 微条件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (tuple[int],可选,默认为 (1024, 1024)) — 根据特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 的第 2.2 节。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • negative_crops_coords_top_left (tuple[int],可选,默认为 (0, 0)) — 根据特定的裁剪坐标对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 第 2.2 节的说明。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • negative_target_size (tuple[int],可选,默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负向条件控制。在大多数情况下,它应与 target_size 相同。这是 SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。
  • aesthetic_score (float,可选,默认值为 6.0) — 用于通过影响正向文本条件来模拟生成图像的美学评分。 这是 https://huggingface.co/papers/2307.01952 第 2.2 节中所述 SDXL 微条件化的一部分。
  • negative_aesthetic_score (float,可选,默认值为 2.5) — SDXL 微条件的一部分,详见 https://huggingface.co/papers/2307.01952 的第 2.2 节。可通过影响负向文本条件来模拟生成图像的美学评分。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、可选) — 在推理过程中,每个去噪步骤结束时调用的函数,或 PipelineCallback 或 MultiPipelineCallbacks 的子类,其参数如下: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 属性中列出的变量。

返回值

StableDiffusionPipelineOutput 或 tuple

如果 return_dict 为 True,则返回 StableDiffusionPipelineOutput,否则返回包含输出图像的 tuple。

调用生成 pipeline 时调用的函数。

示例:

>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTImageProcessor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image

>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()


>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image


>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")

encode_prompt

< >

( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • 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。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。

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

StableDiffusionXLControlNetInpaintPipeline

类 diffusers.StableDiffusionXLControlNetInpaintPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersrequires_aesthetics_score: bool = Falseforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Noneimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None )

参数

使用 Stable Diffusion XL 进行文本到图像生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]] = Noneheight: int | None = Nonewidth: int | None = Nonepadding_mask_crop: int | None = Nonestrength: float = 0.9999num_inference_steps: int = 50denoising_start: float | None = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0guidance_rescale: float = 0.0original_size: tuple = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple = Noneaesthetic_score: float = 6.0negative_aesthetic_score: float = 2.5clip_skip: int | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • image (PIL.Image.Image) — Image,或表示图像批次的张量,该图像将被进行修复,即图像的部分区域将被 mask_image 掩码,并根据 prompt 重新绘制。
  • mask_image (PIL.Image.Image) — Image,或表示图像批次的张量,用于对 image 进行遮罩。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,在使用前会先转换为单通道(亮度)。如果它是张量,则应包含一个颜色通道(L)而不是三个,因此预期的形状应为 (B, H, W, 1)。
  • control_image (PipelineImageInput 或 list[PipelineImageInput],可选) — 用于为 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) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。
  • padding_mask_crop (int, 可选,默认为 None) — 应用于图像和掩码的裁剪边距大小。如果为 None,则不对 image 和 mask_image 进行裁剪。如果 padding_mask_crop 不为 None,则会先找到一个与图像具有相同宽高比且包含所有掩码区域的矩形区域,然后基于 padding_mask_crop 扩展该区域。随后,在调整大小以匹配原始图像尺寸用于修复之前,会根据扩展后的区域对图像和 mask_image 进行裁剪。当掩码区域较小而图像较大,且包含与修复无关的信息(例如背景)时,此功能非常有用。
  • strength (float,可选,默认值为 0.9999) — 从概念上讲,表示对参考image中被掩码部分进行多大程度的变换。取值必须在 0 到 1 之间。image将作为起点,strength越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当strength为 1 时,添加的噪声达到最大值,去噪过程将运行num_inference_steps中指定的完整迭代次数。因此,值为 1 时,基本上会忽略参考image中被掩码的部分。请注意,如果denoising_start被声明为整数,则strength的值将被忽略。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • denoising_start (float, 可选) — 如果指定了该参数,则表示在去噪过程启动之前,需要跳过去噪总过程的相应比例(介于 0.0 和 1.0 之间)。因此,去噪过程的初始部分将被跳过,并且假定传入的 image 是一张部分去噪的图像。请注意,当指定此参数时,strength 将被忽略。denoising_start 参数在将此管道集成到“去噪器混合”多管道配置中时特别有用,具体细节请参阅 优化图像输出。
  • denoising_end (float, 可选) — 若指定此参数,则决定在去噪过程被有意提前终止前,需要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量噪声(大约还需要最后 20% 的时间步),并且应由一个将 denoising_start 设置为 0.8 的后续 pipeline 进行去噪,以便仅对调度器的最后 20% 进行去噪。理想情况下,当此 pipeline 作为“Mixture of Denoisers”多 pipeline 设置的一部分时,应使用 denoising_end 参数,如 优化图像输出 中所述。
  • guidance_scale (float,可选,默认值为 7.5) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.Generator,可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • guess_mode(bool,可选,默认为 False)— 即使移除所有提示词,ControlNet 编码器也会尝试识别输入图像的内容。建议将 guidance_scale 的值设置在 3.0 到 5.0 之间。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。
  • guidance_rescale (float, optional, defaults to 0.0) — Guidance rescale factor from Common Diffusion Noise Schedules and Sample Steps are Flawed.
  • original_size (tuple[int],可选,默认为 (1024, 1024)) — 如果 original_size 与 target_size 不同,图像将看起来像是被下采样或上采样了。 如果未指定,original_size 默认为 (width, height)。这是 SDXL 微条件的一部分, 如 https://huggingface.co/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.co/papers/2307.01952 中的第 2.2 节。
  • target_size (tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,则默认为 (width, height)。这是 https://huggingface.co/papers/2307.01952 第 2.2 节中所述 SDXL 微条件化的一部分。
  • aesthetic_score (float,可选,默认值为 6.0) — 用于通过影响正向文本条件来模拟生成图像的美学评分。 这是 https://huggingface.co/papers/2307.01952 第 2.2 节中所述 SDXL 微条件化的一部分。
  • negative_aesthetic_score (float,可选,默认值为 2.5) — SDXL 微条件的一部分,详见 https://huggingface.co/papers/2307.01952 的第 2.2 节。可通过影响负向文本条件来模拟生成图像的美学评分。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、可选) — 在推理过程中,每个去噪步骤结束时调用的函数,或 PipelineCallback 或 MultiPipelineCallbacks 的子类,其参数如下: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.StableDiffusionXLPipelineOutput 或 tuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否则返回 tuple. 元组。当返回元组时,第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例:

>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> from PIL import Image
>>> import numpy as np
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((1024, 1024))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((1024, 1024))


>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image


>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
... ).images[0]

encode_prompt

< >

( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • 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。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。

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

StableDiffusionPipelineOutput

类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

参数

  • 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 管道的输出类。

Update on GitHub