Diffusers documentation

ControlNetUnion

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

ControlNetUnion

LoRA

ControlNetUnionModel 是 Stable Diffusion XL 的 ControlNet 实现。

ControlNet 模型由 xinsir6 在 ControlNetPlus 中提出。它支持多个条件输入,且不会增加计算量。

我们设计了一种新架构,能够在条件文本到图像生成中支持 10 种以上的控制类型,并生成在视觉上可与 midjourney 媲美的高分辨率图像。该网络基于原始的 ControlNet 架构,我们提出了两个新模块:1. 扩展原始 ControlNet,使其能够使用相同的网络参数支持不同的图像条件。2. 在不增加计算开销的情况下支持多条件输入,这对于希望精细编辑图像的设计师尤为重要。不同的条件使用相同的条件编码器,无需增加额外的计算或参数。

StableDiffusionXLControlNetUnionPipeline

class diffusers.StableDiffusionXLControlNetUnionPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModelscheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Nonefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

参数

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

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

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = 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 = 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.0control_mode: int | list[int] | list[list[int]] | None = Noneoriginal_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'] ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器均使用 prompt。
  • 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) — 生成图像的高度(以像素为单位)。对于 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 停止应用时占总步数的百分比。
  • control_mode (int or list[int] or list[list[int]], *optional*) -- The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image.
  • 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 controlnet_aux
>>> from controlnet_aux import LineartAnimeDetector
>>> from diffusers import StableDiffusionXLControlNetUnionPipeline, ControlNetUnionModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import torch

>>> prompt = "A cat"
>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> # initialize the models and pipeline
>>> controlnet = ControlNetUnionModel.from_pretrained(
...     "xinsir/controlnet-union-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetUnionPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     variant="fp16",
... )
>>> pipe.enable_model_cpu_offload()
>>> # prepare image
>>> processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
>>> controlnet_img = processor(image, output_type="pil")
>>> # generate image
>>> image = pipe(prompt, control_image=[controlnet_img], control_mode=[3], height=1024, width=1024).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

StableDiffusionXLControlNetUnionImg2ImgPipeline

class diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModelscheduler: 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(ControlNetUnionModel)—— 在去噪过程中为 unet 提供额外的条件输入。
  • 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], 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 = 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.0control_mode: int | list[int] | list[list[int]] | None = Noneoriginal_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 (PipelineImageInput 或 list[PipelineImageInput],可选) — 用于为 unet 的生成过程提供引导的 ControlNet 输入条件。如果类型指定为 torch.Tensor,则会原样传递给 ControlNet。也可以接受 PIL.Image.Image 作为图像。输出图像的默认尺寸与 image 的尺寸相同。如果传入了 height 和/或 width,image 将相应地调整大小。如果在 init 中指定了多个 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。如果在 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 停止应用时占总步数的百分比。
  • control_mode (int or list[int] or list[list[int]], *optional*) -- The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image
  • 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 controlnet_aux
from diffusers import (
    StableDiffusionXLControlNetUnionImg2ImgPipeline,
    ControlNetUnionModel,
    AutoencoderKL,
)
from diffusers.utils import load_image
import torch
from PIL import Image
import numpy as np

prompt = "A cat"
# download an image
image = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
)
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
    "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    vae=vae,
    torch_dtype=torch.float16,
    variant="fp16",
).to("cuda")
# `enable_model_cpu_offload` is not recommended due to multiple generations
height = image.height
width = image.width
ratio = np.sqrt(1024.0 * 1024.0 / (width * height))
# 3 * 3 upscale correspond to 16 * 3 multiply, 2 * 2 correspond to 16 * 2 multiply and so on.
scale_image_factor = 3
base_factor = 16
factor = scale_image_factor * base_factor
W, H = int(width * ratio) // factor * factor, int(height * ratio) // factor * factor
image = image.resize((W, H))
target_width = W // scale_image_factor
target_height = H // scale_image_factor
images = []
crops_coords_list = [
    (0, 0),
    (0, width // 2),
    (height // 2, 0),
    (width // 2, height // 2),
    0,
    0,
    0,
    0,
    0,
]
for i in range(scale_image_factor):
    for j in range(scale_image_factor):
        left = j * target_width
        top = i * target_height
        right = left + target_width
        bottom = top + target_height
        cropped_image = image.crop((left, top, right, bottom))
        cropped_image = cropped_image.resize((W, H))
        images.append(cropped_image)
# set ControlNetUnion input
result_images = []
for sub_img, crops_coords in zip(images, crops_coords_list):
    new_width, new_height = W, H
    out = pipe(
        prompt=[prompt] * 1,
        image=sub_img,
        control_image=[sub_img],
        control_mode=[6],
        width=new_width,
        height=new_height,
        num_inference_steps=30,
        crops_coords_top_left=(W, H),
        target_size=(W, H),
        original_size=(W * 2, H * 2),
    )
    result_images.append(out.images[0])
new_im = Image.new("RGB", (new_width * scale_image_factor, new_height * scale_image_factor))
new_im.paste(result_images[0], (0, 0))
new_im.paste(result_images[1], (new_width, 0))
new_im.paste(result_images[2], (new_width * 2, 0))
new_im.paste(result_images[3], (0, new_height))
new_im.paste(result_images[4], (new_width, new_height))
new_im.paste(result_images[5], (new_width * 2, new_height))
new_im.paste(result_images[6], (0, new_height * 2))
new_im.paste(result_images[7], (new_width, new_height * 2))
new_im.paste(result_images[8], (new_width * 2, new_height * 2))

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 表示使用倒数第二层的输出来计算提示嵌入。

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

StableDiffusionXLControlNetUnionInpaintPipeline

类 diffusers.StableDiffusionXLControlNetUnionInpaintPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelcontrolnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModelscheduler: 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.0control_mode: int | list[int] | list[list[int]] | None = Noneguidance_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 停止应用时占总步数的百分比。
  • control_mode (int or list[int] or list[list[int]], *optional*) -- The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image.
  • 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 时调用的函数。

示例:

from diffusers import StableDiffusionXLControlNetUnionInpaintPipeline, ControlNetUnionModel, AutoencoderKL
from diffusers.utils import load_image
import torch
import numpy as np
from PIL import Image

prompt = "A cat"
# download an image
image = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo.png"
).resize((1024, 1024))
mask = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo_mask.png"
).resize((1024, 1024))
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
    "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionInpaintPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    vae=vae,
    torch_dtype=torch.float16,
    variant="fp16",
)
pipe.enable_model_cpu_offload()
controlnet_img = image.copy()
controlnet_img_np = np.array(controlnet_img)
mask_np = np.array(mask)
controlnet_img_np[mask_np > 0] = 0
controlnet_img = Image.fromarray(controlnet_img_np)
# generate image
image = pipe(prompt, image=image, mask_image=mask, control_image=[controlnet_img], control_mode=[7]).images[0]
image.save("inpaint.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 表示使用倒数第二层的输出来计算提示嵌入。

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

Update on GitHub