Diffusers 文档

图像修复

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

图像修复

LoRA

Stable Diffusion 模型也可应用于图像修复,通过提供蒙版和文本提示,您可以使用 Stable Diffusion 编辑图像的特定部分。

提示

建议将此管道与经过专门微调用于图像修复的检查点一起使用,例如 runwayml/stable-diffusion-inpainting。默认的文本到图像 Stable Diffusion 检查点,例如 stable-diffusion-v1-5/stable-diffusion-v1-5 也兼容,但性能可能较差。

务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用管道组件!

如果您有兴趣将官方检查点用于某个任务,请探索 CompVisRunwayStability AI Hub 组织!

StableDiffusionInpaintPipeline

diffusers.StableDiffusionInpaintPipeline

< >

( vae: typing.Union[diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL] text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )

参数

  • vae ([AutoencoderKL, AsymmetricAutoencoderKL]) — 变分自编码器 (VAE) 模型,用于编码和解码图像到潜在表示。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于去噪编码图像潜在的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 与 unet 结合使用的调度器,用于对编码图像潜在进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 用于评估生成图像是否可能具有攻击性或有害的分类模块。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

用于使用 Stable Diffusion 进行文本引导图像修复的管道。

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

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = 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 masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 negative_prompt: 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 output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: 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元组

