Diffusers documentation
超分辨率
超分辨率
Stable Diffusion 超分辨率扩散模型由 CompVis、Stability AI 和 LAION 的研究人员和工程师共同开发。该模型用于将输入图像的分辨率提升 4 倍。
请务必查看 Stable Diffusion 的 技巧 部分,了解如何探索调度器速度与质量之间的权衡,以及如何高效地复用流水线组件!
如果您对使用某个任务的官方检查点感兴趣,请探索 CompVis 和 Stability AI Hub 组织!
StableDiffusionUpscalePipeline
class diffusers.StableDiffusionUpscalePipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModellow_res_scheduler: DDPMSchedulerscheduler: KarrasDiffusionSchedulerssafety_checker: typing.Any | None = Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Nonewatermarker: typing.Any | None = Nonemax_noise_level: int = 350 )
参数
- vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。
- text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) —
用于对文本进行分词的
CLIPTokenizer。 - unet (UNet2DConditionModel) —
用于对编码后的图像潜变量进行去噪的
UNet2DConditionModel。 - low_res_scheduler (SchedulerMixin) — 用于为低分辨率条件图像添加初始噪声的调度器。它必须是 DDPMScheduler 的实例。
- scheduler (SchedulerMixin) —
用于与
unet配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
使用 Stable Diffusion 2 进行文本引导图像超分辨率的 Pipeline。
该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。
该 pipeline 还继承了以下加载方法:
- 用于加载文本反转嵌入的 load_textual_inversion()
- 用于加载 LoRA 权重的 load_lora_weights()
- 用于保存 LoRA 权重的 save_lora_weights()
- 用于加载
.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.0noise_level: int = 20negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int = None ) → StableDiffusionPipelineOutput or 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或表示待放大图像批次的张量。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - guidance_scale (
float,可选,默认值为 7.5) — 较高的 guidance scale 值会促使模型生成与文本prompt紧密相关的图像,但代价是图像质量降低。当guidance_scale > 1时,guidance scale 生效。 - noise_level (
int,可选,默认为 20) — 添加到放大后的输入图像中的噪声量。必须位于[0, max_noise_level]范围内,其中max_noise_level由调度器定义。较高的noise_level会向输入添加更多噪声,从而增加变化性,但会降低对源图像的保真度。 - negative_prompt (
str或list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - eta(
float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。 - 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输入参数生成。 - 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函数的频率。如果未指定,则会在每一步调用该回调。 - cross_attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给self.processor中定义的AttentionProcessor。 - clip_skip (
int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
返回值
StableDiffusionPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 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
< 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 >( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - device — (
torch.device): torch 设备 - num_images_per_prompt (
int) — 每个提示词应生成的图像数量 - do_classifier_free_guidance (
bool) — 是否使用 classifier free guidance - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - lora_scale (
float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。 - clip_skip (
int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
将提示词编码为文本编码器的隐藏状态。
StableDiffusionPipelineOutput
类 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 管道的输出类。