Diffusers 文档

图像到图像

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

图像到图像

LoRA

Stable Diffusion 模型还可以通过传递文本提示和初始图像来应用于图像到图像生成,以调节新图像的生成。

StableDiffusionImg2ImgPipeline 使用 Chenlin Meng、Yutong He、Yang Song、Jiaming Song、Jiajun Wu、Jun-Yan Zhu、Stefano Ermon 在 SDEdit: Guided Image Synthesis and Editing with Stochastic Differential Equations 中提出的扩散去噪机制。

论文摘要如下:

引导式图像合成使用户能够以最小的努力创建和编辑照片级图像。主要挑战在于平衡对用户输入(例如,手绘彩色笔触)的忠实度和合成图像的真实感。现有的基于 GAN 的方法试图通过条件 GAN 或 GAN 逆向来达到这种平衡,这具有挑战性,并且通常需要针对单个应用程序额外的训练数据或损失函数。为了解决这些问题,我们引入了一种新的图像合成和编辑方法,随机微分编辑 (SDEdit),它基于扩散模型生成先验,通过随机微分方程 (SDE) 迭代去噪来合成逼真图像。给定带有任何类型用户输入的图像,SDEdit 首先向输入添加噪声,然后通过 SDE 先验对生成的图像进行去噪,以提高其真实感。SDEdit 不需要特定于任务的训练或逆向,并且可以自然地实现真实感和忠实度之间的平衡。根据一项人类感知研究,SDEdit 在图像合成和编辑以及图像合成等多个任务中,在真实感方面比最先进的基于 GAN 的方法高出 98.09%,在整体满意度方面高出 91.72%。

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

StableDiffusionImg2ImgPipeline

class diffusers.StableDiffusionImg2ImgPipeline

< >

( vae: AutoencoderKL 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) — 变分自动编码器(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 strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: typing.Optional[float] = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = 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 ) StableDiffusionPipelineOutputtuple

参数

  • 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 数组或表示图像批次的张量,用作起点。对于 numpy 数组和 pytorch 张量,预期值范围在 [0, 1] 之间。如果它是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果它是 numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜在空间作为 image,但如果直接传递潜在空间,则不会再次编码。
  • strength (float, 可选, 默认为 0.8) — 表示参考 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 参数的调度器进行去噪过程的自定义 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
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选):用于IP Adapter的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — 预生成的IP-Adapter图像嵌入。它应该是一个列表,长度与IP-adapter的数量相同。每个元素都应该是一个形状为 (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 字典,如果指定,将作为 op 参数传递给 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_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是布尔值列表,指示相应的生成的图像是否包含“不适合工作”(nsfw)内容。

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

示例

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

>>> from diffusers import StableDiffusionImg2ImgPipeline

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

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))

>>> prompt = "A fantasy landscape, trending on artstation"

>>> images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
>>> images[0].save("fantasy_landscape.png")

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 或 xFormers 的 scaled_dot_product_attention (SDPA),请不要启用注意力切片。这些注意力计算已经非常内存高效,因此您无需启用此功能。如果您将注意力切片与 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状态字典
  • 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")

from_single_file

< >

( pretrained_model_link_or_path **kwargs )

