Diffusers 文档
ControlNet 与 Stable Diffusion XL
并获取增强的文档体验
开始使用
ControlNet 与 Stable Diffusion XL
ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 一文中引入。
使用 ControlNet 模型,您可以提供额外的控制图像来调节和控制 Stable Diffusion 的生成。例如,如果您提供深度图,ControlNet 模型将生成一个保留深度图空间信息的图像。这是一种更灵活和准确的方式来控制图像生成过程。
该论文的摘要是
我们介绍了 ControlNet,这是一种神经网络架构,旨在为大型预训练文本到图像扩散模型添加空间条件控制。ControlNet 锁定了已准备好生产的大型扩散模型,并复用其通过数十亿张图像进行预训练的深度且强大的编码层,作为学习各种条件控制的强大骨干网络。该神经网络架构通过“零卷积”(zero convolutions,零初始化的卷积层)连接,这些卷积层从零开始逐步增加参数,并确保有害噪声不会影响微调。我们使用 Stable Diffusion 测试了各种条件控制,例如,边缘、深度、分割、人体姿势等,使用单个或多个条件,有或没有提示词。我们表明,ControlNet 的训练在小型(<5 万)和大型(>1 百万)数据集上都很稳健。广泛的结果表明,ControlNet 可以促进更广泛的应用来控制图像扩散模型。
您可以从 🤗 Diffusers Hub 组织找到其他更小的 Stable Diffusion XL (SDXL) ControlNet 检查点,并在 Hub 上浏览 社区训练的 检查点。
🧪 许多 SDXL ControlNet 检查点都是实验性的,并且仍有很大的改进空间。请随时打开 Issue,并给我们留下关于如何改进的反馈!
如果您没有看到您感兴趣的检查点,您可以使用我们的 训练脚本 训练您自己的 SDXL ControlNet。
StableDiffusionXLControlNetPipeline
class diffusers.StableDiffusionXLControlNetPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_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 指导的文本到图像生成管道。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP 适配器
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → StableDiffusionPipelineOutput 或 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]]
): ControlNet 输入条件,为unet
生成提供指导。如果类型指定为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]
, 可选) — 自定义时间步,用于支持在其set_timesteps
方法中使用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
进行采样来生成 latents 张量。 - 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_embeds
将从negative_prompt
输入参数生成。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为(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 编码器也会尝试识别输入图像的内容。建议使用 3.0 到 5.0 之间的guidance_scale
值。 - 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.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成一个图像,该图像看起来像是从crops_coords_top_left
位置向下“裁剪”出来的。通常,将crops_coords_top_left
设置为 (0, 0) 可以获得良好且居中的图像。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像的所需高度和宽度。如果未指定,则默认为(height, width)
。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - negative_original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 为了基于特定的图像分辨率对生成过程进行负面调节。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面调节。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面调节。 在大多数情况下,它应与target_size
相同。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。 值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。 - 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
。
管道的调用函数用于生成。
示例
>>> # !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://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )
>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5 # 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
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的 prompt - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的 prompt 或 prompts。 如果未定义,则prompt
将在两个文本编码器中使用 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器引导 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须改为传递negative_prompt_embeds
。 当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts,将发送到tokenizer_2
和text_encoder_2
。 如果未定义,则negative_prompt
将在两个文本编码器中使用 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的 pooled 文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从prompt
输入参数生成 pooled 文本 embeddings。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面 pooled 文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从negative_prompt
输入参数生成 pooled negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 lora 缩放比例。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。 值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。
将 prompt 编码为文本编码器隐藏状态。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionXLControlNetImg2ImgPipeline
class diffusers.StableDiffusionXLControlNetImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_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 类的分词器。 - 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 library 来为输出图像添加水印。 如果未定义,则如果已安装该软件包,则默认为 True,否则将不使用水印。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征; 用作safety_checker
的输入。
使用带有 ControlNet 引导的 Stable Diffusion XL 进行图像到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。 查看超类文档,了解库为所有 pipeline 实现的通用方法(例如下载或保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- load_ip_adapter() 用于加载 IP 适配器
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 num_inference_steps: int = 50 guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → StableDiffusionPipelineOutput 或 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]]
): 初始图像将用作图像生成过程的起点。 也可接受图像潜在表示 (latents) 作为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
的尺寸。如果传递了 height 和/或 width,则会根据它们调整image
的大小。如果在 init 中指定了多个 ControlNet,则必须将图像作为列表传递,以便列表的每个元素都可以正确批量处理,以输入到单个 controlnet。 - height (
int
, 可选, 默认为 control_image 的尺寸) — 生成图像的像素高度。 对于 stabilityai/stable-diffusion-xl-base-1.0 和未在低分辨率下专门微调的检查点,低于 512 像素的任何值都无法很好地工作。 - width (
int
, 可选, 默认为 control_image 的尺寸) — 生成图像的像素宽度。 对于 stabilityai/stable-diffusion-xl-base-1.0 和未在低分辨率下专门微调的检查点,低于 512 像素的任何值都无法很好地工作。 - 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) — 无分类器扩散引导 中定义的引导缩放。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://arxiv.org/abs/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
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负池化文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从negative_prompt
输入参数生成池化 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP-Adapter 的预生成图像嵌入。 它应该是一个列表,其长度与 IP 适配器的数量相同。 每个元素都应是一个形状为(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 字典,如果指定,则作为self.processor
下定义的AttentionProcessor
的参数传递,定义在 diffusers.models.attention_processor 中。 - 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.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成一个图像,该图像看起来像是从位置crops_coords_top_left
向下“裁剪”的。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得良好居中的图像。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像的所需高度和宽度。如果未指定,则默认为(height, width)
。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - negative_original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 用于基于特定图像分辨率对生成过程进行负面调节。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) — 用于基于特定裁剪坐标对生成过程进行负面调节。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 用于基于目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应与target_size
相同。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - aesthetic_score (
float
, 可选, 默认为 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学分数。 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中进行了解释。 - negative_aesthetic_score (
float
, 可选, 默认为 2.5) — 作为 SDXL 微调的一部分,在 https://huggingface.ac.cn/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
StableDiffusionPipelineOutput 如果 return_dict
为 True,否则为包含输出图像的 tuple
。
调用管道进行生成时调用的函数。
示例
>>> # 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
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
参数
- prompt (
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
) — 是否使用无分类器引导 - 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
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 一个 lora 缩放比例,如果加载了 LoRA 层,它将应用于文本编码器的所有 LoRA 层。 - clip_skip (
int
, 可选) — 计算提示词嵌入时,从 CLIP 模型中跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。
将 prompt 编码为文本编码器隐藏状态。
StableDiffusionXLControlNetInpaintPipeline
class diffusers.StableDiffusionXLControlNetInpaintPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
- text_encoder (
CLIPTextModel
) — 冻结的文本编码器。 Stable Diffusion XL 使用 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 类的分词器。 - unet (UNet2DConditionModel) — 条件 U-Net 架构,用于对编码后的图像潜在空间进行去噪。
- scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,对编码后的图像潜在空间进行去噪。 可以是 DDIMScheduler, LMSDiscreteScheduler, 或 PNDMScheduler 之一。
使用 Stable Diffusion XL 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。 查看超类文档,了解库为所有 pipeline 实现的通用方法(例如下载或保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP 适配器
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 num_inference_steps: int = 50 denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **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
,或表示图像批次的张量,将被修复(inpainted),即 图像的部分将被mask_image
遮罩,并根据prompt
重新绘制。 - mask_image (
PIL.Image.Image
) —Image
,或表示图像批次的张量,用于遮罩image
。 蒙版中的白色像素将被重新绘制,而黑色像素将被保留。 如果mask_image
是 PIL 图像,则在使用前会将其转换为单通道(亮度)。 如果它是张量,则应包含一个颜色通道 (L) 而不是 3 个,因此预期的形状应为(B, H, W, 1)
。 - 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
,则不对图像和 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` 将被忽略。当此 pipeline 集成到“去噪器混合”多 pipeline 设置中时,denoising_start
参数尤其有益,如 精炼图像输出 中详述。 - denoising_end (
float
, 可选) — 当指定时,确定在有意提前终止之前要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量噪声(大约最后 20% 的时间步仍需要去噪),并且应该由后继 pipeline 进行去噪,该 pipeline 的denoising_start
设置为 0.8,以便仅去噪 scheduler 的最后 20%。当此 pipeline 构成“去噪器混合”多 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]
, 可选) — 不引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
代替。当不使用指导时忽略(即,如果guidance_scale
小于1
,则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不引导图像生成的 prompt 或 prompts,将被发送到tokenizer_2
和text_encoder_2
。如果未定义,则negative_prompt
将在两个文本编码器中使用 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从negative_prompt
输入参数生成 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,则应包含负图像嵌入。如果未提供,则从ip_adapter_image
输入参数计算嵌入。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个 prompt 生成的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他 scheduler 将被忽略。 - generator (
torch.Generator
, 可选) — 一个或一组 torch 生成器,用于使生成具有确定性。 - latents (
torch.Tensor
, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompts 调整相同的生成。如果未提供,将通过使用提供的随机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
。 - original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 如果original_size
与target_size
不同,则图像将显示为缩小或放大。如果未指定,original_size
默认为(width, height)
。作为 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成一个看起来像是从位置crops_coords_top_left
向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来实现有利的、居中良好的图像。作为 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 对于大多数情况,target_size
应设置为生成图像的所需高度和宽度。如果未指定,它将默认为(width, height)
。作为 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。 - aesthetic_score (
float
, 可选, 默认为 6.0) — 用于通过影响正文本条件来模拟生成图像的美学分数。作为 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。 - negative_aesthetic_score (
float
, 可选, 默认为 2.5) — 作为 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。可用于通过影响负文本条件来模拟生成图像的美学分数。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。 - 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
参数传递。您将只能包含 pipeline 类的._callback_tensor_inputs
属性中列出的变量。
返回
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
或 tuple
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
如果 return_dict
为 True,否则为 tuple
。当返回元组时,第一个元素是包含生成图像的列表。
调用管道进行生成时调用的函数。
示例
>>> # !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
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
参数
- prompt (
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
) — 是否使用无分类器引导 - 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
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 lora 缩放值。 - clip_skip (
int
, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。
将 prompt 编码为文本编码器隐藏状态。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的输出类。