Diffusers 文件

潛在升取樣器

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

潛在升取樣器

Stable Diffusion 潛在升取樣器模型由 Katherine CrowsonStability AI 合作建立。它用於將輸出影像解析度提高 2 倍(有關原始實現的演示,請參閱此演示 notebook)。

務必檢視 Stable Diffusion 的 提示 部分,瞭解如何探索排程器速度和質量之間的權衡,以及如何高效地重用管道元件!

如果您有興趣將其中一個官方檢查點用於某個任務,請瀏覽 CompVisRunwayStability AI Hub 組織!

StableDiffusionLatentUpscalePipeline

class diffusers.StableDiffusionLatentUpscalePipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: EulerDiscreteScheduler )

引數

用於將 Stable Diffusion 輸出影像解析度提高 2 倍的管道。

此模型繼承自 DiffusionPipeline。有關所有管道(下載、儲存、在特定裝置上執行等)實現的通用方法,請參閱超類文件。

該管道還繼承了以下載入方法

__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 (strList[str]) — 用於引導影像升取樣的提示。
  • image (torch.TensorPIL.Image.Imagenp.ndarrayList[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 (strList[str], 可選) — 引導影像生成中不應包含的內容的提示。如果未定義,您需要傳遞 negative_prompt_embeds。當不使用引導(guidance_scale < 1)時,忽略此引數。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個 torch.Generator,用於使生成具有確定性。
  • latents (torch.Tensor, 可選) — 從高斯分佈取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同提示調整相同的生成。如果未提供,則使用提供的隨機 generator 進行取樣生成一個潛在張量。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • callback (Callable, 可選) — 一個函式,在推理過程中每 callback_steps 步呼叫一次。該函式使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — 呼叫 callback 函式的頻率。如果未指定,則在每一步呼叫回撥。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 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 )

引數

  • gpu_id (int, 可選) — 推理中應使用的加速器 ID。如果未指定,預設為 0。
  • device (torch.Devicestr, 可選, 預設為 None) — 推理中應使用的加速器的 PyTorch 裝置型別。如果未指定,它將自動檢測可用的加速器並使用。

使用 🤗 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' )

引數

  • slice_size (strint, 可選, 預設為 "auto") — 當為 "auto" 時,將輸入注意力頭減半,因此注意力將分兩步計算。如果為 "max",則透過一次只執行一個切片來節省最大記憶體。如果提供了數字,則使用 attention_head_dim // slice_size 個切片。在這種情況下,attention_head_dim 必須是 slice_size 的倍數。

啟用分片注意力計算。啟用此選項後,注意力模組會將輸入張量分片,分多步計算注意力。對於一個以上的注意力頭,計算將按順序在每個頭之間執行。這有助於節省一些記憶體,但會略微降低速度。

⚠️ 如果您已經在使用 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]

disable_attention_slicing

< >

( )

停用切片注意力計算。如果之前呼叫過 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)

disable_xformers_memory_efficient_attention

< >

( )

停用 xFormers 的記憶體高效注意力。

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 (strlist(int)) — 要編碼的提示詞。
  • device — (torch.device): torch 裝置。
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導。
  • negative_prompt (strList[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]] )

引數

  • 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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.