Diffusers 文档

LEDITS++

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LEDITS++

LEDITS++ 在论文 LEDITS++: Limitless Image Editing using Text-to-Image Models 中被提出,作者是 Manuel Brack, Felix Friedrich, Katharina Kornmeier, Linoy Tsaban, Patrick Schramowski, Kristian Kersting, Apolinário Passos。

该论文的摘要如下:

文本到图像扩散模型最近因其惊人的能力而受到越来越多的关注,它们仅从文本输入即可生成高保真图像。随后的研究工作旨在利用其能力并将其应用于真实图像编辑。然而,现有的图像到图像方法通常效率低下、不精确且通用性有限。它们要么需要耗时的微调,要么不必要地 сильно 偏离输入图像,并且/或者缺乏对多个同步编辑的支持。为了解决这些问题,我们介绍了 LEDITS++,这是一种高效、通用且精确的文本图像操作技术。LEDITS++ 的新型反演方法无需调整或优化,只需几个扩散步骤即可生成高保真结果。其次,我们的方法支持多个同步编辑,并且与架构无关。第三,我们使用了一种新颖的隐式掩码技术,该技术将更改限制在相关的图像区域。我们提出了新的 TEdBench++ 基准作为我们详尽评估的一部分。我们的结果证明了 LEDITS++ 的能力及其相对于先前方法的改进。项目页面可在 https://leditsplusplus-project.static.hf.space 获取。

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

由于当前 diffusers 实现的 [DPMSolverMultistepScheduler](/docs/diffusers/v0.32.2/en/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler) 存在一些向后兼容性问题,LEdits++ 的此实现不再能保证完美的图像反演。这个问题不太可能对实际应用用例产生任何明显的影响。但是,我们提供了一个替代实现,它在一个专门的 [GitHub 仓库](https://github.com/ml-research/ledits_pp) 中保证了完美的图像反演。

我们提供了两个基于不同预训练模型的不同 pipeline。

LEditsPPPipelineStableDiffusion

class diffusers.LEditsPPPipelineStableDiffusion

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

参数

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

此模型继承自 DiffusionPipeline,并构建于 StableDiffusionPipeline 之上。 查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

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

参数

  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • generator (torch.Generator, 可选) — 一个或一组 torch generator(s),用于使生成具有确定性。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。 在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 LEditsPPDiffusionPipelineOutput 而不是普通元组。
  • editing_prompt (strList[str], 可选) — 用于引导图像生成的 prompt 或 prompts。 图像通过设置 editing_prompt = None 来重建。 prompt 的 guidance 方向应通过 reverse_editing_direction 指定。
  • editing_prompt_embeds (torch.Tensor>, 可选) — 预先计算的嵌入,用于引导图像生成。 嵌入的 guidance 方向应通过 reverse_editing_direction 指定。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。 可用于轻松调整文本输入(prompt 权重)。 如果未提供,则 negative_prompt_embedsnegative_prompt 输入参数生成。
  • reverse_editing_direction (boolList[bool], 可选, 默认为 False) — editing_prompt 中对应的 prompt 是应该增加还是减少。
  • edit_guidance_scale (floatList[float], 可选, 默认为 5) — 用于引导图像生成的 Guidance scale。 如果以列表形式提供,则值应与 editing_prompt 对应。 edit_guidance_scale 定义为 LEDITS++ 论文 的公式 12 中的 s_e
  • edit_warmup_steps (floatList[float], 可选, 默认为 10) — guidance 将不应用的扩散步数(对于每个 prompt)。
  • edit_cooldown_steps (floatList[float], 可选, 默认为 None) — guidance 将不再应用的扩散步数(对于每个 prompt)。
  • edit_threshold (floatList[float], 可选, 默认为 0.9) — guidance 的 masking 阈值。 阈值应与修改的图像区域成比例。 ‘edit_threshold’ 定义为 LEDITS++ 论文 的公式 12 中的 ‘λ’。
  • user_mask (torch.Tensor, 可选) — 用户提供的 mask,用于更好地控制编辑过程。 当 LEDITS++ 的隐式 mask 不能满足用户偏好时,这很有用。
  • 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) — 是否将掩码项计算为交叉注意力掩码和从噪声估计导出的掩码的交集。交叉注意力掩码定义为 ‘M^1’,从噪声估计导出的掩码定义为 LEDITS++ 论文 中公式 12 的 ‘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 的引导重缩放因子。当使用零终端 SNR 时,引导重缩放因子应修复过度曝光。
  • 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 属性中列出的变量。

返回

LEditsPPDiffusionPipelineOutputtuple

LEditsPPDiffusionPipelineOutput 如果 return_dict 为 True,否则为 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适合工作场所”(nsfw)内容。

用于编辑的管道调用函数。必须预先调用 invert() 方法。编辑将始终对最后反转的图像执行。

示例

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

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

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

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

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

