# LEDITS++

  

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](https://huggingface.co/papers/2311.16711) 中提出。

该论文的摘要如下：

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

> [!TIP]
> 您可以在[项目页面](https://leditsplusplus-project.static.hf.space/index.html)上找到有关 LEDITS++ 的更多信息，并可在[演示](https://huggingface.co/spaces/editing-images/leditsplusplus)中试用。

> [!WARNING]
> 由于当前 diffusers 中 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 的实现存在一些向后兼容性问题，此 LEdits++ 实现无法再保证完美的反转。该问题在实际应用场景中不太可能产生明显影响。不过，我们提供了一个保证完美反转的替代实现，位于专门的 [GitHub 仓库](https://github.com/ml-research/ledits_pp) 中。

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

## LEditsPPPipelineStableDiffusion[[diffusers.LEditsPPPipelineStableDiffusion]]

#### diffusers.LEditsPPPipelineStableDiffusion[[diffusers.LEditsPPPipelineStableDiffusion]]

```python
diffusers.LEditsPPPipelineStableDiffusion(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, requires_safety_checker: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py#L269)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/main/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器。Stable Diffusion 使用的是 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer))：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

unet ([UNet2DConditionModel](/docs/diffusers/main/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。

scheduler ([DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 或 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler))：用于与 `unet` 配合以去除编码图像潜变量噪声的调度器。可以是 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 或 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler) 之一。如果传入其他调度器，将自动设置为 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler)。

safety_checker (`StableDiffusionSafetyChecker`)：一个分类模块，用于评估生成的图像是否可能被视为冒犯性或有害内容。详情请参阅[模型卡片](https://huggingface.co/CompVis/stable-diffusion-v1-4)。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor))：用于从生成的图像中提取特征，并将其作为 `safety_checker` 输入的模型。

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

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)，并基于 [StableDiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline) 构建。有关为所有 pipeline 实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.LEditsPPPipelineStableDiffusion.__call__]]

```python
__call__(negative_prompt: str | list[str] | None = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, output_type: str | None = 'pil', return_dict: bool = True, editing_prompt: str | list[str] | None = None, editing_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, reverse_editing_direction: bool | list[bool] | None = False, edit_guidance_scale: float | list[float] | None = 5, edit_warmup_steps: int | list[int] | None = 0, edit_cooldown_steps: int | list[int] | None = None, edit_threshold: float | list[float] | None = 0.9, user_mask: typing.Optional[torch.Tensor] = None, sem_guidance: list[torch.Tensor] | None = None, use_cross_attn_mask: bool = False, use_intersect_mask: bool = True, attn_store_steps: list[int] | None = [], store_averaged_over_steps: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py#L720)

**参数：**

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。当未使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

generator (`torch.Generator`, *可选*) : 一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [LEditsPPDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.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)：用于引导图像生成的引导尺度。如果以列表形式提供，其值应与 `editing_prompt` 对应。`edit_guidance_scale` 定义为 [LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中公式 12 的 `s_e`。

edit_warmup_steps (`float` 或 `list[float]`，*可选*，默认为 10)：在生成过程中，前多少个扩散步骤（针对每个提示词）不应用引导。

edit_cooldown_steps (`float` 或 `list[float]`，*可选*，默认为 `None`)：在应用引导之前，每个提示词所执行的扩散步数。

edit_threshold (`float` 或 `list[float]`，*可选*，默认为 0.9)：引导的掩码阈值。该阈值应与被修改的图像区域成比例。[LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中公式 12 的 'λ' 即为 'edit_threshold'。

user_mask (`torch.Tensor`, *可选*) : 用户提供的掩码，用于更精细地控制编辑过程。当 LEDITS++ 的隐式掩码无法满足用户偏好时，此参数非常有用。

sem_guidance (`list[torch.Tensor]`，*可选*)：在生成过程中应用的预生成引导向量列表。列表长度必须与 `num_inference_steps` 相对应。

use_cross_attn_mask (`bool`，默认为 `False`)：是否使用交叉注意力掩码。当 use_intersect_mask 设置为 true 时，始终使用交叉注意力掩码。交叉注意力掩码定义为 [LEDITS++ 论文](https://huggingface.co/papers/2311.16711) 中公式 12 的 'M^1'。

use_intersect_mask (`bool`，默认为 `True`)：是否将掩码项计算为交叉注意力掩码与由噪声估计导出的掩码的交集。交叉注意力掩码定义为 [LEDITS++ 论文](https://huggingface.co/papers/2311.16711) 中公式 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`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `AttentionProcessor` 的参数传递。

guidance_rescale (`float`, *可选*，默认为 0.0) : 来自 [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) 的 guidance rescale 因子。当使用 zero terminal 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](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.LEditsPPDiffusionPipelineOutput) 或 `tuple`

[LEditsPPDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.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 `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the `safety_checker`.

用于编辑的 pipeline 调用函数。在此之前必须调用 [invert()](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.LEditsPPPipelineStableDiffusion.invert) 方法。编辑操作始终针对最后一次反转的图像执行。

示例：
```py
>>> 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]
```

#### 反转[[diffusers.LEditsPPPipelineStableDiffusion.invert]]

```python
invert(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.5, num_inversion_steps: int = 30, skip: float = 0.15, generator: typing.Optional[torch.Generator] = None, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, height: int | None = None, width: int | None = None, resize_mode: str | None = 'default', crops_coords: tuple[int, int, int, int] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py#L1223)

**参数：**

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`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `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`，则将图像调整大小以适应指定的宽度和高度，保持宽高比，然后将图像居中于该尺寸内，并裁剪掉多余部分。请注意，resize_mode `fill` 和 `crop` 仅支持 PIL 图像输入。

crops_coords (`list[tuple[int, int, int, int]]`，*可选*，默认为 `None`)：批次中每张图片的裁剪坐标。如果为 `None`，则不对图片进行裁剪。

**返回：** [LEditsPPInversionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.LEditsPPInversionPipelineOutput)

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

用于执行 [LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中所述图像反转的 pipeline 函数。如果调度器设置为 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，则将执行 [edit-friendly DPDM](https://huggingface.co/papers/2304.06140) 所提出的反转方法。

#### encode_prompt[[diffusers.LEditsPPPipelineStableDiffusion.encode_prompt]]

```python
encode_prompt(device, num_images_per_prompt, enable_edit_guidance, negative_prompt = None, editing_prompt = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, editing_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py#L521)

**参数：**

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[[diffusers.LEditsPPPipelineStableDiffusionXL]]

#### diffusers.LEditsPPPipelineStableDiffusionXL[[diffusers.LEditsPPPipelineStableDiffusionXL]]

```python
diffusers.LEditsPPPipelineStableDiffusionXL(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler | diffusers.schedulers.scheduling_ddim.DDIMScheduler, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py#L273)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/main/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 ([CLIPTextModelWithProjection](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModelWithProjection))：第二个冻结的文本编码器。Stable Diffusion XL 使用 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection) 的文本和池化部分，具体为 [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 变体。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer))：[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer_2 ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer))：第二个 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的 Tokenizer。

unet ([UNet2DConditionModel](/docs/diffusers/main/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。

scheduler ([DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 或 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler))：用于与 `unet` 配合以去除编码图像潜变量噪声的调度器。可以是 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 或 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler) 之一。如果传入其他调度器，将自动设置为 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler)。

force_zeros_for_empty_prompt (`bool`，*可选*，默认为 `"True"`)：是否强制将负提示嵌入始终设置为 0。另请参阅 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。

add_watermarker (`bool`，*可选*)：是否使用 [invisible_watermark 库](https://github.com/ShieldMnt/invisible-watermark/) 为输出图像添加水印。如果未定义，则当该包已安装时默认为 True，否则不使用水印。

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

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)，并基于 [StableDiffusionXLPipeline](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline) 构建。有关为所有管道实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

此外，pipeline 还继承了以下加载方法：
- *LoRA*：[LEditsPPPipelineStableDiffusionXL.load_lora_weights()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- *检查点*：[loaders.FromSingleFileMixin.from_single_file()](/docs/diffusers/main/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)

以及以下保存方法：
- *LoRA*：`loaders.StableDiffusionXLPipeline.save_lora_weights`

#### __调用__[[diffusers.LEditsPPPipelineStableDiffusionXL.__call__]]

```python
__call__(denoising_end: float | None = None, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_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, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, crops_coords_top_left: tuple = (0, 0), target_size: tuple[int, int] | None = None, editing_prompt: str | list[str] | None = None, editing_prompt_embeddings: typing.Optional[torch.Tensor] = None, editing_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, reverse_editing_direction: bool | list[bool] | None = False, edit_guidance_scale: float | list[float] | None = 5, edit_warmup_steps: int | list[int] | None = 0, edit_cooldown_steps: int | list[int] | None = None, edit_threshold: float | list[float] | None = 0.9, sem_guidance: list[torch.Tensor] | None = None, use_cross_attn_mask: bool = False, use_intersect_mask: bool = False, user_mask: typing.Optional[torch.Tensor] = None, attn_store_steps: list[int] | None = [], store_averaged_over_steps: bool = True, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py#L782)

**参数：**

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` 输入参数生成 pooled negative_prompt_embeds。

ip_adapter_image : (`PipelineImageInput`，*可选*)：用于配合 IP Adapter 使用的可选图像输入。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` 而不是普通元组。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `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](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). 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](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

target_size (`tuple[int]`，*可选*，默认值为 (1024, 1024))：在大多数情况下，应将 `target_size` 设置为生成图像所需的宽度和高度。如果未指定，则默认为 `(width, height)`。这是 [https://huggingface.co/papers/2307.01952](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)：用于引导图像生成的引导尺度。如果以列表形式提供，其值应与 `editing_prompt` 对应。`edit_guidance_scale` 定义为 [LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中公式 12 的 `s_e`。

edit_warmup_steps (`float` 或 `list[float]`，*可选*，默认为 10)：每个提示词中不应用引导的扩散步数。

edit_cooldown_steps (`float` 或 `list[float]`，*可选*，默认为 `None`)：在应用引导之前，每个提示词所执行的扩散步数。

edit_threshold (`float` 或 `list[float]`，*可选*，默认为 0.9)：引导的掩码阈值。该阈值应与被修改的图像区域成比例。[LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中公式 12 的 'λ' 即为 'edit_threshold'。

sem_guidance (`list[torch.Tensor]`，*可选*)：在生成过程中应用的预生成引导向量列表。列表长度必须与 `num_inference_steps` 相对应。

use_cross_attn_mask : 是否使用交叉注意力掩码。当 use_intersect_mask 设置为 true 时，始终使用交叉注意力掩码。交叉注意力掩码定义为 [LEDITS++ 论文](https://huggingface.co/papers/2311.16711) 中公式 12 的 'M^1'。

use_intersect_mask : 掩码项是否计算为交叉注意力掩码与由噪声估计推导出的掩码的交集。交叉注意力掩码定义为 [LEDITS++ 论文](https://huggingface.co/papers/2311.16711) 中公式 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](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.LEditsPPDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 True，则返回 [LEditsPPDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.LEditsPPDiffusionPipelineOutput)，否则返回一个 `tuple。当返回元组时，第一个元素是一个包含生成图像的列表。

用于编辑的 pipeline 调用函数。在此之前必须调用 [invert()](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.LEditsPPPipelineStableDiffusionXL.invert) 方法。编辑操作始终针对最后一次反转的图像执行。

示例：
```py
>>> 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]
```

#### 反转[[diffusers.LEditsPPPipelineStableDiffusionXL.invert]]

```python
invert(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.5, negative_prompt: str = None, negative_prompt_2: str = None, num_inversion_steps: int = 50, skip: float = 0.15, generator: typing.Optional[torch.Generator] = None, crops_coords_top_left: tuple = (0, 0), num_zero_noise_steps: int = 3, cross_attention_kwargs: dict[str, typing.Any] | None = None, height: int | None = None, width: int | None = None, resize_mode: str | None = 'default', crops_coords: tuple[int, int, int, int] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py#L1414)

**参数：**

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`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

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](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。

num_zero_noise_steps (`int`，默认为 `3`)：最终扩散步数，这些步骤不会对当前图像重新加噪。如果未将步数设为零，SD-XL 与 [DPMSolverMultistepScheduler](/docs/diffusers/main/zh/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 组合使用时会产生噪声伪影。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

**返回：** [LEditsPPInversionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/ledits_pp#diffusers.pipelines.LEditsPPInversionPipelineOutput)

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

用于执行 [LEDITS++ 论文](https://huggingface.co/papers/2301.12247) 中所述图像反转的 pipeline 函数。如果调度器设置为 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，则将执行 [edit-friendly DPDM](https://huggingface.co/papers/2304.06140) 所提出的反转方法。

#### encode_prompt[[diffusers.LEditsPPPipelineStableDiffusionXL.encode_prompt]]

```python
encode_prompt(device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, negative_prompt: str | None = None, negative_prompt_2: str | None = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None, enable_edit_guidance: bool = True, editing_prompt: str | None = None, editing_prompt_embeds: typing.Optional[torch.Tensor] = None, editing_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py#L399)

**参数：**

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` 输入参数生成 pooled 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[[diffusers.LEditsPPPipelineStableDiffusionXL.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py#L696)

**参数：**

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]]

#### diffusers.pipelines.LEditsPPDiffusionPipelineOutput[[diffusers.pipelines.LEditsPPDiffusionPipelineOutput]]

```python
diffusers.pipelines.LEditsPPDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_output.py#L10)

**参数：**

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[[diffusers.pipelines.LEditsPPInversionPipelineOutput]]

#### diffusers.pipelines.LEditsPPInversionPipelineOutput[[diffusers.pipelines.LEditsPPInversionPipelineOutput]]

```python
diffusers.pipelines.LEditsPPInversionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, vae_reconstruction_images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ledits_pp/pipeline_output.py#L28)

**参数：**

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++ 扩散流水线的输出类。

