Diffusers 文件

Stable unCLIP

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Stable unCLIP

LoRA

Stable unCLIP 檢查點是在 Stable Diffusion 2.1 檢查點的基礎上進行微調,以 CLIP 影像嵌入為條件。Stable unCLIP 仍然以文字嵌入為條件。鑑於這兩個獨立的條件,stable unCLIP 可用於文字引導的影像變體。當與 unCLIP 先驗結合時,它也可以用於完整的文字到影像生成。

論文摘要如下:

CLIP 等對比模型已被證明可以學習影像的魯棒表示,捕捉語義和風格。為了利用這些表示進行影像生成,我們提出了一個兩階段模型:一個根據文字標題生成 CLIP 影像嵌入的先驗,以及一個根據影像嵌入生成影像的解碼器。我們表明,顯式生成影像表示可以提高影像多樣性,同時最大限度地減少照片真實感和標題相似性的損失。我們的以影像表示為條件的解碼器還可以生成保留影像語義和風格的影像變體,同時改變影像表示中不存在的非必要細節。此外,CLIP 的聯合嵌入空間支援零樣本的語言引導影像操作。我們使用擴散模型作為解碼器,並對先驗模型進行自迴歸和擴散模型的實驗,發現後者在計算上更高效,併產生更高質量的樣本。

提示

Stable unCLIP 在推理過程中將 `noise_level` 作為輸入,它決定了影像嵌入中新增多少噪聲。更高的 `noise_level` 會增加最終去噪影像的變化。預設情況下,我們不對影像嵌入新增任何額外的噪聲(`noise_level = 0`)。

文字到影像生成

Stable unCLIP 可以透過與 KakaoBrain 的開源 DALL-E 2 復現專案 Karlo 的先驗模型進行管道連線,從而實現文字到影像生成。

import torch
from diffusers import UnCLIPScheduler, DDPMScheduler, StableUnCLIPPipeline
from diffusers.models import PriorTransformer
from transformers import CLIPTokenizer, CLIPTextModelWithProjection

prior_model_id = "kakaobrain/karlo-v1-alpha"
data_type = torch.float16
prior = PriorTransformer.from_pretrained(prior_model_id, subfolder="prior", torch_dtype=data_type)

prior_text_model_id = "openai/clip-vit-large-patch14"
prior_tokenizer = CLIPTokenizer.from_pretrained(prior_text_model_id)
prior_text_model = CLIPTextModelWithProjection.from_pretrained(prior_text_model_id, torch_dtype=data_type)
prior_scheduler = UnCLIPScheduler.from_pretrained(prior_model_id, subfolder="prior_scheduler")
prior_scheduler = DDPMScheduler.from_config(prior_scheduler.config)

stable_unclip_model_id = "stabilityai/stable-diffusion-2-1-unclip-small"

pipe = StableUnCLIPPipeline.from_pretrained(
    stable_unclip_model_id,
    torch_dtype=data_type,
    variant="fp16",
    prior_tokenizer=prior_tokenizer,
    prior_text_encoder=prior_text_model,
    prior=prior,
    prior_scheduler=prior_scheduler,
)

pipe = pipe.to("cuda")
wave_prompt = "dramatic wave, the Oceans roar, Strong wave spiral across the oceans as the waves unfurl into roaring crests; perfect wave form; perfect wave shape; dramatic wave shape; wave shape unbelievable; wave; wave shape spectacular"

image = pipe(prompt=wave_prompt).images[0]
image

對於文字到影像,我們使用 `stabilityai/stable-diffusion-2-1-unclip-small`,因為它是在 CLIP ViT-L/14 嵌入上訓練的,與 Karlo 模型先驗相同。不建議使用 stabilityai/stable-diffusion-2-1-unclip,因為它是在 OpenCLIP ViT-H 上訓練的。

文字引導影像到影像變體

from diffusers import StableUnCLIPImg2ImgPipeline
from diffusers.utils import load_image
import torch

pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-2-1-unclip", torch_dtype=torch.float16, variation="fp16"
)
pipe = pipe.to("cuda")

url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/tarsila_do_amaral.png"
init_image = load_image(url)

images = pipe(init_image).images
images[0].save("variation_image.png")

(可選)您也可以將提示詞傳遞給 `pipe`,例如

prompt = "A fantasy landscape, trending on artstation"

image = pipe(init_image, prompt=prompt).images[0]
image

請務必檢視排程器 指南,瞭解如何探索排程器速度和質量之間的權衡,並檢視跨管道重用元件部分,瞭解如何有效地將相同元件載入到多個管道中。

StableUnCLIPPipeline

class diffusers.StableUnCLIPPipeline

< >

( prior_tokenizer: CLIPTokenizer prior_text_encoder: CLIPTextModelWithProjection prior: PriorTransformer prior_scheduler: KarrasDiffusionSchedulers image_normalizer: StableUnCLIPImageNormalizer image_noising_scheduler: KarrasDiffusionSchedulers tokenizer: CLIPTokenizer text_encoder: CLIPTextModel unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers vae: AutoencoderKL )

