Diffusers documentation

LEDITS++

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

LEDITS++

LoRA

LEDITS++ 由 Manuel Brack、Felix Friedrich、Katharina Kornmeier、Linoy Tsaban、Patrick Schramowski、Kristian Kersting 和 Apolinário Passos 在 LEDITS++: Limitless Image Editing using Text-to-Image Models 中提出。

该论文的摘要如下:

文生图扩散模型因其仅凭文本输入即可生成高保真图像的惊人能力,近期备受关注。后续研究致力于挖掘并应用其能力,以实现真实的图像编辑。然而,现有的图生图方法往往效率低下、精度不足且通用性有限。它们要么需要耗时的微调,要么不必要地大幅偏离输入图像,要么不支持多个同时进行的编辑。为解决这些问题,我们提出了 LEDITS++,一种高效、通用且精确的文本驱动图像操控技术。LEDITS++ 新颖的逆向方法无需调参或优化,仅需少量扩散步骤即可生成高保真结果。其次,我们的方法支持多个同时进行的编辑,并且与架构无关。第三,我们采用了一种新颖的隐式掩码技术,将修改限制在相关的图像区域内。作为全面评估的一部分,我们提出了新颖的 TEdBench++ 基准。我们的结果展示了 LEDITS++ 的能力及其相较于先前方法的改进。项目页面位于 https://leditsplusplus-project.static.hf.space 。

您可以在项目页面上找到有关 LEDITS++ 的更多信息,并可在演示中试用。

由于当前 diffusers 中 DPMSolverMultistepScheduler 的实现存在一些向后兼容性问题,此 LEdits++ 实现无法再保证完美的反转。 该问题在实际应用场景中不太可能产生明显影响。不过,我们提供了一个保证完美反转的替代实现,位于专门的 GitHub 仓库 中。

我们提供基于不同预训练模型的两条独立流水线。

LEditsPPPipelineStableDiffusion

class diffusers.LEditsPPPipelineStableDiffusion

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )

参数

使用 LEDits++ 和 Stable Diffusion 进行文本图像编辑的 Pipeline。

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

__call__

< >

