Diffusers 文件

超解析度

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

超解析度

LoRA

Stable Diffusion 放大器擴散模型由 CompVisStability AILAION 的研究人員和工程師建立。它用於將輸入影像的解析度提高 4 倍。

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

如果您有興趣將其中一個官方檢查點用於任務,請探索 CompVisRunwayStability 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 )

引數

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 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_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 (strList[str], 可選) — 用於引導影像生成中不包含內容的提示詞。如果未定義,您需要傳遞 negative_prompt_embeds。當不使用引導時(guidance_scale < 1)將被忽略。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞要生成的影像數量。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中將被忽略。
  • generator (torch.GeneratorList[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.Imagenp.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 表示將使用倒數第二層的輸出計算提示詞嵌入。

返回

StableDiffusionPipelineOutputtuple

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

引數

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

disable_xformers_memory_efficient_attention

< >

( )

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

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], 可選) — 要編碼的提示。
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示應生成的影像數量。
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導。
  • negative_prompt (strList[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

< >

( 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.