引數

  • prior_tokenizer (CLIPTokenizer) — 一個 CLIPTokenizer
  • prior_text_encoder (CLIPTextModelWithProjection) — 凍結的 CLIPTextModelWithProjection 文字編碼器。
  • prior (PriorTransformer) — 用於從文字嵌入中近似影像嵌入的規範 unCLIP 先驗。
  • prior_scheduler (KarrasDiffusionSchedulers) — 在先驗去噪過程中使用的排程器。
  • image_normalizer (StableUnCLIPImageNormalizer) — 用於在應用噪聲之前規範化預測的影像嵌入,並在應用噪聲之後反規範化影像嵌入。
  • image_noising_scheduler (KarrasDiffusionSchedulers) — 用於向預測影像嵌入新增噪聲的噪聲排程器。要新增的噪聲量由 `noise_level` 決定。
  • tokenizer (CLIPTokenizer) — 一個 CLIPTokenizer
  • text_encoder (CLIPTextModel) — 凍結的 CLIPTextModel 文字編碼器。
  • unet (UNet2DConditionModel) — 一個用於對編碼影像潛在進行去噪的 UNet2DConditionModel
  • scheduler (KarrasDiffusionSchedulers) — 與 unet 結合使用的排程器,用於對編碼影像潛在進行去噪。
  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。

用於文字到影像生成的 Stable unCLIP 管道。

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

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

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 20 guidance_scale: float = 10.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Optional[torch._C.Generator] = 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 noise_level: int = 0 prior_num_inference_steps: int = 25 prior_guidance_scale: float = 4.0 prior_latents: typing.Optional[torch.Tensor] = None clip_skip: typing.Optional[int] = None ) ImagePipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,您需要傳遞 prompt_embeds
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。
  • num_inference_steps (int, 可選, 預設為 20) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • guidance_scale (float, 可選, 預設為 10.0) — 更高的指導比例值會促使模型生成與文字 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 輸入引數生成 negative_prompt_embeds
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ImagePipelineOutput 而不是普通元組。
  • callback (Callable, 可選) — 在推理過程中每 callback_steps 步呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — 呼叫 callback 函式的頻率。如果未指定,則在每一步都呼叫回撥。
  • cross_attention_kwargs (dict, 可選) — 如果指定,此 kwargs 字典將作為 op 引數傳遞給 self.processor 中定義的 AttentionProcessor
  • noise_level (int, 可選, 預設為 0) — 新增到影像嵌入的噪聲量。更高的 noise_level 會增加最終去噪影像的方差。有關更多詳細資訊,請參見 StableUnCLIPPipeline.noise_image_embeddings()
  • prior_num_inference_steps (int, 可選, 預設為 25) — 先驗去噪過程中的去噪步數。更多的去噪步數通常會帶來更高質量的影像,但會犧牲推理速度。
  • prior_guidance_scale (float, 可選, 預設為 4.0) — 更高的指導比例值會促使模型生成與文字 prompt 緊密相關的影像,但會犧牲影像質量。當 guidance_scale > 1 時啟用指導比例。
  • prior_latents (torch.Tensor, 可選) — 預先生成的高斯分佈取樣噪聲潛變數,用作先驗去噪過程中影像嵌入生成的輸入。可用於使用不同提示調整相同的生成。如果未提供,則使用提供的隨機 generator 進行取樣生成潛變數張量。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。

返回

ImagePipelineOutputtuple

如果 return_dict 為 True,則為 ~ pipeline_utils.ImagePipelineOutput,否則為 tuple。返回元組時,第一個元素是生成的影像列表。

用於生成的管道的呼叫函式。

示例

>>> import torch
>>> from diffusers import StableUnCLIPPipeline

>>> pipe = StableUnCLIPPipeline.from_pretrained(
...     "fusing/stable-unclip-2-1-l", torch_dtype=torch.float16
... )  # TODO update model path
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> images = pipe(prompt).images
>>> images[0].save("astronaut_horse.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_vae_slicing

< >

( )

啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_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 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_embeds 將從 negative_prompt 輸入引數生成。
  • lora_scale (float, 可選) — 將應用於文字編碼器所有 LoRA 層的 LoRA 比例(如果 LoRA 層已載入)。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。

將提示編碼為文字編碼器隱藏狀態。

noise_image_embeddings

< >

( image_embeds: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )

向影像嵌入新增噪聲。噪聲量由 noise_level 輸入控制。更高的 noise_level 會增加最終去噪影像的方差。

噪聲透過兩種方式施加:

  1. 噪聲時間表直接應用於嵌入。
  2. 將正弦時間嵌入向量附加到輸出。

兩種情況下,噪聲量都由相同的 noise_level 控制。

在應用噪聲之前,嵌入會被歸一化,並在應用噪聲之後解除歸一化。

StableUnCLIPImg2ImgPipeline

class diffusers.StableUnCLIPImg2ImgPipeline

< >

( feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection image_normalizer: StableUnCLIPImageNormalizer image_noising_scheduler: KarrasDiffusionSchedulers tokenizer: CLIPTokenizer text_encoder: CLIPTextModel unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers vae: AutoencoderKL )

引數

  • feature_extractor (CLIPImageProcessor) — 用於影像預處理的特徵提取器,在編碼之前。
  • image_encoder (CLIPVisionModelWithProjection) — 用於編碼影像的 CLIP 視覺模型。
  • image_normalizer (StableUnCLIPImageNormalizer) — 用於在施加噪聲之前對預測的影像嵌入進行歸一化,並在施加噪聲之後解除歸一化。
  • image_noising_scheduler (KarrasDiffusionSchedulers) — 用於向預測影像嵌入新增噪聲的噪聲時間表。要新增的噪聲量由 noise_level 決定。
  • tokenizer (~transformers.CLIPTokenizer) — 一個 [~transformers.CLIPTokenizer)]。
  • text_encoder (CLIPTextModel) — 凍結的 CLIPTextModel 文字編碼器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛變數進行去噪的 UNet2DConditionModel
  • scheduler (KarrasDiffusionSchedulers) — 與 unet 結合使用的排程器,用於對編碼影像潛變數進行去噪。
  • vae (AutoencoderKL) — 變分自動編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。

