Diffusers 文档
深度到图像
并获得增强的文档体验
开始使用
深度到图像
Stable Diffusion 模型还可以使用 MiDaS 基于图像推断深度。这允许您传递文本 prompt 和初始图像来调节新图像的生成,以及 depth_map
以保留图像结构。
请务必查看 Stable Diffusion 的 技巧 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!
如果您有兴趣使用任务的官方 checkpoints 之一,请浏览 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionDepth2ImgPipeline
class diffusers.StableDiffusionDepth2ImgPipeline
< 源代码 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers depth_estimator: DPTForDepthEstimation feature_extractor: DPTImageProcessor )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用于文本标记化的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。
用于文本引导的基于深度的图像到图像生成的 Stable Diffusion 管线。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有管线实现的通用方法(下载、保存、在特定设备上运行等)。
该管线还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__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 depth_map: typing.Optional[torch.Tensor] = None strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 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 output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None 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 ) → StableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则需要传递prompt_embeds
。 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
或张量,表示用作起点的图像批次。仅当depth_map
不为None
时,才能接受图像潜在空间作为image
。 - depth_map (
torch.Tensor
, 可选) — 深度预测,用作图像生成过程的附加条件。如果未定义,它将使用self.depth_estimator
自动预测深度。 - strength (
float
, 可选, 默认为 0.8) — 指示转换参考image
的程度。必须介于 0 和 1 之间。image
用作起点,并且strength
越高,添加的噪声就越多。去噪步骤的数量取决于最初添加的噪声量。当strength
为 1 时,添加的噪声最大,并且去噪过程将运行在num_inference_steps
中指定的完整迭代次数。值为 1 本质上会忽略image
。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会以较慢的推理速度为代价,从而产生更高质量的图像。此参数由strength
调制。 - 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
。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则negative_prompt_embeds
将从negative_prompt
输入参数生成。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是纯元组。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - 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
属性中列出的变量。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成的图像的列表。
管道的调用函数用于生成。
示例
>>> import torch
>>> import requests
>>> from PIL import Image
>>> from diffusers import StableDiffusionDepth2ImgPipeline
>>> pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(
... "stabilityai/stable-diffusion-2-depth",
... torch_dtype=torch.float16,
... )
>>> pipe.to("cuda")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> init_image = Image.open(requests.get(url, stream=True).raw)
>>> prompt = "two tigers"
>>> n_prompt = "bad, deformed, ugly, bad anotomy"
>>> image = pipe(prompt=prompt, image=init_image, negative_prompt=n_prompt, strength=0.7).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
,则注意力将在一个步骤中计算。
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, 可选) — 覆盖默认的None
运算符,用作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 的内存高效注意力。
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]
) — 可以是以下之一或它们的列表:- 一个字符串,预训练模型的模型 ID(例如
sd-concepts-library/low-poly-hd-logos-icons
),托管在 Hub 上。 - 目录的路径(例如
./my_text_inversion_directory/
),其中包含文本反演权重。 - 文件的路径(例如
./my_text_inversions.pt
),其中包含文本反演权重。 - torch 状态字典。
- 一个字符串,预训练模型的模型 ID(例如
- token (
str
或List[str]
, 可选) — 覆盖用于文本反演权重的 token。如果pretrained_model_name_or_path
是一个列表,则token
也必须是长度相等的列表。 - text_encoder (CLIPTextModel, 可选) — 冻结的文本编码器 (clip-vit-large-patch14)。如果未指定,函数将采用 self.tokenizer。
- tokenizer (CLIPTokenizer, 可选) — 一个
CLIPTokenizer
用于 token 化文本。如果未指定,函数将采用 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
, 可选) — 如果您在中国下载模型时遇到可访问性问题,可以使用镜像源来解决。我们不保证来源的及时性或安全性,您应参考镜像站点以获取更多信息。
将文本反演嵌入加载到 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")
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 层的状态字典。 必须显式传递文本编码器 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 参数。
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]
, 可选) — 要编码的提示 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器引导 - negative_prompt (
str
或List[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 表示预最终层的输出将用于计算提示嵌入。
将提示编码为文本编码器隐藏状态。
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 管道的输出类。