Diffusers documentation

Stable Diffusion 3 的 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 3 的 ControlNet

LoRA

StableDiffusion3ControlNetPipeline 是 Stable Diffusion 3 的 ControlNet 实现。

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 有助于将图像扩散模型的应用扩展到更广泛的领域。

This controlnet code is mainly implemented by The InstantX Team. The inpainting-related code was developed by The Alimama Creative Team. You can find pre-trained checkpoints for SD3-ControlNet in the table below:

ControlNet 类型开发者链接
CannyInstantX 团队链接
深度InstantX 团队链接
姿态InstantX 团队链接
TileInstantX 团队链接
图像修复AlimamaCreative 团队链接

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

StableDiffusion3ControlNetPipeline

类 diffusers.StableDiffusion3ControlNetPipeline

< >

( transformer: SD3Transformer2DModelscheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertext_encoder_2: CLIPTextModelWithProjectiontokenizer_2: CLIPTokenizertext_encoder_3: T5EncoderModeltokenizer_3: T5Tokenizercontrolnet: diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel | list[diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel] | tuple[diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel] | diffusers.models.controlnets.controlnet_sd3.SD3MultiControlNetModelimage_encoder: transformers.models.siglip.modeling_siglip.SiglipVisionModel | None = Nonefeature_extractor: transformers.models.siglip.image_processing_pil_siglip.SiglipImageProcessorPil | None = None )

参数

  • transformer (SD3Transformer2DModel) — 用于对编码后的图像潜在变量进行去噪的条件 Transformer(MMDiT)架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
  • text_encoder (CLIPTextModelWithProjection) — CLIP, 具体为 clip-vit-large-patch14 变体, 并额外添加了一个投影层,该层使用维度为 hidden_size 的对角矩阵进行初始化。
  • text_encoder_2(CLIPTextModelWithProjection)—— CLIP, 具体为 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • text_encoder_3 (T5EncoderModel) — 冻结的文本编码器。Stable Diffusion 3 使用 T5,具体为 t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — 第二个 CLIPTokenizer 类的 Tokenizer。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 类的分词器。
  • controlnet(SD3ControlNetModel 或 list[SD3ControlNetModel] 或 SD3MultiControlNetModel)— 在去噪过程中为 unet 提供额外的条件信息。如果以列表形式设置多个 ControlNet,则会将每个 ControlNet 的输出相加,以生成一个合并的额外条件。
  • image_encoder (SiglipVisionModel,可选) — 用于 IP Adapter 的预训练视觉模型。
  • feature_extractor (SiglipImageProcessor,可选) — 用于 IP Adapter 的图像处理器。

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_3: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0controlnet_pooled_projections: typing.Optional[torch.FloatTensor] = Nonenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = 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: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 256 ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,将使用 prompt。
  • prompt_3 (str 或 list[str],可选) — 要发送给 tokenizer_3 和 text_encoder_3 的提示词。如果未定义,将使用 prompt。
  • height (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • sigmas (list[float],可选) — 用于在支持 sigmas 参数的调度器的 set_timesteps 方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float,可选,默认值为 5.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。
  • 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]]): 用于为 unet 的生成过程提供引导的 ControlNet 输入条件。如果类型指定为 torch.Tensor,则会原样传递给 ControlNet。也可以接受 PIL.Image.Image 作为图像。输出图像的默认尺寸与 image 的尺寸相同。如果传入了高度和/或宽度,image 将相应地调整大小。如果在 init 中指定了多个 ControlNet,则必须以列表形式传入图像,以便列表中的每个元素都能被正确批处理,作为单个 ControlNet 的输入。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • controlnet_pooled_projections(形状为 (batch_size, projection_dim) 的 torch.FloatTensor)— 从 controlnet 输入条件的嵌入中投影得到的嵌入。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词或提示词列表,用于引导图像生成。如果未定义,则使用 negative_prompt。
  • negative_prompt_3(str 或 list[str],可选)— 要发送给 tokenizer_3 和 text_encoder_3 的、用于引导图像生成的反向提示词。如果未定义,则使用 negative_prompt。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image (PipelineImageInput,可选) — 用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (torch.Tensor, 可选) — 用于 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) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。
  • max_sequence_length (int,默认为 256) — 与 prompt 配合使用的最大序列长度。

返回值

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 或 tuple

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

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

示例:

>>> import torch
>>> from diffusers import StableDiffusion3ControlNetPipeline
>>> from diffusers.models import SD3ControlNetModel, SD3MultiControlNetModel
>>> from diffusers.utils import load_image

>>> controlnet = SD3ControlNetModel.from_pretrained("InstantX/SD3-Controlnet-Canny", torch_dtype=torch.float16)

