Diffusers documentation
潜在上采样器
潜在上采样器
Stable Diffusion 潜在上采样模型由 Katherine Crowson 与 Stability AI 合作创建。该模型用于将输出图像的分辨率提升 2 倍(有关原始实现的演示,请参阅此 notebook)。
请务必查看 Stable Diffusion 的 技巧 部分,了解如何探索调度器速度与质量之间的权衡,以及如何高效地复用流水线组件!
如果您对使用某个任务的官方检查点感兴趣,请探索 CompVis 和 Stability AI Hub 组织!
StableDiffusionLatentUpscalePipeline
类 diffusers.StableDiffusionLatentUpscalePipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: 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。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。
该 pipeline 还继承了以下加载方法:
- 用于加载
.ckpt文件的 from_single_file()
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 75guidance_scale: float = 9.0negative_prompt: str | list[str] | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_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]) —Image或表示待放大图像批次的张量。如果它是张量,则可以是 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],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。 - generator (
torch.Generator或list[torch.Generator],可选) — 用于使生成过程确定性的torch.Generator。 - latents (
torch.Tensor, 可选) — 预先生成的、从高斯分布中采样的含噪潜变量,用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,则使用提供的随机generator进行采样,生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从prompt输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor,可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds将根据negative_prompt输入参数生成。 - pooled_prompt_embeds (
torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入(提示词加权)。如果未提供,则从prompt输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds(
torch.Tensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则会根据negative_prompt输入参数生成池化的negative_prompt_embeds。 - 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,其中第一个元素是包含生成图像的列表。
用于生成的 pipeline 的调用函数。
示例:
>>> 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: int | None = Nonedevice: 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
< source >( slice_size: str | int = '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",
... 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 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。
> ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient attention 具有 > 优先权。
示例:
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", 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 >( promptdevicedo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )
参数
- prompt (
str或list(int)) — 要编码的提示 - device — (
torch.device): torch 设备 - do_classifier_free_guidance (
bool) — 是否使用 classifier free guidance - 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输入参数生成池化的 negative_prompt_embeds。
将提示词编码为文本编码器的隐藏状态。
StableDiffusionPipelineOutput
类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 管道的输出类。