Diffusers 文档
文本到图像
并获取增强的文档体验
开始使用
Text-to-image
Stable Diffusion 模型由来自 CompVis、Stability AI、Runway 和 LAION 的研究人员和工程师创建。StableDiffusionPipeline 能够根据任何文本输入生成照片般逼真的图像。它在 LAION-5B 数据集子集的 512x512 图像上进行训练。此模型使用冻结的 CLIP ViT-L/14 文本编码器,以文本提示作为模型的条件。凭借其 8.6 亿参数的 UNet 和 1.23 亿参数的文本编码器,该模型相对轻量级,可以在消费级 GPU 上运行。潜在扩散是构建 Stable Diffusion 的研究基础。Robin Rombach、Andreas Blattmann、Dominik Lorenz、Patrick Esser、Björn Ommer 在 High-Resolution Image Synthesis with Latent Diffusion Models 中提出了这一概念。
论文摘要如下:
通过将图像形成过程分解为去噪自动编码器的顺序应用,扩散模型 (DMs) 在图像数据及其他领域取得了最先进的合成结果。此外,它们的公式允许引导机制来控制图像生成过程,而无需重新训练。然而,由于这些模型通常直接在像素空间中运行,因此强大 DM 的优化通常消耗数百个 GPU 日,并且由于顺序评估,推理成本很高。为了在有限的计算资源上实现 DM 训练,同时保持其质量和灵活性,我们将它们应用于强大的预训练自动编码器的潜在空间中。与之前的工作相比,在这样的表示上训练扩散模型首次实现了复杂性降低和细节保留之间的近乎最佳的平衡点,大大提高了视觉保真度。通过在模型架构中引入交叉注意力层,我们将扩散模型转变为强大而灵活的生成器,用于通用条件输入,例如文本或边界框,并且可以以卷积方式实现高分辨率合成。我们的潜在扩散模型 (LDMs) 在图像修复方面取得了新的最先进水平,并在各种任务(包括无条件图像生成、语义场景合成和超分辨率)上取得了极具竞争力的性能,同时与基于像素的 DM 相比,显著降低了计算要求。代码可在 https://github.com/CompVis/latent-diffusion 获取。
请务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!
如果您有兴趣使用官方的 checkpoint 来完成某项任务,请浏览 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionPipeline
class diffusers.StableDiffusionPipeline
< source >( 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
结合使用,以对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅 模型卡。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演 embedding
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- from_single_file() 用于加载
.ckpt
文件 - load_ip_adapter() 用于加载 IP Adapter
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None 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 guidance_rescale: float = 0.0 clip_skip: typing.Optional[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 or tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示。如果未定义,则需要传递prompt_embeds
。 - 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) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。 - timesteps (
List[int]
, 可选) — 自定义 timesteps,用于支持在其set_timesteps
方法中使用timesteps
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。必须按降序排列。 - sigmas (
List[float]
, 可选) — 自定义 sigmas,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会以降低图像质量为代价。当guidance_scale > 1
时,guidance scale 启用。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不应包含的内容的提示。如果未定义,则需要传递negative_prompt_embeds
代替。当不使用 guidance 时(guidance_scale < 1
),将被忽略。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成过程具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的、从高斯分布中采样的噪声潜在变量,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,则会通过使用提供的随机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.Image
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - guidance_rescale (
float
, 可选,默认为 0.0) — 来自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的 Guidance rescale 因子。 Guidance rescale 因子应该可以修复使用零终端信噪比时的过度曝光问题。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可选) — 在推理期间,在每个去噪步骤结束时调用的函数或PipelineCallback
或MultiPipelineCallbacks
的子类。带有以下参数: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
属性中列出的变量。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合工作场所观看”(nsfw)内容。
管道的调用函数,用于生成。
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).images[0]
enable_attention_slicing
< source >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
启用切片注意力计算。启用此选项后,注意力模块会将输入张量拆分为切片,以分多个步骤计算注意力。对于多个注意力头,计算将按顺序对每个头执行。这有助于节省一些内存,但会略微降低速度。
⚠️ 如果您已经在使用 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]
禁用切片注意力计算。如果之前调用了 enable_attention_slicing
,则注意力将一步计算完成。
启用切片 VAE 解码。启用此选项后,VAE 会将输入张量拆分为切片,以分多个步骤计算解码。这有助于节省一些内存并允许更大的批量大小。
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
enable_xformers_memory_efficient_attention
< source >( 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)
禁用来自 xFormers 的内存高效注意力。
启用平铺 VAE 解码。启用此选项后,VAE 会将输入张量拆分为平铺,以分多个步骤计算解码和编码。这对于节省大量内存并允许处理更大的图像非常有用。
禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling
,此方法将恢复为一步计算解码。
load_textual_inversion
< source >( 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 (
str
或os.PathLike
或List[str or os.PathLike]
或Dict
或List[Dict]
) — 可以是以下其中一项或它们的列表:- 一个字符串,托管在 Hub 上的预训练模型的模型 ID (例如
sd-concepts-library/low-poly-hd-logos-icons
)。 - 一个指向包含文本反演权重的目录的路径 (例如
./my_text_inversion_directory/
)。 - 一个指向包含文本反演权重的文件的路径 (例如
./my_text_inversions.pt
)。 - 一个 torch 状态字典。
- 一个字符串,托管在 Hub 上的预训练模型的模型 ID (例如
- token (
str
或List[str]
, 可选) — 覆盖用于文本反演权重的 token。如果pretrained_model_name_or_path
是一个列表,则token
也必须是等长的列表。 - text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器 (clip-vit-large-patch14)。如果未指定,该函数将使用 self.tokenizer。
- tokenizer (CLIPTokenizer, 可选) — 用于 token 化文本的
CLIPTokenizer
。如果未指定,该函数将使用 self.tokenizer。 - weight_name (
str
, 可选) — 自定义权重文件的名称。当需要以下情况时应使用此参数:- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
text_inv.bin
)保存。 - 保存的文本反演文件是 Automatic1111 格式。
- 保存的文本反演文件是 🤗 Diffusers 格式,但以特定的权重名称(例如
- 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 (
str
或 bool, 可选) — 用作远程文件 HTTP Bearer 授权的 token。如果为True
,则使用从diffusers-cli login
生成的 token(存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。 - subfolder (
str
, 可选, 默认为""
) — Hub 上或本地的较大模型仓库中模型文件的子文件夹位置。 - mirror (
str
, 可选) — 镜像源,用于解决在中国下载模型时的可访问性问题。我们不保证源的及时性或安全性,您应参考镜像站点以获取更多信息。
将 Textual Inversion 嵌入加载到 StableDiffusionPipeline 的文本编码器中(支持 🤗 Diffusers 和 Automatic1111 格式)。
示例
加载 🤗 Diffusers 格式的 Textual Inversion 嵌入向量
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 格式的 Textual Inversion 嵌入向量,请确保首先下载向量(例如从 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
< source >( pretrained_model_link_or_path **kwargs )
参数
- pretrained_model_link_or_path (
str
或os.PathLike
, 可选) — 可以是以下之一:- 指向 Hub 上
.ckpt
文件的链接 (例如"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"
)。 - 指向包含所有 pipeline 权重的文件的路径。
- 指向 Hub 上
- torch_dtype (
str
或torch.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 (
str
或 bool, 可选) — 用作远程文件 HTTP Bearer 授权的 token。如果为True
,则使用从diffusers-cli login
生成的 token(存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID 或 Git 允许的任何标识符。 - original_config_file (
str
, 可选) — 用于训练模型的原始配置文件的路径。如果未提供,将从检查点文件推断配置文件。 - config (
str
, 可选) — 可以是以下之一:- 字符串,Hub 上托管的预训练 pipeline 的 repo id(例如
CompVis/ldm-text2im-large-256
)。 - 指向目录的路径(例如
./my_pipeline_directory/
),其中包含 Diffusers 格式的 pipeline 组件配置。
- 字符串,Hub 上托管的预训练 pipeline 的 repo id(例如
- 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
< source >( 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 (
str
或os.PathLike
或dict
) — 参见 lora_state_dict()。 - adapter_name (
str
, 可选) — 用于引用加载的适配器模型的适配器名称。如果未指定,则将使用default_{i}
,其中 i 是正在加载的适配器总数。 - low_cpu_mem_usage (
bool
, 可选) — 通过仅加载预训练的 LoRA 权重而不初始化随机权重来加速模型加载。 - kwargs (
dict
, 可选) — 参见 lora_state_dict()。
将 pretrained_model_name_or_path_or_dict
中指定的 LoRA 权重加载到 self.unet
和 self.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
< source >( 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 (
str
或os.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 层的状态字典。 必须显式传递 text encoder 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 和 text encoder 的 LoRA 参数。
encode_prompt
< source >( 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 (
str
或List[str]
, 可选) — 要编码的 prompt - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器 guidance - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递negative_prompt_embeds
。不使用 guidance 时忽略(即,如果guidance_scale
小于1
则忽略)。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于 text encoder 的所有 LoRA 层的 LoRA 缩放比例。 - clip_skip (
int
, 可选) — 在计算 prompt embeddings 时,从 CLIP 中跳过的层数。值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。
将 prompt 编码为文本编码器隐藏状态。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion pipelines 的输出类。
FlaxStableDiffusionPipeline
class diffusers.FlaxStableDiffusionPipeline
< source >( 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) — 用于对编码后的图像 latents 进行去噪的
FlaxUNet2DConditionModel
。 - scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,以对编码后的图像 latents 进行去噪。可以是FlaxDDIMScheduler
、FlaxLMSDiscreteScheduler
、FlaxPNDMScheduler
或FlaxDPMSolverMultistepScheduler
之一。 - safety_checker (
FlaxStableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
基于 Flax 的 pipeline,用于使用 Stable Diffusion 进行文本到图像的生成。
此模型继承自 FlaxDiffusionPipeline。查看超类文档,了解为所有 pipelines 实现的通用方法(下载、保存、在特定设备上运行等)。
__call__
< source >( prompt_ids: <function array at 0x7f484db85cf0> 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 ) → FlaxStableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的 prompt 或 prompts。 - 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) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - guidance_scale (
float
, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
更紧密相关的图像,但会降低图像质量。当guidance_scale > 1
时,guidance scale 功能启用。 - latents (
jnp.ndarray
, 可选) — 从高斯分布中采样的预生成噪声潜变量,用作图像生成的输入。可用于通过不同的 prompts 调整相同的生成结果。如果未提供,则会使用提供的随机generator
采样生成潜变量数组。 - jit (
bool
, 默认为False
) — 是否运行生成和安全评分函数的pmap
版本。此参数的存在是因为
__call__
尚未实现端到端 pmap 化。它将在未来的版本中移除。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通的元组。
返回
如果 return_dict
为 True
,则返回 FlaxStableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适合在工作场所观看”(nsfw)的内容。
管道的调用函数,用于生成。
示例
>>> import jax
>>> import numpy as np
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> from diffusers import FlaxStableDiffusionPipeline
>>> pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
... "runwayml/stable-diffusion-v1-5", variant="bf16", dtype=jax.numpy.bfloat16
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> prng_seed = jax.random.PRNGKey(0)
>>> num_inference_steps = 50
>>> num_samples = jax.device_count()
>>> prompt = num_samples * [prompt]
>>> prompt_ids = pipeline.prepare_inputs(prompt)
# shard inputs and rng
>>> params = replicate(params)
>>> prng_seed = jax.random.split(prng_seed, jax.device_count())
>>> prompt_ids = shard(prompt_ids)
>>> images = pipeline(prompt_ids, 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
< source >( images: ndarray nsfw_content_detected: typing.List[bool] )
Flax-based Stable Diffusion pipeline 的输出类。
返回一个新对象,将指定的字段替换为新值。