Diffusers 文档
ControlNet 与 Stable Diffusion XL
并获得增强的文档体验
开始使用
ControlNet 与 Stable Diffusion XL
ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《为文本到图像扩散模型添加条件控制》 中提出。
通过 ControlNet 模型,您可以提供额外的控制图像来调整和控制 Stable Diffusion 生成。例如,如果您提供深度图,ControlNet 模型将生成一张保留深度图空间信息的图像。这是一种更灵活、更准确的图像生成控制方式。
论文摘要如下:
我们提出了 ControlNet,一种用于为大型预训练文本到图像扩散模型添加空间条件控制的神经网络架构。ControlNet 锁定生产级大型扩散模型,并重用其经过数十亿图像预训练的深层、稳健的编码层作为强大的骨干网络,以学习多样化的条件控制。该神经网络架构通过“零卷积”(零初始化卷积层)连接,这些层逐步从零开始增长参数,并确保不会有害的噪声影响微调。我们使用 Stable Diffusion 测试了各种条件控制,例如边缘、深度、分割、人体姿态等,可以使用单个或多个条件,带或不带提示词。我们展示了 ControlNet 的训练在小(<50k)和大(>1m)数据集上均表现出稳健性。大量结果表明,ControlNet 可以促进图像扩散模型的更广泛应用。
您可以在 🤗 Diffusers Hub 组织中找到其他较小的 Stable Diffusion XL (SDXL) ControlNet 检查点,并在 Hub 上浏览 社区训练的 检查点。
🧪 许多 SDXL ControlNet 检查点仍处于实验阶段,还有很大的改进空间。欢迎随时提出 问题 并向我们提供改进建议!
如果您没有找到您感兴趣的检查点,可以使用我们的 训练脚本 训练您自己的 SDXL ControlNet。
StableDiffusionXLControlNetPipeline
class diffusers.StableDiffusionXLControlNetPipeline
< 源代码 >( 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__
< 源代码 >( 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]]
): 用于为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]
, 可选) — 用于去噪过程的自定义时间步长,适用于支持在其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) — 较高的引导比例值鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时,启用引导比例。 - 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_embeds
将从negative_prompt
输入参数生成。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器配合使用的可选图像输入。 - 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 编码器也会尝试识别输入图像的内容。建议使用介于 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 跳过的层数。值为 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
。
用于生成的管道的调用函数。
示例
>>> # !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_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_embeds
将从negative_prompt
输入参数生成。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从prompt
输入参数生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化negative_prompt_embeds
将从negative_prompt
输入参数生成。 - lora_scale (
float
, 可选) — 将应用于文本编码器所有 LoRA 层的 LoRA 比例(如果已加载 LoRA 层)。 - clip_skip (
int
, 可选) — 计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
将提示编码为文本编码器隐藏状态。
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 库 为输出图像添加水印。如果未定义,如果已安装该包,则默认为 True,否则不使用水印器。 - feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的
CLIPImageProcessor
;用作safety_checker
的输入。
使用 Stable Diffusion XL 和 ControlNet 引导的图像到图像生成管道。
此模型继承自 DiffusionPipeline。有关库为所有管道(例如下载或保存、在特定设备上运行等)实现的通用方法,请查阅超类文档。
该管道还继承了以下加载方法
- 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]]
): 初始图像将用作图像生成过程的起始点。如果直接传递潜在表示,也可以接受图像潜在表示作为image
,它将不会再次编码。 - control_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): ControlNet 的输入条件。ControlNet 使用此输入条件为 Unet 生成引导。如果类型指定为torch.Tensor
,则按原样传递给 ControlNet。PIL.Image.Image
也可以作为图像接受。输出图像的尺寸默认为image
的尺寸。如果传递了高度和/或宽度,则image
会根据它们进行调整大小。如果在初始化中指定了多个 ControlNet,则图像必须作为列表传递,以便列表的每个元素都可以正确批处理以输入到单个 ControlNet。 - height (
int
, 可选, 默认为 control_image 的大小) — 生成图像的高度(像素)。对于 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) — 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
输入参数生成负文本嵌入。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从negative_prompt
输入参数生成池化负文本嵌入。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP 适配器配合使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — 预生成的 IP-Adapter 图像嵌入。它应该是一个列表,长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,它应该包含负图像嵌入。如果未提供,嵌入将从ip_adapter_image
输入参数计算。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则传递给 diffusers.models.attention_processor 中定义的self.processor
下的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可选, 默认为 1.0) — controlnet 的输出在添加到原始 unet 中的残差之前乘以controlnet_conditioning_scale
。如果在初始化中指定了多个 ControlNet,则可以将其相应的比例设置为列表。 - guess_mode (
bool
, 可选, 默认为False
) — 在此模式下,即使您删除了所有提示,ControlNet 编码器也会尽力识别输入图像的内容。建议guidance_scale
在 3.0 到 5.0 之间。 - control_guidance_start (
float
或List[float]
, 可选, 默认为 0.0) — controlnet 开始应用的步骤总数的百分比。 - control_guidance_end (
float
或List[float]
, 可选, 默认为 1.0) — controlnet 停止应用的步骤总数的百分比。 - original_size (
Tuple[int]
, optional, defaults to (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]
, optional, defaults to (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]
, optional, defaults to (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像的所需高度和宽度。如果未指定,它将默认为(height, width)
。这是 SDXL 微条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。 - negative_original_size (
Tuple[int]
, optional, defaults to (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]
, optional, defaults to (0, 0)) — 根据特定裁剪坐标对生成过程进行负面条件化。这是 SDXL 微条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。更多信息请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 根据目标图像分辨率对生成过程进行负面条件化。在大多数情况下,它应该与target_size
相同。这是 SDXL 微条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。更多信息请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208。 - aesthetic_score (
float
, optional, defaults to 6.0) — 通过影响正向文本条件来模拟生成图像的美学分数。这是 SDXL 微条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。 - negative_aesthetic_score (
float
, optional, defaults to 2.5) — 这是 SDXL 微条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节。可用于通过影响负向文本条件来模拟生成图像的美学分数。 - clip_skip (
int
, optional) — 在计算提示嵌入时,从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, optional) — 在推理过程中,每个去噪步骤结束时调用的函数或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
, optional) —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
orList[str]
, optional) — 要编码的提示 - prompt_2 (
str
orList[str]
, optional) — 要发送到tokenizer_2
和text_encoder_2
的提示。如果未定义,prompt
将在两个文本编码器中使用。 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用分类器自由引导 - negative_prompt (
str
orList[str]
, optional) — 不用于引导图像生成的提示。如果未定义,则必须传递negative_prompt_embeds
。当不使用引导时(即guidance_scale
小于1
时),此参数将被忽略。 - negative_prompt_2 (
str
orList[str]
, optional) — 不用于引导图像生成,要发送到tokenizer_2
和text_encoder_2
的提示。如果未定义,negative_prompt
将在两个文本编码器中使用。 - prompt_embeds (
torch.Tensor
, optional) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 预先生成的负向文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从negative_prompt
输入参数生成负向文本嵌入。 - pooled_prompt_embeds (
torch.Tensor
, optional) — 预先生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从prompt
输入参数生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, optional) — 预先生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化负向文本嵌入将从negative_prompt
输入参数生成。 - lora_scale (
float
, optional) — 将应用于文本编码器所有 LoRA 层的 LoRA 缩放因子(如果加载了 LoRA 层)。 - clip_skip (
int
, optional) — 在计算提示嵌入时,从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
将提示编码为文本编码器隐藏状态。
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 进行文本到图像生成的管道。
此模型继承自 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 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
orList[str]
, optional) — 用于引导图像生成的提示。如果未定义,则必须传递prompt_embeds
。 - prompt_2 (
str
orList[str]
, optional) — 要发送到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) 而不是 3 个,因此预期形状为(B, H, W, 1)
。 - height (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。 - width (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。 - padding_mask_crop (
int
, optional, defaults toNone
) — 应用于图像和遮罩的裁剪边缘大小。如果为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 将被忽略。denoising_start
参数特别适用于将此管道集成到“去噪器混合”多管道设置中,详细信息请参见精炼图像输出。 - denoising_end (
float
, 可选) — 指定时,确定在有意提前终止去噪过程之前要完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。结果,返回的样本仍将保留大量的噪声(大约需要调度器最后 20% 的时间步),并且应由denoising_start
设置为 0.8 的后续管道进行去噪,以便它只去噪调度器最后 20% 的时间步。当此管道作为“去噪器混合”多管道设置的一部分时,应理想地使用 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
输入参数生成。 - ip_adapter_image — (
PipelineImageInput
, 可选): 用于 IP Adapters 的可选图像输入。 - 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
输入参数生成。 - 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 字典,如果指定,将作为self.processor
中定义的AttentionProcessor
的参数传入 diffusers.models.attention_processor。 - 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 的层数。值为 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
。返回元组时,第一个元素是生成的图像列表。
调用管道进行生成时调用的函数。
示例
>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> from PIL import Image
>>> import numpy as np
>>> import torch
>>> init_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((1024, 1024))
>>> generator = torch.Generator(device="cpu").manual_seed(1)
>>> mask_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((1024, 1024))
>>> def make_canny_condition(image):
... image = np.array(image)
... image = cv2.Canny(image, 100, 200)
... image = image[:, :, None]
... image = np.concatenate([image, image, image], axis=2)
... image = Image.fromarray(image)
... return image
>>> control_image = make_canny_condition(init_image)
>>> controlnet = ControlNetModel.from_pretrained(
... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> image = pipe(
... "a handsome man with ray-ban sunglasses",
... num_inference_steps=20,
... generator=generator,
... eta=1.0,
... image=init_image,
... mask_image=mask_image,
... control_image=control_image,
... ).images[0]
encode_prompt
< 源文件 >( prompt: 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
输入参数生成。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化文本嵌入将根据prompt
输入参数生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,负向池化提示词嵌入将根据negative_prompt
输入参数生成。 - lora_scale (
float
, 可选) — 一个 LoRA 比例,如果加载了 LoRA 层,它将应用于文本编码器的所有 LoRA 层。 - clip_skip (
int
, 可选) — 在计算提示词嵌入时要跳过 CLIP 的层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。
将提示编码为文本编码器隐藏状态。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< 源文件 >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的输出类。