invert

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.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._C.Generator] = None cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None height: typing.Optional[int] = None width: typing.Optional[int] = None resize_mode: typing.Optional[str] = 'default' crops_coords: typing.Optional[typing.Tuple[int, int, int, int]] = 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 必须介于 01 之间。
  • 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, 可选, 默认为 None) -- 预处理的宽度。如果为 None, 将使用 get_default_height_width() 获取默认宽度。
  • resize_mode (str, 可选, 默认为 default) — 调整大小模式,可以是 defaultfill 之一。如果为 default,将调整图像大小以适应指定的宽度和高度,并且可能不保持原始宽高比。如果为 fill,将调整图像大小以适应指定的宽度和高度,保持宽高比,然后在尺寸内居中图像,并使用图像数据填充空白。如果为 crop,将调整图像大小以适应指定的宽度和高度,保持宽高比,然后在尺寸内居中图像,并裁剪多余部分。请注意,仅 PIL 图像输入支持调整大小模式 fillcrop
  • crops_coords (List[Tuple[int, int, int, int]], 可选, 默认为 None) — 批次中每个图像的裁剪坐标。如果为 None,则不会裁剪图像。

返回

LEditsPPInversionPipelineOutput

输出将包含调整大小后的输入图像和各自的 VAE 重建。

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

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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

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

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

LEditsPPPipelineStableDiffusionXL

class diffusers.LEditsPPPipelineStableDiffusionXL

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: typing.Union[diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler, diffusers.schedulers.scheduling_ddim.DDIMScheduler] image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = 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 (DPMSolverMultistepSchedulerDDIMScheduler) — 与 unet 结合使用的调度器,用于对编码的图像潜在空间进行去噪。可以是 DPMSolverMultistepSchedulerDDIMScheduler 之一。如果传递任何其他调度器,它将自动设置为 DPMSolverMultistepScheduler
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "True") — 负面提示嵌入是否应强制始终设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 为输出图像添加水印。如果未定义,如果已安装该软件包,则默认为 True,否则将不使用水印。

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

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

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

以及以下保存方法

  • LoRA: loaders.StableDiffusionXLPipeline.save_lora_weights

__call__

< >

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

参数

  • denoising_end (float, 可选) — 如果指定,则确定在有意提前终止之前要完成的去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量的噪声,具体取决于调度器选择的离散时间步长。“denoising_end”参数应在当此pipeline构成“混合去噪器”多pipeline设置的一部分时使用,如 [**Refining the Image
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds 来代替。当不使用 guidance 时会被忽略 (即,如果 guidance_scale 小于 1,则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成的提示或提示列表,将发送到 tokenizer_2text_encoder_2。如果未定义,则 negative_prompt 将在两个文本编码器中都使用。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP 适配器一起使用的可选图像输入。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通的元组。
  • callback (Callable, 可选) — 将在推理期间每 callback_steps 步调用的函数。该函数将被调用,参数如下: callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — callback 函数将被调用的频率。如果未指定,则将在每个步骤调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给在 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.0) — 由 Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的 Guidance 重新缩放因子。guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为 φ。当使用零终端 SNR 时,Guidance 重新缩放因子应修复过度曝光。
  • crops_coords_top_left (Tuple[int, int], 可选, 默认为 (0, 0)) — crops_coords_top_left 可用于生成从位置 crops_coords_top_left 向下“裁剪”的图像。通常通过将 crops_coords_top_left 设置为 (0, 0) 来获得良好的、居中对齐的图像。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int, int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的 height 和 width。如果未指定,则默认为 (width, height)。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • editing_prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。图像通过设置 editing_prompt = None 来重建。提示的引导方向应通过 reverse_editing_direction 指定。
  • editing_prompt_embeddings (torch.Tensor, 可选) — 预生成的编辑文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 editing_prompt 输入参数生成 editing_prompt_embeddings。
  • editing_pooled_prompt_embeddings (torch.Tensor, 可选) — 预生成的池化编辑文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 editing_prompt 输入参数生成 editing_prompt_embeddings。
  • reverse_editing_direction (boolList[bool], 可选, 默认为 False) — editing_prompt 中相应的提示是应该增加还是减少。
  • edit_guidance_scale (floatList[float], 可选, 默认为 5) — 用于引导图像生成的 Guidance 比例。如果作为列表提供,则值应与 editing_prompt 相对应。edit_guidance_scaleLEDITS++ Paper 的公式 12 中定义为 s_e
  • edit_warmup_steps (intList[int], 可选, 默认为 0) — 不应用 guidance 的扩散步骤数(对于每个提示)。
  • edit_cooldown_steps (intList[int], 可选, 默认为 None) — 在之后不再应用 guidance 的扩散步骤数(对于每个提示)。
  • edit_threshold (floatList[float], 可选, 默认为 0.9) — guidance 的掩蔽阈值。阈值应与修改的图像区域成比例。“edit_threshold”在 LEDITS++ Paper 的公式 12 中定义为 ‘λ’。
  • sem_guidance (List[torch.Tensor], 可选) — 要在生成时应用的预生成 guidance 向量列表。列表的长度必须与 num_inference_steps 相对应。
  • use_cross_attn_mask — 是否使用交叉注意力掩码。当 use_intersect_mask 设置为 true 时,始终使用交叉注意力掩码。交叉注意力掩码在 LEDITS++ paper 的公式 12 中定义为 ‘M^1’。
  • use_intersect_mask — 掩蔽项是否计算为交叉注意力掩码与噪声估计导出的掩码的交集。交叉注意力掩码定义为 ‘M^1’,噪声估计导出的掩码定义为 LEDITS++ 论文 方程式 12 中的 ‘M^2’。
  • user_mask — 用户提供的掩码,以便更好地控制编辑过程。当 LEDITS++ 的隐式掩码不符合用户偏好时,这很有用。
  • attn_store_steps — 在 AttentionStore 中存储注意力图的步骤。仅用于可视化目的。
  • store_averaged_over_steps — ‘attn_store_steps’ 的注意力图是否在扩散步骤中取平均值后存储。如果为 False,则每个步骤的注意力图将单独存储。仅用于可视化目的。
  • clip_skip (int, optional) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, optional) — 在推理过程中每个去噪步骤结束时调用的函数。该函数调用时会带有以下参数:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)callback_kwargs 将包含 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (List, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含在管道类的 ._callback_tensor_inputs 属性中列出的变量。

返回

LEditsPPDiffusionPipelineOutputtuple

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

用于编辑的管道调用函数。必须预先调用 invert() 方法。编辑将始终针对最后反演的图像执行。

示例

>>> import torch
>>> import PIL
>>> import requests
>>> from io import BytesIO

>>> from diffusers import LEditsPPPipelineStableDiffusionXL

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


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


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

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

invert

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.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._C.Generator] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) num_zero_noise_steps: int = 3 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) LEditsPPInversionPipelineOutput