( negative_prompt: str | list[str] | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueediting_prompt: str | list[str] | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9user_mask: typing.Optional[torch.Tensor] = Nonesem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Trueattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0clip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple

参数

  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的反向提示词。当未使用引导时将被忽略(即当 guidance_scale 小于 1 时忽略)。
  • generator (torch.Generator,可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 LEditsPPDiffusionPipelineOutput 而不是普通元组。
  • editing_prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。通过将 editing_prompt = None 来重建图像。提示词的引导方向应通过 reverse_editing_direction 指定。
  • editing_prompt_embeds (torch.Tensor>,可选) — 用于引导图像生成的预计算嵌入。嵌入的引导方向应通过 reverse_editing_direction 指定。
  • negative_prompt_embeds (torch.Tensor,可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • reverse_editing_direction (bool 或 list[bool],可选,默认为 False) — 是否应增加或减少 editing_prompt 中对应提示词的影响。
  • edit_guidance_scale (float 或 list[float],可选,默认值为 5) — 用于引导图像生成的 guidance scale。如果以列表形式提供,其值应与 editing_prompt 对应。edit_guidance_scale 定义为 LEDITS++ Paper 中公式 12 的 s_e。
  • edit_warmup_steps (float 或 list[float],可选,默认为 10) — 每个提示词在应用引导之前所执行的扩散步数。
  • edit_cooldown_steps(float 或 list[float],可选,默认为 None)— 在应用引导之前,每个提示词所经历的扩散步数。
  • edit_threshold (float 或 list[float],可选,默认值为 0.9) — 引导的掩码阈值。该阈值应与被修改的图像区域成比例。 ‘edit_threshold’ 定义为 LEDITS++ 论文 中公式 12 的 ‘λ’。
  • user_mask (torch.Tensor, 可选) — 用户提供的掩码,用于对编辑过程进行更精细的控制。当 LEDITS++ 的隐式掩码无法满足用户偏好时,此参数非常有用。
  • sem_guidance(list[torch.Tensor],可选)— 在生成过程中应用的预生成引导向量列表。该列表的长度必须与 num_inference_steps 相对应。
  • use_cross_attn_mask (bool,默认为 False) — 是否使用交叉注意力掩码。当 use_intersect_mask 设置为 true 时,始终使用交叉注意力掩码。交叉注意力掩码定义为 LEDITS++ 论文 中公式 12 的 ‘M^1’。
  • use_intersect_mask (bool,默认为 True) — 是否将掩码项计算为交叉注意力掩码与由噪声估计推导出的掩码的交集。交叉注意力掩码定义为 LEDITS++ 论文 中公式 12 的 ‘M^1’,由噪声估计推导出的掩码定义为 ‘M^2’。
  • attn_store_steps (list[int],可选) — 在 AttentionStore 中存储注意力图的步骤。仅用于可视化目的。
  • store_averaged_over_steps (bool,默认为 True) — 是否将 ‘attn_store_steps’ 对应的注意力图在扩散步骤上进行平均后存储。如果为 False,则每个步骤的注意力图将分别存储。仅用于可视化目的。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。
  • guidance_rescale (float,可选,默认值为 0.0) — 来自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的 guidance rescale 因子。当使用零终端 SNR 时,guidance rescale 因子应可修复过度曝光问题。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs 将包含由 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (list,可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含流水线类 ._callback_tensor_inputs 属性中列出的变量。

返回值

LEditsPPDiffusionPipelineOutput 或 tuple

LEditsPPDiffusionPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the safety_checker`.

用于编辑的 pipeline 调用函数。在此之前必须调用 invert() 方法。编辑操作将始终针对最后反转的图像执行。

示例:

>>> import torch

>>> from diffusers import LEditsPPPipelineStableDiffusion
>>> from diffusers.utils import load_image

>>> pipe = LEditsPPPipelineStableDiffusion.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")

>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/cherry_blossom.png"
>>> image = load_image(img_url).resize((512, 512))

>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.1)

>>> edited_image = pipe(
...     editing_prompt=["cherry blossom"], edit_guidance_scale=10.0, edit_threshold=0.75
... ).images[0]

反转

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale: float = 3.5num_inversion_steps: int = 30skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput

参数

  • image (PipelineImageInput) — 待编辑图像的输入。多张输入图像必须具有相同的宽高比。
  • source_prompt (str,默认为 "") — 用于描述输入图像的提示词,将在反转过程中用于引导。如果 source_prompt 为 "",则禁用引导。
  • source_guidance_scale (float,默认为 3.5) — 反转过程中的引导强度。
  • num_inversion_steps (int,默认为 30) — 在丢弃初始的 skip 步之后,实际执行的总反转步数。
  • skip (float,默认为 0.15) — 在反转及后续生成过程中将被忽略的初始步数比例。值越低,对输入图像的改动越强。skip 必须介于 0 和 1 之间。
  • generator (torch.Generator,可选) — 用于使反转过程确定性的 torch.Generator。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • height (int,可选,默认为 None) — 预处理图像的高度。如果为 None,将使用 get_default_height_width() 获取默认高度。
  • width (int, optional, defaults to None) -- The width in preprocessed. If None, will use get_default_height_width() to get the default width.
  • resize_mode (str, 可选, 默认为 default) — 缩放模式,可以是 default 或 fill 之一。如果为 default,则将图像缩放以适应指定的宽度和高度,且可能不保持原始宽高比。如果为 fill,则将图像缩放以适应指定的宽度和高度,保持宽高比,然后将图像居中于该尺寸内,并用图像数据填充空白区域。如果为 crop,则将图像缩放以适应指定的宽度和高度,保持宽高比,然后将图像居中于该尺寸内,并裁剪掉多余部分。请注意,fill 和 crop 这两种 resize_mode 仅支持 PIL 图像输入。
  • crops_coords (list[tuple[int, int, int, int]],可选,默认为 None) — 批次中每张图片的裁剪坐标。如果为 None,则不对图片进行裁剪。

输出将包含调整大小后的输入图像以及相应的 VAE 重建结果。

用于图像反转的 pipeline 函数,如 LEDITS++ 论文 中所述。如果调度器设置为 DDIMScheduler,则将执行 edit-friendly DPDM 提出的反转方法。

encode_prompt

< >

( devicenum_images_per_promptenable_edit_guidancenegative_prompt = Noneediting_prompt = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

参数

  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • enable_edit_guidance (bool) — 是否执行编辑,还是直接重建输入图像
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • editing_prompt (str 或 list[str],可选) — 要编码的编辑提示。如果未定义,则必须改为传入 editing_prompt_embeds。
  • editing_prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。

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

LEditsPPPipelineStableDiffusionXL

class diffusers.LEditsPPPipelineStableDiffusionXL

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler | diffusers.schedulers.scheduling_ddim.DDIMSchedulerimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = None )

参数

使用 LEDits++ 和 Stable Diffusion XL 进行文本图像编辑的 Pipeline。

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

此外,pipeline 还继承了以下加载方法:

以及以下保存方法:

  • LoRA:loaders.StableDiffusionXLPipeline.save_lora_weights

__call__

< >

( denoising_end: float | None = Nonenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0crops_coords_top_left: tuple[int, int] = (0, 0)target_size: tuple[int, int] | None = Noneediting_prompt: str | list[str] | None = Noneediting_prompt_embeddings: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9sem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Falseuser_mask: typing.Optional[torch.Tensor] = Noneattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Trueclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple

参数

  • denoising_end (float, 可选) — 如果指定,则确定在有意提前终止之前,总去噪过程中需要完成的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量噪声,具体程度由调度器选择的离散时间步决定。理想情况下,当此流水线作为“去噪器混合”多流水线设置的一部分时,应使用 denoising_end 参数,如 [**Refining the Image
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput,可选): 用于配合 IP Adapter 使用的可选图像输入。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • guidance_rescale (float, optional, defaults to 0.7) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawed guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. Guidance rescale factor should fix overexposure when using zero terminal SNR.
  • crops_coords_top_left (tuple[int],可选,默认为 (0, 0)) — crops_coords_top_left 可用于生成一张看似从 crops_coords_top_left 位置向下裁剪的图像。通常将 crops_coords_top_left 设置为 (0, 0) 即可获得构图良好、居中效果理想的图像。这是 SDXL 微条件的一部分,详见 https://huggingface.co/papers/2307.01952 中的第 2.2 节。
  • target_size (tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,则默认为 (width, height)。这是 https://huggingface.co/papers/2307.01952 第 2.2 节中所述 SDXL 微条件化的一部分。
  • editing_prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。通过将 editing_prompt = None 来重建图像。提示词的引导方向应通过 reverse_editing_direction 指定。
  • editing_prompt_embeddings (torch.Tensor, 可选) — 预生成的编辑文本嵌入。可用于轻松调整文本输入,例如 提示词权重。 如果未提供,editing_prompt_embeddings 将从 editing_prompt 输入参数生成。
  • editing_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化编辑文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,editing_prompt_embeddings 将从 editing_prompt 输入参数生成。
  • reverse_editing_direction (bool 或 list[bool],可选,默认为 False) — 是否应增加或减少 editing_prompt 中对应提示词的影响。
  • edit_guidance_scale (float 或 list[float],可选,默认值为 5) — 用于引导图像生成的 guidance scale。如果以列表形式提供,其值应与 editing_prompt 对应。edit_guidance_scale 定义为 LEDITS++ Paper 中公式 12 的 s_e。
  • edit_warmup_steps (float 或 list[float],可选,默认为 10) — 每个提示词在应用引导之前所执行的扩散步数。
  • edit_cooldown_steps(float 或 list[float],可选,默认为 None)— 在应用引导之前,每个提示词所执行的扩散步数。
  • edit_threshold (float 或 list[float],可选,默认值为 0.9) — 引导的掩码阈值。该阈值应与被修改的图像区域成比例。 ‘edit_threshold’ 定义为 LEDITS++ 论文 中公式 12 的 ‘λ’。
  • sem_guidance(list[torch.Tensor],可选)— 在生成过程中应用的预生成引导向量列表。该列表的长度必须与 num_inference_steps 相对应。
  • use_cross_attn_mask — 是否使用交叉注意力掩码。当 use_intersect_mask 设置为 true 时,始终使用交叉注意力掩码。交叉注意力掩码定义为 LEDITS++ 论文 中公式 12 的 ‘M^1’。
  • use_intersect_mask — 是否将掩码项计算为交叉注意力掩码与由噪声估计导出的掩码的交集。交叉注意力掩码定义为 LEDITS++ 论文 中公式 12 的 ‘M^1’,由噪声估计导出的掩码定义为 ‘M^2’。
  • user_mask — 用户提供的掩码,用于对编辑过程进行更精细的控制。当 LEDITS++ 的隐式掩码无法满足用户偏好时,此参数非常有用。
  • attn_store_steps — 在 AttentionStore 中存储注意力图的步数。仅用于可视化目的。
  • store_averaged_over_steps — 是否将 'attn_store_steps' 对应的注意力图在扩散步骤上进行平均后存储。如果为 False,则每个步骤的注意力图会分别存储。仅用于可视化目的。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs 将包含由 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (list,可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含流水线类 ._callback_tensor_inputs 属性中列出的变量。

返回值

LEditsPPDiffusionPipelineOutput 或 tuple

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

用于编辑的 pipeline 调用函数。在此之前必须调用 invert() 方法。编辑操作将始终针对最后反转的图像执行。

示例:

>>> import torch

>>> from diffusers import LEditsPPPipelineStableDiffusionXL
>>> from diffusers.utils import load_image

>>> pipe = LEditsPPPipelineStableDiffusionXL.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")

>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
>>> image = load_image(img_url).resize((1024, 1024))

>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.2)

>>> edited_image = pipe(
...     editing_prompt=["tennis ball", "tomato"],
...     reverse_editing_direction=[True, False],
...     edit_guidance_scale=[5.0, 10.0],
...     edit_threshold=[0.9, 0.85],
... ).images[0]

反转

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale = 3.5negative_prompt: str = Nonenegative_prompt_2: str = Nonenum_inversion_steps: int = 50skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecrops_coords_top_left: tuple[int, int] = (0, 0)num_zero_noise_steps: int = 3cross_attention_kwargs: dict[str, typing.Any] | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput

参数

  • image (PipelineImageInput) — 待编辑图像的输入。多张输入图像必须具有相同的宽高比。
  • source_prompt (str,默认为 "") — 用于描述输入图像的提示词,将在反转过程中用于引导。如果 source_prompt 为 "",则禁用引导。
  • source_guidance_scale (float,默认为 3.5) — 反转过程中的引导强度。
  • 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_inversion_steps (int,默认为 50) — 在丢弃初始的 skip 步之后,实际执行的总反转步数。
  • skip (float,默认为 0.15) — 在反转及后续生成过程中将被忽略的初始步数比例。值越低,对输入图像的改动越强。skip 必须介于 0 和 1 之间。
  • generator (torch.Generator,可选) — 用于使反转过程确定性的 torch.Generator。
  • 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 节。
  • num_zero_noise_steps (int,默认为 3) — 不会重新加噪当前图像的末尾扩散步数。如果未将任何步数设为零,SD-XL 与 DPMSolverMultistepScheduler 组合使用时会产生噪声伪影。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。

输出将包含调整大小后的输入图像以及相应的 VAE 重建结果。

用于图像反转的 pipeline 函数,如 LEDITS++ 论文 中所述。如果调度器设置为 DDIMScheduler,则将执行 edit-friendly DPDM 提出的反转方法。

encode_prompt

< >

( device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1negative_prompt: str | None = Nonenegative_prompt_2: str | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = Noneenable_edit_guidance: bool = Trueediting_prompt: str | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )

参数

  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • negative_prompt (str 或 list[str],可选) — 用于引导图像生成的负面提示词。如果未定义,则必须传入 negative_prompt_embeds。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
  • enable_edit_guidance (bool) — 是否引导模型朝向编辑提示词。
  • editing_prompt (str 或 list[str],可选) — 要编码的编辑提示。如果未定义且 ‘enable_edit_guidance’ 为 True,则必须改为传入 editing_prompt_embeds。
  • editing_prompt_embeds (torch.Tensor, 可选) — 预生成的编辑文本嵌入。可用于轻松调整文本输入,例如 提示词加权。 如果未提供且 ‘enable_edit_guidance’ 为 True,则 editing_prompt_embeds 将从 editing_prompt 输入参数生成。
  • editing_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的编辑池化文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,将从 editing_prompt 输入参数生成池化的 editing_pooled_prompt_embeds。

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

get_guidance_scale_embedding

< >

( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
  • embedding_dim (int,可选,默认为 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype,可选,默认为 torch.float32) — 生成嵌入的数据类型。

返回值

torch.Tensor

形状为 (len(w), embedding_dim) 的嵌入向量。

参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

LEditsPPDiffusionPipelineOutput

类 diffusers.pipelines.LEditsPPDiffusionPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )

参数

  • images (list[PIL.Image.Image] 或 np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected (list[bool]) — 一个列表,指示对应的生成图像是否包含“不适合工作场所”(nsfw)内容;如果无法执行安全检查,则为 None。

LEdits++ 扩散流水线的输出类。

LEditsPPInversionPipelineOutput

class diffusers.pipelines.LEditsPPInversionPipelineOutput

< >

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

参数

  • input_images (list[PIL.Image.Image] 或 np.ndarray) — 裁剪并调整大小后的输入图像列表,作为长度为 batch_size 的 PIL 图像,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • vae_reconstruction_images (list[PIL.Image.Image] 或 np.ndarray) — 所有输入图像的 VAE 重建结果,以 PIL 图像列表形式返回,长度为 batch_size;或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。

LEdits++ 扩散流水线的输出类。

Update on GitHub