Diffusers 文档
潜在空间放大器
并获得增强的文档体验
开始使用
潜在空间放大器
Stable Diffusion 潜在空间放大器模型由 Katherine Crowson 与 Stability AI 合作创建。它用于将输出图像分辨率增强 2 倍(有关原始实现的演示,请参阅此演示 notebook)。
请务必查看 Stable Diffusion 提示 部分,了解如何探索 scheduler 速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!
如果您有兴趣使用官方检查点来执行任务,请浏览 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionLatentUpscalePipeline
class diffusers.StableDiffusionLatentUpscalePipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: EulerDiscreteScheduler )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 一个
CLIPTokenizer
,用于文本标记化。 - unet (UNet2DConditionModel) — 一个
UNet2DConditionModel
,用于对编码后的图像潜在空间进行去噪。 - scheduler (SchedulerMixin) — 一个 EulerDiscreteScheduler (欧拉离散调度器),与
unet
结合使用,以对编码后的图像潜在空间进行去噪。
用于将 Stable Diffusion 输出图像分辨率放大 2 倍的 Pipeline (管线)。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有管线实现的通用方法(下载、保存、在特定设备上运行等)。
该管线还继承了以下加载方法
- from_single_file() 用于加载
.ckpt
文件
__call__
< source >( 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 num_inference_steps: int = 75 guidance_scale: float = 9.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 ) → StableDiffusionPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
) — 用于引导图像放大的 prompt (提示) 或 prompts (提示列表)。 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
(图像) 或 tensor (张量),表示要放大的图像批次。如果它是张量,则可以是来自 Stable Diffusion 模型的潜在输出,也可以是范围在[-1, 1]
内的图像张量。如果image.shape[1]
为4
,则被认为是latent
(潜在空间);否则,它被认为是图像表示,并将使用此管线的vae
编码器进行编码。 - num_inference_steps (
int
, 可选,默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - guidance_scale (
float
, 可选,默认为 7.5) — guidance scale (引导比例) 值越高,模型就越倾向于生成与文本prompt
(提示) 紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时,guidance scale (引导比例) 生效。 - negative_prompt (
str
或List[str]
, 可选) — prompt (提示) 或 prompts (提示列表),用于引导图像生成中不应包含的内容。如果未定义,则需要传递negative_prompt_embeds
代替。当不使用 guidance (引导) 时(guidance_scale < 1
),将被忽略。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler (DDIM 调度器),在其他调度器中将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) —torch.Generator
,用于使生成结果具有确定性。 - latents (
torch.Tensor
, 可选) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。可用于通过不同的 prompt (提示) 调整相同的生成结果。如果未提供,则将通过使用提供的随机generator
(生成器) 进行采样来生成潜在空间张量。 - output_type (
str
, 可选,默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通的 tuple (元组)。 - callback (
Callable
, 可选) — 在推理过程中每隔callback_steps
步调用的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选,默认为 1) —callback
函数被调用的频率。如果未指定,则在每个步骤都调用回调。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple
(元组),其中第一个元素是包含生成的图像的列表。
用于生成管线的调用函数。
示例
>>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
>>> import torch
>>> pipeline = StableDiffusionPipeline.from_pretrained(
... "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... )
>>> pipeline.to("cuda")
>>> model_id = "stabilityai/sd-x2-latent-upscaler"
>>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
>>> upscaler.to("cuda")
>>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
>>> generator = torch.manual_seed(33)
>>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images
>>> with torch.no_grad():
... image = pipeline.decode_latents(low_res_latents)
>>> image = pipeline.numpy_to_pil(image)[0]
>>> image.save("../images/a1.png")
>>> upscaled_image = upscaler(
... prompt=prompt,
... image=low_res_latents,
... num_inference_steps=20,
... guidance_scale=0,
... generator=generator,
... ).images[0]
>>> upscaled_image.save("../images/a2.png")
enable_sequential_cpu_offload
< source >( gpu_id: typing.Optional[int] = None device: typing.Union[torch.device, str] = 'cuda' )
使用 🤗 Accelerate 将所有模型卸载到 CPU,从而显著减少内存使用量。调用时,所有 torch.nn.Module
组件(self._exclude_from_cpu_offload
中的组件除外)的状态字典将保存到 CPU,然后移动到 torch.device('meta')
,并且仅当其特定子模块的 forward
方法被调用时才加载到 GPU。卸载是基于子模块进行的。内存节省高于 enable_model_cpu_offload
,但性能较低。
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
运算符,用作 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 的内存高效注意力。
encode_prompt
< source >( prompt device do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )
参数
- prompt (
str
或list(int)
) — 要编码的提示词 - device — (
torch.device
): torch 设备 - do_classifier_free_guidance (
bool
) — 是否使用无分类器引导 - negative_prompt (
str
或List[str]
) — 不用于引导图像生成的提示或提示列表。当不使用引导时忽略(即,如果guidance_scale
小于1
,则忽略)。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从negative_prompt
输入参数生成池化 negative_prompt_embeds。
将提示词编码为文本编码器隐藏状态。
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 管道的输出类。