>>> pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> control_image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
... )
>>> prompt = "A bird in space"
>>> image = pipe(
...     prompt, control_image=control_image, height=1024, width=768, controlnet_conditioning_scale=0.7
... ).images[0]
>>> image.save("sd3.png")

encode_image

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]device: device ) → torch.Tensor

参数

  • image (PipelineImageInput) — 要编码的输入图像。
  • device — (torch.device): Torch 设备。

返回值

torch.Tensor

编码后的图像特征表示。

使用预训练图像编码器将给定图像编码为特征表示。

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str]prompt_3: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneclip_skip: int | None = Nonemax_sequence_length: int = 256lora_scale: float | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则所有文本编码器均使用 prompt。
  • prompt_3(str 或 list[str],可选)— 要发送给 tokenizer_3 和 text_encoder_3 的提示词。如果未定义,则所有文本编码器都会使用 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。
  • negative_prompt_3 (str 或 list[str],可选) — 用于引导图像生成的负面提示词,将发送给 tokenizer_3 和 text_encoder_3。如果未定义,则所有文本编码器都会使用 negative_prompt。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

prepare_ip_adapter_image_embeds

< >

( ip_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: typing.Optional[torch.Tensor] = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = True )

参数

  • ip_adapter_image (PipelineImageInput,可选) — 用于 IP-Adapter 提取特征的输入图像。
  • ip_adapter_image_embeds (torch.Tensor, 可选) — 预计算好的图像嵌入。
  • device — (torch.device,可选): Torch 设备。
  • num_images_per_prompt (int,默认为 1) — 每个提示词应生成的图像数量。
  • do_classifier_free_guidance (bool,默认为 True) — 是否使用 classifier free guidance。

为在 IP-Adapter 中使用而准备图像嵌入。

必须传入 ip_adapter_image 或 ip_adapter_image_embeds。

StableDiffusion3ControlNetInpaintingPipeline

类 diffusers.StableDiffusion3ControlNetInpaintingPipeline

< >

( transformer: SD3Transformer2DModelscheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertext_encoder_2: CLIPTextModelWithProjectiontokenizer_2: CLIPTokenizertext_encoder_3: T5EncoderModeltokenizer_3: T5Tokenizercontrolnet: diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel | list[diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel] | tuple[diffusers.models.controlnets.controlnet_sd3.SD3ControlNetModel] | diffusers.models.controlnets.controlnet_sd3.SD3MultiControlNetModelimage_encoder: SiglipModel = Nonefeature_extractor: transformers.models.siglip.image_processing_pil_siglip.SiglipImageProcessorPil | None = None )

参数

  • transformer (SD3Transformer2DModel) — 用于对编码后的图像潜在变量进行去噪的条件 Transformer(MMDiT)架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
  • text_encoder (CLIPTextModelWithProjection) — CLIP, 具体为 clip-vit-large-patch14 变体, 并额外添加了一个投影层,该层使用维度为 hidden_size 的对角矩阵进行初始化。
  • text_encoder_2(CLIPTextModelWithProjection)—— CLIP, 具体为 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • text_encoder_3 (T5EncoderModel) — 冻结的文本编码器。Stable Diffusion 3 使用 T5,具体为 t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — 第二个 CLIPTokenizer 类的 Tokenizer。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 类的分词器。
  • controlnet(SD3ControlNetModel 或 list[SD3ControlNetModel] 或 SD3MultiControlNetModel)— 在去噪过程中为 transformer 提供额外的条件信息。如果以列表形式设置多个 ControlNet,则会将每个 ControlNet 的输出相加,以生成一个合并的额外条件。
  • image_encoder (PreTrainedModel,可选) — 用于 IP Adapter 的预训练视觉模型。
  • feature_extractor (BaseImageProcessor,可选) — 用于 IP Adapter 的图像处理器。

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_3: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_mask: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0controlnet_pooled_projections: typing.Optional[torch.FloatTensor] = Nonenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = 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: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 256 ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,将使用 prompt。
  • prompt_3 (str 或 list[str],可选) — 要发送给 tokenizer_3 和 text_encoder_3 的提示词。如果未定义,将使用 prompt。
  • height (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • sigmas (list[float],可选) — 用于在支持 sigmas 参数的调度器的 set_timesteps 方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float,可选,默认值为 5.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。
  • control_image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]、list[np.ndarray]) — Image、numpy 数组或张量,表示要进行图像修复(inpainting)的图像批次(即根据 prompt 对 control_mask 所指定的图像区域进行遮罩并重绘)。对于 numpy 数组和 PyTorch 张量,预期的取值范围为 [0, 1]。如果它是张量或张量列表,预期的形状应为 (B, C, H, W)。如果它是 numpy 数组或数组列表,预期的形状应为 (B, H, W, C) 或 (H, W, C)。
  • control_mask (torch.Tensor, PIL.Image.Image, np.ndarray, list[torch.Tensor], list[PIL.Image.Image], list[np.ndarray]) — Image、numpy 数组或张量,表示用于对 image 进行遮罩的图像批次。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,则在使用前会将其转换为单通道(亮度)。如果它是 numpy 数组或 PyTorch 张量,则应包含一个颜色通道(L)而不是三个通道,因此 PyTorch 张量的预期形状为 (B, 1, H, W)。对于 numpy 数组,其形状应为 (B, H, W, 1)、(B, H, W)、(H, W, 1) 或 (H, W)。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • controlnet_pooled_projections(形状为 (batch_size, projection_dim) 的 torch.FloatTensor)— 从 controlnet 输入条件的嵌入中投影得到的嵌入。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词或提示词列表,用于引导图像生成。如果未定义,则使用 negative_prompt。
  • negative_prompt_3(str 或 list[str],可选)— 要发送给 tokenizer_3 和 text_encoder_3 的、用于引导图像生成的反向提示词。如果未定义,则使用 negative_prompt。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image (PipelineImageInput,可选) — 用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (torch.Tensor, 可选) — 用于 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) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。
  • max_sequence_length (int,默认为 256) — 与 prompt 配合使用的最大序列长度。

