Diffusers 文档

超分辨率

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

超分辨率

Stable Diffusion 放大器扩散模型由来自 CompVisStability AILAION 的研究人员和工程师创建。它用于将输入图像的分辨率提高 4 倍。

请务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用 pipeline 组件!

如果您有兴趣为任务使用官方 checkpoints 之一,请浏览 CompVisRunwayStability AI Hub 组织!

StableDiffusionUpscalePipeline

class diffusers.StableDiffusionUpscalePipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel low_res_scheduler: DDPMScheduler scheduler: KarrasDiffusionSchedulers safety_checker: typing.Optional[typing.Any] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None watermarker: typing.Optional[typing.Any] = None max_noise_level: int = 350 )

参数

使用 Stable Diffusion 2 进行文本引导的图像超分辨率的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。

该 pipeline 还继承了以下加载方法

__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 noise_level: int = 20 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 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: int = None ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的 prompt 或 prompts。如果未定义,则需要传递 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image 或 tensor,表示要放大的图像批次。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会以较慢的推理速度为代价,从而产生更高质量的图像。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会降低图像质量。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不包含的内容的 prompt 或 prompts。如果未定义,则需要改为传递 negative_prompt_embeds。不使用 guidance 时忽略(guidance_scale < 1)。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。 仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在空间,用作图像生成的输入。 可用于通过不同的 prompts 微调相同的生成。 如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜在空间 tensor。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入(prompt 权重)。 如果未提供,则文本 embeddings 会从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本 embeddings。 可用于轻松调整文本输入(prompt 权重)。 如果未提供,则 negative_prompt_embeds 会从 negative_prompt 输入参数生成。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。 在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通 tuple。
  • callback (Callable, 可选) — 一个在推理的每 callback_steps 步调用的函数。该函数被以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每个步骤都调用回调函数。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适合工作场所”(nsfw)内容。

用于生成 pipeline 的调用函数。

示例

>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionUpscalePipeline
>>> import torch

>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
...     model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")

>>> # let's download an  image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"

>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")

enable_attention_slicing

< >

( slice_size: typing.Union[int, str, NoneType] = 'auto' )

参数

  • slice_size (strint, 可选, 默认为 "auto") — 当为 "auto" 时,将 attention heads 的输入减半,因此 attention 将分两步计算。如果为 "max",则通过一次只运行一个切片来最大程度地节省内存。如果提供了数字,则使用与 attention_head_dim // slice_size 一样多的切片。在这种情况下,attention_head_dim 必须是 slice_size 的倍数。

启用切片 attention 计算。启用此选项后,attention 模块会将输入张量分割成切片,以分几个步骤计算 attention。对于多个 attention head,计算将按顺序在每个 head 上执行。这对于节省一些内存以换取少量速度下降很有用。

⚠️ 如果您已经在使用 PyTorch 2.0 或 xFormers 中的 scaled_dot_product_attention (SDPA),请不要启用 attention slicing。这些 attention 计算已经非常节省内存,因此您不需要启用此功能。如果您在 SDPA 或 xFormers 中启用 attention slicing,则可能会导致严重的减速!

示例

>>> 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]

disable_attention_slicing

< >

( )

禁用切片 attention 计算。如果之前调用过 enable_attention_slicing,则 attention 将一步计算完成。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

参数

  • attention_op (Callable, 可选) — 覆盖默认的 None 运算符,用作 xFormers 的 memory_efficient_attention() 函数的 op 参数。

启用来自 xFormers 的内存高效 attention。启用此选项后,您应该观察到更低的 GPU 内存使用率和推理期间潜在的速度提升。不保证训练期间的速度提升。

⚠️ 当内存高效 attention 和切片 attention 都启用时,内存高效 attention 优先。

示例

>>> 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)

disable_xformers_memory_efficient_attention

< >

( )

禁用来自 xFormers 的内存高效 attention。

encode_prompt

< >

( 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 (strList[str], 可选) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器 guidance
  • negative_prompt (strList[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 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示预倒数第二层的输出将用于计算 prompt embeddings。

将 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]] )

参数

  • images (List[PIL.Image.Image]np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表或形状为 (batch_size, height, width, num_channels) 的 NumPy 数组。
  • nsfw_content_detected (List[bool]) — 列表,指示相应的生成图像是否包含“不适宜工作场所观看”(nsfw)内容,如果无法执行安全检查,则为 None

Stable Diffusion 管道的输出类。

< > 在 GitHub 上更新