参数

  • pretrained_model_link_or_path (stros.PathLike, 可选) — 可以是以下之一:

    • Hub上的.ckpt文件链接(例如"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt")。
    • 包含所有管道权重的文件路径。
  • torch_dtype (strtorch.dtype, 可选) — 覆盖默认的 torch.dtype,并以另一种数据类型加载模型。
  • force_download (bool, 可选,默认为 False) — 是否强制(重新)下载模型权重和配置文件,覆盖现有缓存版本。
  • cache_dir (Union[str, os.PathLike], 可选) — 如果不使用标准缓存,则下载的预训练模型配置的缓存目录路径。
  • proxies (Dict[str, str], 可选) — 一个字典,包含按协议或端点使用的代理服务器,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用于每个请求。
  • local_files_only (bool, 可选,默认为 False) — 是否只加载本地模型权重和配置文件。如果设置为 True,模型将不会从 Hub 下载。
  • token (strbool, 可选) — 用作远程文件HTTP bearer授权的token。如果为 True,则使用 diffusers-cli login 生成的token(存储在 ~/.huggingface 中)。
  • revision (str, 可选,默认为 "main") — 要使用的特定模型版本。它可以是分支名称、标签名称、提交ID或Git允许的任何标识符。
  • original_config_file (str, 可选) — 用于训练模型的原始配置文件路径。如果未提供,配置文件将从检查点文件推断。
  • config (str, 可选) — 可以是以下之一:

    • Hub上预训练管道的仓库ID(例如CompVis/ldm-text2im-large-256)。
    • 包含Diffusers格式管道组件配置的目录路径(例如./my_pipeline_directory/)。
  • disable_mmap (‘bool’, 可选,默认为 ‘False’) — 加载 Safetensors 模型时是否禁用mmap。当模型位于网络挂载或硬盘上时,此选项可能表现更好。
  • kwargs (剩余的关键字参数字典,可选) — 可用于覆盖可加载和可保存的变量(特定管道类的管道组件)。被覆盖的组件直接传递给管道的 __init__ 方法。更多信息请参见下面的示例。

从以 .ckpt.safetensors 格式保存的预训练管道权重实例化 DiffusionPipeline。管道默认设置为评估模式 (model.eval())。

示例

>>> from diffusers import StableDiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
... )

>>> # Download pipeline from local file
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly.ckpt")

>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
...     torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")

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

FlaxStableDiffusionImg2ImgPipeline

class diffusers.FlaxStableDiffusionImg2ImgPipeline

< >

( 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 image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array strength: float = 0.8 num_inference_steps: int = 50 height: typing.Optional[int] = None width: typing.Optional[int] = None guidance_scale: typing.Union[float, jax.Array] = 7.5 noise: Array = None neg_prompt_ids: Array = None return_dict: bool = True jit: bool = False ) FlaxStableDiffusionPipelineOutputtuple

参数

  • prompt_ids (jnp.ndarray) — 用于引导图像生成的提示词。
  • image (jnp.ndarray) — 表示用作起点的图像批处理数组。
  • params (DictFrozenDict) — 包含模型参数/权重的字典。
  • prng_seed (jax.Arrayjax.Array) — 包含随机数生成器密钥的数组。
  • strength (float, 可选, 默认为 0.8) — 指示转换参考 image 的程度。必须介于 0 到 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的全部迭代次数。值为 1 基本上会忽略 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度会变慢。此参数受 strength 调制。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但图像质量较低。当 guidance_scale > 1 时,启用引导比例。
  • noise (jnp.ndarray, 可选) — 从高斯分布中采样的预生成噪声潜在表示,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。该数组通过使用提供的随机 generator 进行采样来生成。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元组。
  • jit (bool, 默认为 False) — 是否运行生成和安全评分函数的 pmap 版本。

    此参数存在是因为 __call__ 尚未实现端到端的 pmap。它将在未来版本中移除。

返回

FlaxStableDiffusionPipelineOutputtuple

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

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

示例

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


>>> def create_key(seed=0):
...     return jax.random.PRNGKey(seed)


>>> rng = create_key(0)

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> init_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_img = init_img.resize((768, 512))

>>> prompts = "A fantasy landscape, trending on artstation"

>>> pipeline, params = FlaxStableDiffusionImg2ImgPipeline.from_pretrained(
...     "CompVis/stable-diffusion-v1-4",
...     revision="flax",
...     dtype=jnp.bfloat16,
... )

>>> num_samples = jax.device_count()
>>> rng = jax.random.split(rng, jax.device_count())
>>> prompt_ids, processed_image = pipeline.prepare_inputs(
...     prompt=[prompts] * num_samples, image=[init_img] * num_samples
... )
>>> p_params = replicate(params)
>>> prompt_ids = shard(prompt_ids)
>>> processed_image = shard(processed_image)

>>> output = pipeline(
...     prompt_ids=prompt_ids,
...     image=processed_image,
...     params=p_params,
...     prng_seed=rng,
...     strength=0.75,
...     num_inference_steps=50,
...     jit=True,
...     height=512,
...     width=768,
... ).images

>>> output_images = pipeline.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.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 上更新