Diffusers 文档
潜在升采样器
并获得增强的文档体验
开始使用
潜在升采样器
Stable Diffusion 潜在升采样器模型由 Katherine Crowson 与 Stability AI 合作创建。它用于将输出图像分辨率提高 2 倍(有关原始实现的演示,请参阅此演示 notebook)。
务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用管道组件!
如果您有兴趣将其中一个官方检查点用于某个任务,请浏览 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionLatentUpscalePipeline
class diffusers.StableDiffusionLatentUpscalePipeline
< 来源 >( 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) — 用于与
unet
结合以对编码图像潜在表示进行去噪的 EulerDiscreteScheduler。
用于将 Stable Diffusion 输出图像分辨率提高 2 倍的管道。
此模型继承自 DiffusionPipeline。有关所有管道(下载、保存、在特定设备上运行等)实现的通用方法,请参阅超类文档。
该管道还继承了以下加载方法
- from_single_file() 用于加载
.ckpt
文件
__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 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 or tuple
参数
- prompt (
str
或List[str]
) — 用于引导图像升采样的提示。 - image (
torch.Tensor
、PIL.Image.Image
、np.ndarray
、List[torch.Tensor]
、List[PIL.Image.Image]
或List[np.ndarray]
) — 要升采样的图像或表示图像批次的张量。如果它是张量,它可以是 Stable Diffusion 模型的潜在输出,也可以是范围[-1, 1]
内的图像张量。如果image.shape[1]
为4
,则被视为latent
;否则,被视为图像表示并使用此管道的vae
编码器进行编码。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本prompt
密切相关的图像,但图像质量较低。当guidance_scale > 1
时,启用引导比例。 - negative_prompt (
str
或List[str]
, 可选) — 引导图像生成中不应包含的内容的提示。如果未定义,您需要传递negative_prompt_embeds
。当不使用引导(guidance_scale < 1
)时,忽略此参数。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个torch.Generator
,用于使生成具有确定性。 - latents (
torch.Tensor
, 可选) — 从高斯分布采样的预生成噪声潜在表示,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则使用提供的随机generator
进行采样生成一个潜在张量。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。 - 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
< 来源 >( gpu_id: typing.Optional[int] = None device: typing.Union[torch.device, str] = None )
使用 🤗 Accelerate 将所有模型卸载到 CPU,显著减少内存使用。调用时,所有 torch.nn.Module
组件的状态字典(除了 self._exclude_from_cpu_offload
中的组件)都保存到 CPU,然后移动到 torch.device('meta')
,并且只有当其特定的子模块调用 forward
方法时才加载到加速器。卸载以子模块为基础进行。内存节省高于 enable_model_cpu_offload
,但性能较低。
enable_attention_slicing
< 来源 >( 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(
... "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]
禁用切片注意力计算。如果之前调用过 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)
encode_prompt
< 源 >( 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_embeds
将从negative_prompt
输入参数生成。 - pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化文本嵌入将从prompt
输入参数生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化negative_prompt_embeds
将从negative_prompt
输入参数生成。
将提示编码为文本编码器隐藏状态。
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]] )
Stable Diffusion 管道的输出类。