Diffusers 文档
超分辨率
并获得增强的文档体验
开始使用
超分辨率
Stable Diffusion 放大器扩散模型由 CompVis、Stability AI 和 LAION 的研究人员和工程师创建。它用于将输入图像的分辨率提高 4 倍。
务必查看 Stable Diffusion 的 提示 部分,了解如何探索调度器速度和质量之间的权衡,以及如何高效地重用管道组件!
如果您有兴趣将其中一个官方检查点用于任务,请探索 CompVis、Runway 和 Stability AI Hub 组织!
StableDiffusionUpscalePipeline
类 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 )
参数
- 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 的文本引导图像超分辨率管道。
此模型继承自 DiffusionPipeline。请查阅超类文档以了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。
该管道还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
- 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 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 ) → StableDiffusionPipelineOutput 或 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]
) — 要放大的图像或表示图像批次的张量。 - 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
)将被忽略。 - 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) 内容。
用于生成的管道的调用函数。
示例
>>> 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' )
启用分片注意力计算。当启用此选项时,注意力模块会将输入张量分片以分多步计算注意力。对于多个注意力头,计算按每个头顺序执行。这有助于节省一些内存,但会略微降低速度。
⚠️ 如果您已经在使用 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
< source >( attention_op: typing.Optional[typing.Callable] = None )
参数
- attention_op (
Callable
, optional) — 覆盖默认的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 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 (
str
或List[str]
, 可选) — 要编码的提示。 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量。 - do_classifier_free_guidance (
bool
) — 是否使用分类器自由引导。 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示。如果未定义,则必须传递negative_prompt_embeds
。在使用引导时(即如果guidance_scale
小于1
),则忽略此参数。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则文本嵌入将从prompt
输入参数生成。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,负提示嵌入将从negative_prompt
输入参数生成。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 缩放。 - clip_skip (
int
, 可选) — 计算提示嵌入时要跳过 CLIP 的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
将提示编码为文本编码器隐藏状态。
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 管道的输出类。