Diffusers 文档
ControlNetUnion
并获取增强的文档体验
开始使用
ControlNetUnion
ControlNetUnionModel 是 ControlNet 为 Stable Diffusion XL 的一个实现。
ControlNet 模型由 xinsir6 在 ControlNetPlus 中引入。它支持多个条件输入而不会增加计算量。
我们设计了一个新的架构,可以在条件文本到图像生成中支持 10 种以上的控制类型,并且可以生成视觉效果与 Midjourney 相媲美的高分辨率图像。该网络基于原始 ControlNet 架构,我们提出了两个新模块来:1. 扩展原始 ControlNet,以使用相同的网络参数支持不同的图像条件。2. 支持多条件输入,而无需增加计算负载,这对于想要详细编辑图像的设计师尤其重要,不同的条件使用相同的条件编码器,无需添加额外的计算或参数。
StableDiffusionXLControlNetUnionPipeline
class diffusers.StableDiffusionXLControlNetUnionPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: ControlNetUnionModel 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 (ControlNetUnionModel
) -- 在去噪过程中为
unet` 提供额外的条件控制。 - 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
;否则不使用水印。
使用 ControlNet 指导的 Stable Diffusion XL 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
该 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 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 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 control_mode: typing.Union[int, typing.List[int], NoneType] = None 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'] ) → StableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词。如果未定义,则需要传递prompt_embeds
。 - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的提示词。如果未定义,则prompt
将在两个文本编码器中都使用。 - control_image (
PipelineImageInput
) — ControlNet 输入条件,为unet
生成提供指导。如果类型指定为torch.Tensor
,则按原样传递给 ControlNet。PIL.Image.Image
也可以接受为图像。输出图像的尺寸默认为image
的尺寸。如果传递了高度和/或宽度,则会相应地调整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]
, 可选) — 自定义 sigma 值,用于支持在其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]
, 可选) — 用于指导图像生成中不包含的内容的 prompt 或 prompts。如果未定义,则需要传递negative_prompt_embeds
。当不使用 guidance 时(guidance_scale < 1
),忽略此参数。 - negative_prompt_2 (
str
或List[str]
, 可选) — 用于指导图像生成中不包含的内容的 prompt 或 prompts。这被发送到tokenizer_2
和text_encoder_2
。如果未定义,则negative_prompt
将在两个文本编码器中使用。 - num_images_per_prompt (
int
, 可选,默认为 1) — 每个 prompt 生成的图像数量。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的、从高斯分布中采样的噪声 latents,用作图像生成的输入。可用于使用不同的 prompts 调整相同的生成。如果未提供,则会通过使用提供的随机generator
进行采样来生成 latents 张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(prompt 加权)。如果未提供,则文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(prompt 加权)。如果未提供,则negative_prompt_embeds
将从negative_prompt
输入参数生成。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入(prompt 加权)。如果未提供,则池化文本嵌入将从prompt
输入参数生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入(prompt 加权)。如果未提供,则池化negative_prompt_embeds
将从negative_prompt
输入参数生成。 - 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.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
) — 即使您删除所有 prompts,ControlNet 编码器也尝试识别输入图像的内容。建议guidance_scale
值在 3.0 到 5.0 之间。 - control_guidance_start (
float
或List[float]
, 可选,默认为 0.0) — ControlNet 开始应用的占总步骤的百分比。 - control_guidance_end (
float
或List[float]
, 可选, 默认为 1.0) — ControlNet 停止应用的总体步骤的百分比。 - original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 如果original_size
与target_size
不同,图像将显示为降采样或升采样。如果未指定,original_size
默认为(height, width)
。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成看起来像是从位置crops_coords_top_left
向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得有利的、居中良好的图像。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 对于大多数情况,target_size
应设置为生成图像的所需高度和宽度。如果未指定,它将默认为(height, width)
。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。 - negative_original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 为了基于特定的图像分辨率对生成过程进行负面调节。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面调节。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应与target_size
相同。作为 SDXL 微调的一部分,在 https://huggingface.co/papers/2307.01952 的第 2.2 节中进行了解释。有关更多信息,请参阅此问题线程: 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 controlnet_aux
>>> from controlnet_aux import LineartAnimeDetector
>>> from diffusers import StableDiffusionXLControlNetUnionPipeline, ControlNetUnionModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import torch
>>> prompt = "A cat"
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> # initialize the models and pipeline
>>> controlnet = ControlNetUnionModel.from_pretrained(
... "xinsir/controlnet-union-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetUnionPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0",
... controlnet=controlnet,
... vae=vae,
... torch_dtype=torch.float16,
... variant="fp16",
... )
>>> pipe.enable_model_cpu_offload()
>>> # prepare image
>>> processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
>>> controlnet_img = processor(image, output_type="pil")
>>> # generate image
>>> image = pipe(prompt, control_image=[controlnet_img], control_mode=[3], height=1024, width=1024).images[0]
encode_prompt
< 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
) — 是否使用 classifier free guidance - negative_prompt (
str
或List[str]
, 可选) — 不引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
代替。当不使用 guidance 时忽略(即,如果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
StableDiffusionXLControlNetUnionImg2ImgPipeline
class diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: ControlNetUnionModel 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 (ControlNetUnionModel) — 在去噪过程中为 unet 提供额外的条件控制。
- scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,对编码后的图像潜在空间进行去噪。 可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。 - requires_aesthetics_score (
bool
, 可选, 默认为"False"
) —unet
是否需要在推理期间传递aesthetic_score
条件。 另请参阅stabilityai/stable-diffusion-xl-refiner-1-0
的配置。 - force_zeros_for_empty_prompt (
bool
, 可选, 默认为"True"
) — 负面提示嵌入是否应强制始终设置为 0。 另请参阅stabilityai/stable-diffusion-xl-base-1-0
的配置。 - add_watermarker (
bool
, 可选) — 是否使用 invisible_watermark library 为输出图像添加水印。 如果未定义,如果已安装该软件包,则默认为 True,否则将不使用水印。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion XL 和 ControlNet 指导的图像到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。 查看超类文档,了解库为所有 pipeline 实现的通用方法(例如,下载或保存、在特定设备上运行等)。
该 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 control_mode: typing.Union[int, typing.List[int], NoneType] = None 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 or tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示或提示列表。 如果未定义,则必须传递prompt_embeds
。 代替。 - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的提示或提示列表。 如果未定义,则prompt
将在两个文本编码器中使用 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): 初始图像将用作图像生成过程的起点。 也可以接受图像潜在空间作为image
,如果直接传递潜在空间,则不会再次编码。 - control_image (
PipelineImageInput
) — ControlNet 的输入条件。 ControlNet 使用此输入条件来生成对 Unet 的引导。如果类型指定为torch.Tensor
,它将按原样传递给 ControlNet。PIL.Image.Image
也可以接受作为图像。输出图像的尺寸默认为image
的尺寸。如果传递了 height 和/或 width,则会根据它们调整image
的大小。如果在 init 中指定了多个 ControlNet,则必须将图像作为列表传递,以便可以正确地批量处理列表中的每个元素,以输入到单个 controlnet。 - height (
int
, optional, defaults to the size of control_image) — 生成图像的像素高度。对于 stabilityai/stable-diffusion-xl-base-1.0 和未在低分辨率上进行专门微调的检查点,低于 512 像素的任何高度都无法很好地工作。 - width (
int
, optional, defaults to the size of control_image) — 生成图像的像素宽度。对于 stabilityai/stable-diffusion-xl-base-1.0 和未在低分辨率上进行专门微调的检查点,低于 512 像素的任何宽度都无法很好地工作。 - strength (
float
, optional, defaults to 0.8) — 表示转换参考image
的程度。必须介于 0 和 1 之间。image
用作起点,strength
越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当strength
为 1 时,添加的噪声最大,并且去噪过程运行在num_inference_steps
中指定的完整迭代次数。值为 1 本质上会忽略image
。 - num_inference_steps (
int
, optional, defaults to 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲更慢的推理速度。 - guidance_scale (
float
, optional, defaults to 7.5) — Guidance scale(引导比例),定义在 Classifier-Free Diffusion Guidance 中。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - negative_prompt (
str
orList[str]
, optional) — 不引导图像生成的提示或提示列表。如果未定义,则必须传递negative_prompt_embeds
。当不使用 guidance 时忽略(即,如果guidance_scale
小于1
则忽略)。 - negative_prompt_2 (
str
orList[str]
, optional) — 不引导图像生成的提示或提示列表,将发送到tokenizer_2
和text_encoder_2
。如果未定义,则negative_prompt
将在两个文本编码器中都使用。 - num_images_per_prompt (
int
, optional, defaults to 1) — 每个提示要生成的图像数量。 - eta (
float
, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。 - generator (
torch.Generator
orList[torch.Generator]
, optional) — 用于使生成结果确定性的单个或列表 torch 生成器。 - latents (
torch.Tensor
, optional) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成潜变量张量。 - prompt_embeds (
torch.Tensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, optional) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput
, optional): 与 IP 适配器一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, optional) — IP 适配器的预生成图像嵌入。它应该是一个列表,其长度与 IP 适配器的数量相同。每个元素都应该是形状为(batch_size, num_images, emb_dim)
的张量。如果do_classifier_free_guidance
设置为True
,则应包含负面图像嵌入。如果未提供,则从ip_adapter_image
输入参数计算嵌入。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - cross_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processor 中self.processor
下定义的AttentionProcessor
。 - controlnet_conditioning_scale (
float
orList[float]
, optional, defaults to 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,会乘以controlnet_conditioning_scale
。如果在 init 中指定了多个 ControlNet,则可以将相应的比例设置为列表。 - guess_mode (
bool
, optional, defaults toFalse
) — 在此模式下,即使您删除所有提示,ControlNet 编码器也会尽力识别输入图像的内容。建议guidance_scale
在 3.0 到 5.0 之间。 - control_guidance_start (
float
orList[float]
, optional, defaults to 0.0) — ControlNet 开始应用的占总步骤的百分比。 - control_guidance_end (
float
或List[float]
, 可选, 默认为 1.0) — ControlNet 停止应用的步数百分比。 - original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 如果original_size
与target_size
不同,图像将看起来被缩小或放大。如果未指定,original_size
默认为(height, width)
。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成看起来像是从crops_coords_top_left
位置向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得良好、居中的图像。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像所需的 height 和 width。如果未指定,则默认为(height, width)
。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。 - negative_original_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 用于根据特定的图像分辨率对生成过程进行负面调节。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。更多信息,请参考此 issue 线程:https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) — 用于根据特定的裁剪坐标对生成过程进行负面调节。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。更多信息,请参考此 issue 线程:https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 用于根据目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应与target_size
相同。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。更多信息,请参考此 issue 线程:https://github.com/huggingface/diffusers/issues/4208。 - aesthetic_score (
float
, 可选, 默认为 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学评分。作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。 - negative_aesthetic_score (
float
, 可选, 默认为 2.5) — 作为 SDXL 微调的一部分,详见https://huggingface.co/papers/2307.01952的 2.2 节。可用于通过影响负面文本条件来模拟生成图像的美学评分。 - 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
StableDiffusionPipelineOutput 如果 return_dict
为 True,否则为包含输出图像的 tuple
。
调用管道进行生成时调用的函数。
示例
# !pip install controlnet_aux
from diffusers import (
StableDiffusionXLControlNetUnionImg2ImgPipeline,
ControlNetUnionModel,
AutoencoderKL,
)
from diffusers.utils import load_image
import torch
from PIL import Image
import numpy as np
prompt = "A cat"
# download an image
image = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
)
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
"brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionImg2ImgPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
controlnet=controlnet,
vae=vae,
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
# `enable_model_cpu_offload` is not recommended due to multiple generations
height = image.height
width = image.width
ratio = np.sqrt(1024.0 * 1024.0 / (width * height))
# 3 * 3 upscale correspond to 16 * 3 multiply, 2 * 2 correspond to 16 * 2 multiply and so on.
scale_image_factor = 3
base_factor = 16
factor = scale_image_factor * base_factor
W, H = int(width * ratio) // factor * factor, int(height * ratio) // factor * factor
image = image.resize((W, H))
target_width = W // scale_image_factor
target_height = H // scale_image_factor
images = []
crops_coords_list = [
(0, 0),
(0, width // 2),
(height // 2, 0),
(width // 2, height // 2),
0,
0,
0,
0,
0,
]
for i in range(scale_image_factor):
for j in range(scale_image_factor):
left = j * target_width
top = i * target_height
right = left + target_width
bottom = top + target_height
cropped_image = image.crop((left, top, right, bottom))
cropped_image = cropped_image.resize((W, H))
images.append(cropped_image)
# set ControlNetUnion input
result_images = []
for sub_img, crops_coords in zip(images, crops_coords_list):
new_width, new_height = W, H
out = pipe(
prompt=[prompt] * 1,
image=sub_img,
control_image=[sub_img],
control_mode=[6],
width=new_width,
height=new_height,
num_inference_steps=30,
crops_coords_top_left=(W, H),
target_size=(W, H),
original_size=(W * 2, H * 2),
)
result_images.append(out.images[0])
new_im = Image.new("RGB", (new_width * scale_image_factor, new_height * scale_image_factor))
new_im.paste(result_images[0], (0, 0))
new_im.paste(result_images[1], (new_width, 0))
new_im.paste(result_images[2], (new_width * 2, 0))
new_im.paste(result_images[3], (0, new_height))
new_im.paste(result_images[4], (new_width, new_height))
new_im.paste(result_images[5], (new_width * 2, new_height))
new_im.paste(result_images[6], (0, new_height * 2))
new_im.paste(result_images[7], (new_width, new_height * 2))
new_im.paste(result_images[8], (new_width * 2, new_height * 2))
encode_prompt
< 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。如果未定义,则prompt
将用于两个文本编码器 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器 guidance - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt。如果未定义,则必须传递negative_prompt_embeds
。当不使用 guidance 时忽略(即,如果guidance_scale
小于1
则忽略)。 - negative_prompt_2 (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt,将发送到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 编码为文本编码器隐藏状态。
StableDiffusionXLControlNetUnionInpaintPipeline
class diffusers.StableDiffusionXLControlNetUnionInpaintPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: ControlNetUnionModel 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 实现的通用方法(例如,下载或保存、在特定设备上运行等)。
该 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]] = 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 control_mode: typing.Union[int, typing.List[int], NoneType] = None 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
,或表示将要进行图像修复的图像批次的张量,即 图像的部分将被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,以便它仅对调度器的最后 20% 进行去噪。 当此 pipeline 构成“去噪器混合”多 pipeline 设置的一部分时,应理想地利用 denoising_end 参数,如 优化图像输出 中详细说明。 - 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
- prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从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
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从negative_prompt
输入参数生成池化的 negative_prompt_embeds。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/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.co/papers/2307.01952 第 2.2 节中所述。 - crops_coords_top_left (
Tuple[int]
, 可选, 默认为 (0, 0)) —crops_coords_top_left
可用于生成从位置crops_coords_top_left
向下“裁剪”的图像。通常通过将crops_coords_top_left
设置为 (0, 0) 来获得有利的、居中良好的图像。SDXL 微调的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节中所述。 - target_size (
Tuple[int]
, 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size
应设置为生成图像的所需高度和宽度。如果未指定,它将默认为(width, height)
。SDXL 微调的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节中所述。 - aesthetic_score (
float
, 可选, 默认为 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学评分。SDXL 微调的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节中所述。 - negative_aesthetic_score (
float
, 可选, 默认为 2.5) — SDXL 微调的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节中所述。可用于通过影响负面文本条件来模拟生成图像的美学评分。 - clip_skip (
int
, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可选) — 在推理期间每个去噪步骤结束时调用的函数或PipelineCallback
或MultiPipelineCallbacks
的子类。使用以下参数:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包括callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您将只能包含管道类的._callback_tensor_inputs
属性中列出的变量。
返回值
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
或 tuple
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
如果 return_dict
为 True,否则为 tuple
。当返回元组时,第一个元素是包含生成图像的列表。
调用管道进行生成时调用的函数。
示例
from diffusers import StableDiffusionXLControlNetUnionInpaintPipeline, ControlNetUnionModel, AutoencoderKL
from diffusers.utils import load_image
import torch
import numpy as np
from PIL import Image
prompt = "A cat"
# download an image
image = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo.png"
).resize((1024, 1024))
mask = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo_mask.png"
).resize((1024, 1024))
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
"brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionInpaintPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
controlnet=controlnet,
vae=vae,
torch_dtype=torch.float16,
variant="fp16",
)
pipe.enable_model_cpu_offload()
controlnet_img = image.copy()
controlnet_img_np = np.array(controlnet_img)
mask_np = np.array(mask)
controlnet_img_np[mask_np > 0] = 0
controlnet_img = Image.fromarray(controlnet_img_np)
# generate image
image = pipe(prompt, image=image, mask_image=mask, control_image=[controlnet_img], control_mode=[7]).images[0]
image.save("inpaint.png")
encode_prompt
< 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 编码为文本编码器隐藏状态。