返回值

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 或 tuple

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

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

示例:

>>> import torch
>>> from diffusers.utils import load_image, check_min_version
>>> from diffusers.pipelines import StableDiffusion3ControlNetInpaintingPipeline
>>> from diffusers.models.controlnet_sd3 import SD3ControlNetModel

>>> controlnet = SD3ControlNetModel.from_pretrained(
...     "alimama-creative/SD3-Controlnet-Inpainting", use_safetensors=True, extra_conditioning_channels=1
... )
>>> pipe = StableDiffusion3ControlNetInpaintingPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     controlnet=controlnet,
...     torch_dtype=torch.float16,
... )
>>> pipe.text_encoder.to(torch.float16)
>>> pipe.controlnet.to(torch.float16)
>>> pipe.to("cuda")

>>> image = load_image(
...     "https://huggingface.co/alimama-creative/SD3-Controlnet-Inpainting/resolve/main/images/dog.png"
... )
>>> mask = load_image(
...     "https://huggingface.co/alimama-creative/SD3-Controlnet-Inpainting/resolve/main/images/dog_mask.png"
... )
>>> width = 1024
>>> height = 1024
>>> prompt = "A cat is sitting next to a puppy."
>>> generator = torch.Generator(device="cuda").manual_seed(24)
>>> res_image = pipe(
...     negative_prompt="deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, mutated hands and fingers, disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, NSFW",
...     prompt=prompt,
...     height=height,
...     width=width,
...     control_image=image,
...     control_mask=mask,
...     num_inference_steps=28,
...     generator=generator,
...     controlnet_conditioning_scale=0.95,
...     guidance_scale=7,
... ).images[0]
>>> res_image.save(f"sd3.png")

encode_image

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]device: device ) → torch.Tensor

参数

  • image (PipelineImageInput) — 要编码的输入图像。
  • device — (torch.device): Torch 设备。

返回值

torch.Tensor

编码后的图像特征表示。

使用预训练图像编码器将给定图像编码为特征表示。

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str]prompt_3: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_3: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneclip_skip: int | None = Nonemax_sequence_length: int = 256lora_scale: float | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则所有文本编码器均使用 prompt。
  • prompt_3(str 或 list[str],可选)— 要发送给 tokenizer_3 和 text_encoder_3 的提示词。如果未定义,则所有文本编码器都会使用 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。
  • negative_prompt_3 (str 或 list[str],可选) — 用于引导图像生成的负面提示词,将发送给 tokenizer_3 和 text_encoder_3。如果未定义,则所有文本编码器都会使用 negative_prompt。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

prepare_ip_adapter_image_embeds

< >

( ip_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: typing.Optional[torch.Tensor] = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = True )

参数

  • ip_adapter_image (PipelineImageInput,可选) — 用于 IP-Adapter 提取特征的输入图像。
  • ip_adapter_image_embeds (torch.Tensor, 可选) — 预计算好的图像嵌入。
  • device — (torch.device,可选): Torch 设备。
  • num_images_per_prompt (int,默认为 1) — 每个提示词应生成的图像数量。
  • do_classifier_free_guidance (bool,默认为 True) — 是否使用 classifier free guidance。

为在 IP-Adapter 中使用而准备图像嵌入。

必须传入 ip_adapter_image 或 ip_adapter_image_embeds。

StableDiffusion3PipelineOutput

class diffusers.pipelines.stable_diffusion_3.pipeline_output.StableDiffusion3PipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

参数

  • images (list[PIL.Image.Image] 或 np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 numpy 数组。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。

Stable Diffusion 管道的输出类。

Update on GitHub