参数

  • prompt (strList[str], 可选) — 引导图像生成的提示词。如果未定义,则需要传递 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image、numpy 数组或张量,表示要进行图像修复的图像批次(使用 mask_image 遮罩图像的哪些部分,并根据 prompt 重新绘制)。对于 numpy 数组和 pytorch 张量,预期值范围在 [0, 1] 之间。如果它是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果它是 numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜在值作为 image,但如果直接传递潜在值,则不会再次进行编码。
  • mask_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image、numpy 数组或张量,表示用于遮罩 image 的图像批次。蒙版中的白色像素将被重新绘制,而黑色像素将保留。如果 mask_image 是 PIL 图像,则在使用前将其转换为单通道(亮度)。如果它是 numpy 数组或 pytorch 张量,则应包含一个颜色通道 (L) 而不是 3 个,因此 pytorch 张量的预期形状为 (B, 1, H, W)(B, H, W)(1, H, W)(H, W)。对于 numpy 数组,预期形状为 (B, H, W, 1)(B, H, W)(H, W, 1)(H, W)
  • 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, 可选, 默认为 1.0) — 表示转换参考 image 的程度。必须介于 0 和 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的全部迭代次数。值为 1 基本上会忽略 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。此参数受 strength 调制。
  • timesteps (List[int], 可选) — 使用支持其 set_timesteps 方法中 timesteps 参数的调度器进行去噪过程的自定义时间步。如果未定义,则将使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 使用支持其 set_timesteps 方法中 sigmas 参数的调度器进行去噪过程的自定义 σ 值。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的引导尺度值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时启用引导尺度。
  • negative_prompt (strList[str], 可选) — 引导图像生成中不包含内容的提示词。如果未定义,则需要传递 negative_prompt_embeds。当不使用引导时 (guidance_scale < 1) 忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在值,用作图像生成的输入。可用于通过不同的提示调整相同的生成。如果未提供,则通过使用提供的随机 generator 进行采样生成一个潜在张量。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则文本嵌入将从 `prompt` 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,`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.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput,而不是普通的元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为 `self.processor` 中定义的 `AttentionProcessor` 的参数传递。
  • clip_skip (int, 可选) — 计算提示词嵌入时跳过的 CLIP 层数。值为 1 表示使用倒数第二层的输出计算提示词嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,具有以下参数:`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` 属性中列出的变量。

返回

StableDiffusionPipelineOutputtuple

如果 `return_dict` 为 `True`,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

用于生成的管道的调用函数。

示例

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

>>> from diffusers import StableDiffusionInpaintPipeline


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


>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))

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

>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]

enable_attention_slicing

< >

( slice_size: typing.Union[int, str, NoneType] = 'auto' )

参数

  • slice_size (strint, 可选, 默认为 "auto") — 当设置为 "auto" 时,将注意力头的输入减半,因此注意力将分两步计算。如果设置为 "max",则通过每次只运行一个切片来节省最大内存。如果提供一个数字,则使用 attention_head_dim // slice_size 个切片。在这种情况下,`attention_head_dim` 必须是 `slice_size` 的倍数。

启用切片注意力计算。启用此选项后,注意力模块将输入张量分割成切片,分多步计算注意力。对于多个注意力头,计算按顺序在每个头进行。这有助于节省一些内存,但会略微降低速度。

⚠️ 如果您已经在使用 PyTorch 2.0 的 `scaled_dot_product_attention` (SDPA) 或 xFormers,请不要启用注意力切片。这些注意力计算已经非常节省内存,因此您无需启用此功能。如果您启用注意力切片与 SDPA 或 xFormers 一起使用,可能会导致严重的速度下降!

示例

>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]

disable_attention_slicing

< >

( )

禁用切片注意力计算。如果之前调用过 enable_attention_slicing,则注意力将一步计算完成。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

参数

  • attention_op (Callable, 可选) — 覆盖默认的 None 运算符,用作 xFormers 的 memory_efficient_attention() 函数的 `op` 参数。

启用 xFormers 的内存高效注意力。启用此选项后,您将观察到更低的 GPU 内存使用量以及推理速度的潜在提升。训练期间的速度提升不保证。

⚠️ 当内存高效注意力和切片注意力同时启用时,内存高效注意力优先。

示例

>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)

disable_xformers_memory_efficient_attention

< >

( )

禁用 xFormers 的内存高效注意力。

load_textual_inversion

< >

( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[str, typing.List[str], NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )

参数

  • pretrained_model_name_or_path (stros.PathLikeList[str 或 os.PathLike]DictList[Dict]) — 可以是以下之一或它们的列表:

    • Hub 上托管的预训练模型的模型 ID 字符串(例如 sd-concepts-library/low-poly-hd-logos-icons)。
    • 包含文本反转权重的目录路径(例如 ./my_text_inversion_directory/)。
    • 包含文本反转权重的文件路径(例如 ./my_text_inversions.pt)。
    • 一个 torch state dict
  • token (strList[str], 可选) — 覆盖用于文本反转权重的 token。如果 `pretrained_model_name_or_path` 是一个列表,则 `token` 也必须是一个等长的列表。
  • text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器(clip-vit-large-patch14)。如果未指定,函数将使用 self.tokenizer。
  • tokenizer (CLIPTokenizer, 可选) — 用于文本标记化的 CLIPTokenizer。如果未指定,函数将使用 self.tokenizer。
  • weight_name (str, 可选) — 自定义权重文件的名称。应在以下情况使用:

    • 保存的文本反转文件为 🤗 Diffusers 格式,但以特定权重名称(例如 `text_inv.bin`)保存。
    • 保存的文本反转文件为 Automatic1111 格式。
  • cache_dir (Union[str, os.PathLike], 可选) — 如果不使用标准缓存,则下载的预训练模型配置的缓存目录路径。
  • force_download (bool, 可选, 默认为 False) — 是否强制(重新)下载模型权重和配置文件,如果存在则覆盖缓存版本。
  • proxies (Dict[str, str], 可选) — 按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用于每个请求。
  • local_files_only (bool, 可选, 默认为 False) — 是否只加载本地模型权重和配置文件。如果设置为 True,则模型不会从 Hub 下载。
  • hf_token (strbool, 可选) — 用作远程文件的 HTTP Bearer 授权的 token。如果为 True,则使用从 diffusers-cli login 生成的 token(存储在 ~/.huggingface 中)。
  • revision (str, 可选, 默认为 "main") — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。
  • subfolder (str, 可选, 默认为 "") — 模型文件在 Hub 或本地较大模型仓库中的子文件夹位置。
  • mirror (str, 可选) — 解决在中国下载模型时的可访问性问题的镜像源。我们不保证该源的及时性或安全性,您应该参考镜像站点获取更多信息。

将文本反转嵌入加载到 StableDiffusionPipeline 的文本编码器中(支持 🤗 Diffusers 和 Automatic1111 两种格式)。

示例

加载 🤗 Diffusers 格式的文本反转嵌入向量

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

要加载 Automatic1111 格式的文本反转嵌入向量,请务必先下载该向量(例如从 civitAI),然后加载该向量

本地

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

load_lora_weights

< >

( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name: typing.Optional[str] = None hotswap: bool = False **kwargs )

参数

  • pretrained_model_name_or_path_or_dict (stros.PathLikedict) — 参见 lora_state_dict()
  • adapter_name (str, 可选) — 用于引用已加载的适配器模型的适配器名称。如果未指定,将使用 `default_{i}`,其中 i 是正在加载的适配器总数。
  • low_cpu_mem_usage (bool, 可选) — 通过仅加载预训练的 LoRA 权重而不初始化随机权重来加快模型加载速度。
  • hotswap (bool, 可选) — 默认为 False。是否用新加载的适配器原地替换现有(LoRA)适配器。这意味着,不是加载额外的适配器,而是将现有适配器权重替换为新适配器的权重。这可以更快且更节省内存。然而,热插拔的主要优点是,当模型使用 torch.compile 编译时,加载新适配器不需要重新编译模型。使用热插拔时,传递的 `adapter_name` 应该是已加载适配器的名称。

    如果新适配器和旧适配器具有不同的秩和/或 LoRA alpha(即缩放),则在加载适配器之前需要调用一个额外的方法:

pretrained_model_name_or_path_or_dict 中指定的 LoRA 权重加载到 self.unetself.text_encoder 中。

所有 kwargs 都转发到 self.lora_state_dict

有关如何加载 state dict 的更多详细信息,请参阅 lora_state_dict()

有关如何将 state dict 加载到 self.unet 中的更多详细信息,请参阅 load_lora_into_unet()

有关如何将 state dict 加载到 self.text_encoder 中的更多详细信息,请参阅 load_lora_into_text_encoder()

save_lora_weights

< >

( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None text_encoder_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = True unet_lora_adapter_metadata = None text_encoder_lora_adapter_metadata = None )

参数

  • save_directory (stros.PathLike) — 保存 LoRA 参数的目录。如果不存在,则会创建。
  • unet_lora_layers (Dict[str, torch.nn.Module]Dict[str, torch.Tensor]) — 对应于 `unet` 的 LoRA 层状态字典。
  • text_encoder_lora_layers (Dict[str, torch.nn.Module]Dict[str, torch.Tensor]) — 对应于 `text_encoder` 的 LoRA 层状态字典。必须显式传递文本编码器 LoRA 状态字典,因为它来自 🤗 Transformers。
  • is_main_process (bool, 可选, 默认为 True) — 调用此过程是否为主过程。在分布式训练中,当您需要在所有过程中调用此函数时很有用。在这种情况下,仅在主过程中设置 `is_main_process=True` 以避免竞态条件。
  • save_function (Callable) — 用于保存状态字典的函数。在分布式训练中,当您需要将 torch.save 替换为其他方法时很有用。可以通过环境变量 DIFFUSERS_SAVE_MODE 进行配置。
  • safe_serialization (bool, 可选, 默认为 True) — 是否使用 `safetensors` 或传统 PyTorch 方式(带 `pickle`)保存模型。
  • unet_lora_adapter_metadata — 与 unet 相关的 LoRA 适配器元数据,将与状态字典一起序列化。
  • text_encoder_lora_adapter_metadata — 与文本编码器相关的 LoRA 适配器元数据,将与状态字典一起序列化。

保存对应于 UNet 和文本编码器的 LoRA 参数。

encode_prompt

< >

( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图片数量。
  • do_classifier_free_guidance (bool) — 是否使用无分类器指导。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即如果 guidance_scale 小于 1 时),此参数将被忽略。
  • 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 意味着将使用倒数第二层的输出计算提示词嵌入。

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

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

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

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

参数

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

Stable Diffusion 管道的输出类。

FlaxStableDiffusionInpaintPipeline

class diffusers.FlaxStableDiffusionInpaintPipeline

< >

( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_flax.FlaxDDIMScheduler, diffusers.schedulers.scheduling_pndm_flax.FlaxPNDMScheduler, diffusers.schedulers.scheduling_lms_discrete_flax.FlaxLMSDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep_flax.FlaxDPMSolverMultistepScheduler] safety_checker: FlaxStableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor dtype: dtype = <class 'jax.numpy.float32'> )

参数

  • vae (FlaxAutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码和解码为潜在表示。
  • text_encoder (FlaxCLIPTextModel) — 冻结文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (FlaxUNet2DConditionModel) — 用于对编码图像潜在表示进行去噪的 FlaxUNet2DConditionModel
  • scheduler (SchedulerMixin) — 用于与 unet 结合使用的调度器,以对编码图像潜在表示进行去噪。可以是 FlaxDDIMSchedulerFlaxLMSDiscreteSchedulerFlaxPNDMSchedulerFlaxDPMSolverMultistepScheduler 之一。
  • safety_checker (FlaxStableDiffusionSafetyChecker) — 用于评估生成图像是否可能被视为冒犯性或有害的分类模块。有关模型的潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

基于 Flax 的 Stable Diffusion 文本引导图像修复流水线。

🧪 这是一个实验性功能!

此模型继承自 FlaxDiffusionPipeline。请查看超类文档,了解所有流水线实现的通用方法(下载、保存、在特定设备上运行等)。

__call__

< >

( prompt_ids: Array mask: Array masked_image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 height: typing.Optional[int] = None width: typing.Optional[int] = None guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None return_dict: bool = True jit: bool = False ) FlaxStableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str]) — 用于引导图像生成的提示词。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度会变慢。此参数受 strength 调制。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导尺度值鼓励模型生成与文本 prompt 紧密相关的图像,但会以较低的图像质量为代价。当 guidance_scale > 1 时启用引导尺度。
  • latents (jnp.ndarray, 可选) — 从高斯分布中采样的预生成的噪声潜在表示,用作图像生成的输入。可用于使用不同提示词调整同一生成。如果未提供,将使用提供的随机 generator 采样生成潜在数组。
  • jit (bool, 默认为 False) — 是否运行生成和安全评分函数的 pmap 版本。

    此参数存在是因为 __call__ 尚未完全支持 pmap。它将在未来版本中移除。

  • return_dict (bool, 可选, 默认为 True) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通的元组。

返回

FlaxStableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 FlaxStableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不安全工作”(nsfw)内容的 bool 列表。

调用管道进行生成时调用的函数。

示例

>>> import jax
>>> import numpy as np
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> import PIL
>>> import requests
>>> from io import BytesIO
>>> from diffusers import FlaxStableDiffusionInpaintPipeline


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


>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))

>>> pipeline, params = FlaxStableDiffusionInpaintPipeline.from_pretrained(
...     "xvjiarui/stable-diffusion-2-inpainting"
... )

>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> prng_seed = jax.random.PRNGKey(0)
>>> num_inference_steps = 50

>>> num_samples = jax.device_count()
>>> prompt = num_samples * [prompt]
>>> init_image = num_samples * [init_image]
>>> mask_image = num_samples * [mask_image]
>>> prompt_ids, processed_masked_images, processed_masks = pipeline.prepare_inputs(
...     prompt, init_image, mask_image
... )
# shard inputs and rng

>>> params = replicate(params)
>>> prng_seed = jax.random.split(prng_seed, jax.device_count())
>>> prompt_ids = shard(prompt_ids)
>>> processed_masked_images = shard(processed_masked_images)
>>> processed_masks = shard(processed_masks)

>>> images = pipeline(
...     prompt_ids, processed_masks, processed_masked_images, params, prng_seed, num_inference_steps, jit=True
... ).images
>>> images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))

FlaxStableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput

< >

( images: ndarray nsfw_content_detected: typing.List[bool] )

参数

  • images (np.ndarray) — 数组形状为 (batch_size, height, width, num_channels) 的去噪图像。
  • nsfw_content_detected (List[bool]) — 列表,指示相应的生成图像是否包含“不安全工作”(nsfw)内容,如果无法执行安全检查,则为 None

Flax-based Stable Diffusion 管道的输出类。

替换

< >

( **updates )

返回一个新对象,用新值替换指定的字段。

< > 在 GitHub 上更新