Diffusers 文档

图像到图像

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

Image-to-image

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], 可选) — 用于去噪过程的自定义 sigmas,适用于在其 set_timesteps 方法中支持 sigmas 参数的调度器。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的引导比例值会鼓励模型生成与文本 prompt 紧密相关的图像,但会降低图像质量。当 guidance_scale > 1 时,引导比例生效。
  • negative_prompt (strList[str], 可选) — 用于指导图像生成中**不**包含的内容的提示词。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(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 输入参数生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, 可选): 可选的图像输入,用于 IP 适配器。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 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_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回 tuple,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。

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

示例

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

>>> from diffusers import StableDiffusionImg2ImgPipeline

>>> device = "cuda"
>>> model_id_or_path = "runwayml/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(
...     "runwayml/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[typing.List[str], 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 or 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 下载模型。
  • 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 = "runwayml/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 = "runwayml/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")。
    • 包含所有 pipeline 权重的文件的路径。
  • torch_dtype (strtorch.dtype, 可选) — 覆盖默认的 torch.dtype 并使用另一种 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 上托管的预训练 pipeline 的仓库 ID(例如 CompVis/ldm-text2im-large-256)。
    • 目录的路径(例如 ./my_pipeline_directory/),其中包含 Diffusers 格式的 pipeline 组件配置。
  • kwargs (剩余的关键字参数字典, 可选) — 可用于覆盖可加载和可保存的变量(特定 pipeline 类的 pipeline 组件)。覆盖的组件将直接传递给 pipeline 的 __init__ 方法。有关更多信息,请参见下面的示例。

从以 .ckpt.safetensors 格式保存的预训练 pipeline 权重实例化 DiffusionPipeline。默认情况下,pipeline 设置为评估模式 (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/runwayml/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 = None **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 权重而不初始化随机权重来加速模型加载。
  • kwargs (dict, optional) — 参见 lora_state_dict()

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

所有 kwargs 都将转发到 self.lora_state_dict

有关状态字典如何加载的更多详细信息,请参见 lora_state_dict()

有关状态字典如何加载到 self.unet 中的更多详细信息,请参见 load_lora_into_unet()

有关状态字典如何加载到 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 )

参数

  • 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, optional, 默认为 True) — 调用此进程是否为主进程。在分布式训练期间很有用,您需要在所有进程上调用此函数。在这种情况下,仅在主进程上设置 is_main_process=True 以避免竞争条件。
  • save_function (Callable) — 用于保存状态字典的函数。在分布式训练中,当您需要将 torch.save 替换为其他方法时很有用。可以使用环境变量 DIFFUSERS_SAVE_MODE 进行配置。
  • safe_serialization (bool, optional, 默认为 True) — 是否使用 safetensors 或传统的 PyTorch 方式 pickle 保存模型。

保存对应于 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], optional) — 要编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], optional) — 不引导图像生成的提示或提示列表。如果未定义,则必须改为传递 negative_prompt_embeds。不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 使用指定的引导比例生成嵌入向量,以随后丰富时间步长嵌入。
  • embedding_dim (int, optional, 默认为 512) — 要生成的嵌入的维度。
  • dtype (torch.dtype, optional, 默认为 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) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。 当 guidance_scale > 1 时,guidance scale 启用。
  • noise (jnp.ndarray, 可选) — 从高斯分布中采样的预生成噪声潜在空间,用作图像生成的输入。 可用于使用不同的提示调整相同的生成。 该数组是通过使用提供的随机 generator 进行采样而生成的。
  • return_dict (bool, 可选,默认为 True) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元组。
  • jit (bool, 默认为 False) — 是否运行生成和安全评分函数的 pmap 版本。

    此参数存在的原因是 __call__ 尚不能进行端到端 pmap。 它将在未来的版本中删除。

返回

FlaxStableDiffusionPipelineOutputtuple

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

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

示例

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

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

replace

< >

( **updates )

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

< > Update on GitHub