Diffusers 文件
潛在一致性模型
並獲得增強的文件體驗
開始使用
潛在一致性模型
潛在一致性模型 (LCM) 是由 Simian Luo、Yiqin Tan、Longbo Huang、Jian Li 和 Hang Zhao 在《潛在一致性模型:用少量步驟推理合成高解析度影像》中提出的。
論文摘要如下:
潛在擴散模型 (LDM) 在合成高解析度影像方面取得了顯著成果。然而,迭代取樣過程計算量大,導致生成速度慢。受一致性模型 (song et al.) 的啟發,我們提出了潛在一致性模型 (LCM),可以在任何預訓練 LDM(包括 Stable Diffusion (rombach et al))上實現以最少步驟進行快速推理。將引導反向擴散過程視為求解增強機率流 ODE (PF-ODE),LCM 旨在直接預測潛在空間中此類 ODE 的解,從而減少大量迭代的需要,並實現快速、高保真取樣。從預訓練的無分類器引導擴散模型中高效提取,一個高質量的 768 x 768 2~4 步 LCM 僅需 32 A100 GPU 小時進行訓練。此外,我們引入了潛在一致性微調 (LCF),這是一種專為在定製影像資料集上微調 LCM 而量身定製的新穎方法。在 LAION-5B-Aesthetics 資料集上的評估表明,LCM 在少量步驟推理下實現了最先進的文字到影像生成效能。專案頁面:this https URL。
SimianLuo/LCM_Dreamshaper_v7 檢查點的演示可以在此處找到。
該管道由luosiallen、nagolinc 和dg845貢獻。
LatentConsistencyModelPipeline
類 diffusers.LatentConsistencyModelPipeline
< 來源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: LCMScheduler safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自動編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器(clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於對文字進行標記的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 與
unet
結合使用,用於對編碼影像潛在表示進行去噪的排程器。目前僅支援 LCMScheduler。 - safety_checker (
StableDiffusionSafetyChecker
) — 用於評估生成影像是否可能被視為冒犯性或有害的分類模組。有關模型潛在危害的更多詳細資訊,請參閱模型卡片。 - feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。 - requires_safety_checker (
bool
, 可選, 預設為True
) — 管道是否需要安全檢查器元件。
用於使用潛在一致性模型進行文字到影像生成的管道。
此模型繼承自DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請參閱超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 4 original_inference_steps: int = None timesteps: typing.List[int] = None guidance_scale: float = 8.5 num_images_per_prompt: typing.Optional[int] = 1 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → StableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[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
, 可選, 預設為 50) — 去噪步驟數。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。 - original_inference_steps (
int
, 可選) — 用於生成線性間隔時間步長的原始推理步驟數,我們將從中均勻間隔抽取num_inference_steps
個時間步長作為最終的時間步長排程,遵循論文中的跳步方法(參見 4.3 節)。如果未設定,則預設為排程器的original_inference_steps
屬性。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步長。如果未定義,將使用原始 LCM 訓練/蒸餾時間步長排程中均勻間隔的num_inference_steps
個時間步長。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 7.5) — 較高的引導比例值鼓勵模型生成與文字prompt
緊密相關的影像,但會以較低的影像質量為代價。當guidance_scale > 1
時啟用引導比例。請注意,原始潛在一致性模型論文使用不同的 CFG 公式,其中引導比例減少 1(因此在論文公式中,當guidance_scale > 0
時啟用 CFG)。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, 可選) — 從高斯分佈取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則使用提供的隨機generator
進行取樣生成一個潛在張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示詞加權)。如果未提供,則從prompt
輸入引數生成文字嵌入。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預生成的用於 IP-Adapter 的影像嵌入。它應該是一個長度與 IP 介面卡數量相同的列表。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,則從ip_adapter_image
輸入引數計算嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,則傳遞給self.processor
中定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 計算提示詞嵌入時要跳過的 CLIP 層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理過程中每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類的._callback_tensor_inputs
屬性中列出的變數。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是布林值列表,指示相應的生成影像是否包含“不適合工作”(nsfw) 內容。
用於生成的管道的呼叫函式。
示例
>>> from diffusers import DiffusionPipeline
>>> import torch
>>> pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)
>>> prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=8.0).images
>>> images[0].save("image.png")
啟用 FreeU
< source >( s1: float s2: float b1: float b2: float )
啟用FreeU機制,詳見 https://huggingface.co/papers/2309.11497。
縮放因子後面的字尾表示它們應用的階段。
有關Stable Diffusion v1、v2和Stable Diffusion XL等不同管道的已知良好值組合,請參閱官方倉庫。
如果FreeU機制已啟用,則停用它。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
encode_prompt
< source >( prompt: str 或 List[str] device: torch.device num_images_per_prompt: int do_classifier_free_guidance: bool 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表示將使用倒數第二層的輸出計算提示詞嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
LatentConsistencyModelImg2ImgPipeline
class diffusers.LatentConsistencyModelImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: LCMScheduler safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 變分自編碼器(VAE)模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器(clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 一個用於標記化文字的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 一個
UNet2DConditionModel
模型,用於對編碼影像的潛在表示進行去噪。 - scheduler (SchedulerMixin) — 一個與
unet
結合使用的排程器,用於對編碼影像的潛在表示進行去噪。目前僅支援 LCMScheduler。 - safety_checker (
StableDiffusionSafetyChecker
) — 用於評估生成影像是否可能具有冒犯性或有害性的分類模組。有關模型潛在危害的更多詳細資訊,請參閱模型卡。 - feature_extractor (CLIPImageProcessor) — 一個用於從生成的影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。 - requires_safety_checker (
bool
, 可選, 預設為True
) — 管道是否需要安全檢查器元件。
用於影像到影像生成的潛在一致性模型管道。
此模型繼承自DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請參閱超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( 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 = 4 strength: float = 0.8 original_inference_steps: int = None timesteps: typing.List[int] = None guidance_scale: float = 8.5 num_images_per_prompt: typing.Optional[int] = 1 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs: Any ) → StableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[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
, 可選, 預設為50) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但推理速度會變慢。 - original_inference_steps (
int
, 可選) — 用於生成線性間隔時間步計劃的原始推理步數,我們將從中抽取num_inference_steps
個均勻間隔的時間步作為最終時間步計劃,遵循論文中的跳過步長法(參見第4.3節)。如果未設定,這將預設為排程器的original_inference_steps
屬性。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,則使用原始LCM訓練/蒸餾時間步計劃上等距的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為7.5) — 更高的引導尺度值鼓勵模型生成與文字prompt
緊密相關的影像,但影像質量會降低。當guidance_scale > 1
時啟用引導尺度。請注意,原始潛在一致性模型論文中使用了不同的CFG公式,其中引導尺度減少了1(因此在論文公式中,當guidance_scale > 0
時啟用CFG)。 - num_images_per_prompt (
int
, 可選, 預設為1) — 每個提示詞要生成的影像數量。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個torch.Generator
,用於使生成具有確定性。 - latents (
torch.Tensor
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同提示詞調整相同的生成。如果未提供,則使用提供的隨機generator
進行取樣生成一個潛在表示張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示詞權重)。如果未提供,文字嵌入將根據prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選):與IP介面卡一起使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — IP-Adapter的預生成影像嵌入。它應該是一個長度與IP介面卡數量相同的列表。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將傳遞給self.processor
中定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 計算提示詞嵌入時要跳過CLIP的層數。值為1表示將使用倒數第二層的輸出計算提示詞嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理過程中每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是布林值列表,指示相應的生成影像是否包含“不適合工作”(nsfw) 內容。
用於生成的管道的呼叫函式。
示例
>>> from diffusers import AutoPipelineForImage2Image
>>> import torch
>>> import PIL
>>> pipe = AutoPipelineForImage2Image.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)
>>> prompt = "High altitude snowy mountains"
>>> image = PIL.Image.open("./snowy_mountains.png")
>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(
... prompt=prompt, image=image, num_inference_steps=num_inference_steps, guidance_scale=8.0
... ).images
>>> images[0].save("image.png")
啟用 FreeU
< source >( s1: float s2: float b1: float b2: float )
啟用FreeU機制,詳見 https://huggingface.co/papers/2309.11497。
縮放因子後面的字尾表示它們應用的階段。
有關Stable Diffusion v1、v2和Stable Diffusion XL等不同管道的已知良好值組合,請參閱官方倉庫。
如果FreeU機制已啟用,則停用它。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
encode_prompt
< source >( prompt: str 或 List[str] device: torch.device num_images_per_prompt: int do_classifier_free_guidance: bool 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_embeds
將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 將應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子(如果已載入 LoRA 層)。 - clip_skip (
int
, 可選) — 從 CLIP 跳過的層數,用於計算提示詞嵌入。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
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 管道的輸出類。