参数

  • image (PipelineImageInput) — 要编辑的图像的输入。多个输入图像必须具有相同的宽高比。
  • source_prompt (str, defaults to "") — 描述输入图像的提示,该提示将用于反演过程中的引导。如果 source_prompt"",则禁用引导。
  • source_guidance_scale (float, defaults to 3.5) — 反演过程中的引导强度。
  • negative_prompt (str or List[str], optional) — 不希望引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (str or List[str], optional) — 不希望引导图像生成的提示或提示列表,将发送到 tokenizer_2text_encoder_2。如果未定义,则 negative_prompt 将在两个文本编码器中使用
  • num_inversion_steps (int, defaults to 50) — 在丢弃初始 skip 步骤后执行的总反演步骤数。
  • skip (float, defaults to 0.15) — 将在反演和后续生成中被忽略的初始步骤部分。值越低将导致对输入图像的更改越强。skip 必须介于 01 之间。
  • generator (torch.Generator, optional) — 用于使反演具有确定性的 torch.Generator
  • crops_coords_top_left (Tuple[int], optional, defaults to (0, 0)) — crops_coords_top_left 可用于生成看起来像是从 crops_coords_top_left 位置向下“裁剪”的图像。通常通过将 crops_coords_top_left 设置为 (0, 0) 来获得良好的居中图像。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • num_zero_noise_steps (int, defaults to 3) — 不会对当前图像重新添加噪声的最终扩散步骤数。如果未将任何步骤设置为零,则 SD-XL 与 DPMSolverMultistepScheduler 结合使用会产生噪声伪影。
  • cross_attention_kwargs (dict, optional) — kwargs 字典,如果指定,则作为 AttentionProcessor 传递,定义在 diffusers.models.attention_processorself.processor 下。

返回

LEditsPPInversionPipelineOutput

输出将包含调整大小后的输入图像和各自的 VAE 重建。

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

encode_prompt

< >

( device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None negative_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 enable_edit_guidance: bool = True editing_prompt: typing.Optional[str] = None editing_prompt_embeds: typing.Optional[torch.Tensor] = None editing_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )

参数

  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • negative_prompt (str or List[str], optional) — 不希望引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds
  • negative_prompt_2 (strList[str], 可选) — 不希望图像生成受其引导的提示或提示语,将被发送到 tokenizer_2text_encoder_2。 如果未定义,则 negative_prompt 将在两个文本编码器中都使用。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示词权重。 如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。 如果未提供,池化的 negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 lora 缩放比例。
  • clip_skip (int, 可选) — 在计算提示词嵌入时,从 CLIP 中跳过的层数。 值为 1 表示将使用预最终层的输出进行提示词嵌入的计算。
  • enable_edit_guidance (bool) — 是否引导向编辑提示。
  • editing_prompt (strList[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_pooled_prompt_embeds 将从 editing_prompt 输入参数生成。

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 生成具有指定引导比例的嵌入向量,以随后丰富时间步长嵌入。
  • 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

class diffusers.pipelines.LEditsPPDiffusionPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )

参数

  • 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++ Diffusion 管道的输出类。

LEditsPPInversionPipelineOutput

class diffusers.pipelines.LEditsPPInversionPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] vae_reconstruction_images: typing.Union[typing.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 重建列表,为长度为 batch_size 的 PIL 图像,或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。

LEdits++ Diffusion 管道的输出类。

< > 在 GitHub 上更新