使用 stable unCLIP 進行文字引導影像到影像生成的管線。

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

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

__call__

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = None prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 20 guidance_scale: float = 10 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Optional[torch._C.Generator] = 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 noise_level: int = 0 image_embeds: typing.Optional[torch.Tensor] = None clip_skip: typing.Optional[int] = None ) ImagePipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 指導影像生成的提示或提示列表。如果未定義,將使用 prompt_embeds 或將提示初始化為 ""
  • image (torch.TensorPIL.Image.Image) — 表示影像批次的影像或張量。影像被編碼為其 CLIP 嵌入,unet 以此為條件。影像**未**透過 vae 編碼,然後像標準 Stable Diffusion 文字引導影像變體過程那樣用作去噪過程中的潛在表示。
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。
  • num_inference_steps (int, 可選, 預設為 20) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。
  • guidance_scale (float, 可選, 預設為 10.0) — 更高的引導尺度值會促使模型生成與文字 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) — 是否返回 ImagePipelineOutput 而不是普通的元組。
  • callback (Callable, 可選) — 一個函式,在推理過程中每 callback_steps 步呼叫一次。該函式以以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — 呼叫 callback 函式的頻率。如果未指定,則每一步都呼叫回撥。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,則作為 AttentionProcessor 的引數傳遞,如 self.processor 中定義。
  • noise_level (int, 可選, 預設為 0) — 新增到影像嵌入中的噪聲量。更高的 noise_level 會增加最終去噪影像中的方差。有關更多詳細資訊,請參見 StableUnCLIPPipeline.noise_image_embeddings()
  • image_embeds (torch.Tensor, 可選) — 預生成的 CLIP 嵌入,用於將 unet 作為條件。這些潛在變數不用於去噪過程。如果希望提供預生成的潛在變數,請將其作為 latents 傳遞給 __call__
  • clip_skip (int, 可選) — 在計算提示嵌入時,從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。

返回

ImagePipelineOutputtuple

如果 return_dict 為 True,則為 ~ pipeline_utils.ImagePipelineOutput,否則為 tuple。返回元組時,第一個元素是生成的影像列表。

用於生成的管道的呼叫函式。

示例

>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO

>>> from diffusers import StableUnCLIPImg2ImgPipeline

>>> pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1-unclip-small", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))

>>> prompt = "A fantasy landscape, trending on artstation"

>>> images = pipe(init_image, prompt).images
>>> images[0].save("fantasy_landscape.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_vae_slicing

< >

( )

啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_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 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_embeds 將從 negative_prompt 輸入引數生成。
  • lora_scale (float, 可選) — 應用於文字編碼器所有 LoRA 層的 LoRA 縮放(如果載入了 LoRA 層)。
  • clip_skip (int, 可選) — 在計算提示嵌入時,從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。

將提示編碼為文字編碼器隱藏狀態。

noise_image_embeddings

< >

( image_embeds: Tensor noise_level: int noise: typing.Optional[torch.Tensor] = None generator: typing.Optional[torch._C.Generator] = None )

向影像嵌入新增噪聲。噪聲量由 noise_level 輸入控制。更高的 noise_level 會增加最終去噪影像的方差。

噪聲透過兩種方式施加:

  1. 噪聲時間表直接應用於嵌入。
  2. 將正弦時間嵌入向量附加到輸出。

兩種情況下,噪聲量都由相同的 noise_level 控制。

在應用噪聲之前,嵌入會被歸一化,並在應用噪聲之後解除歸一化。

ImagePipelineOutput

class diffusers.ImagePipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )

引數

  • images (List[PIL.Image.Image]np.ndarray) — 去噪後的 PIL 影像列表,長度為 batch_size,或形狀為 (batch_size, height, width, num_channels) 的 NumPy 陣列。

影像流水線的輸出類。

< > 在 GitHub 上更新

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