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 管道的輸出類。