Diffusers 文件

擾動注意力引導

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

擾動注意力引導

LoRA

擾動注意力引導 (PAG) 是一種新的擴散取樣引導方法,它在無條件和條件設定下都能提高樣本質量,無需額外訓練或整合外部模組。

PAG 在 Donghoon Ahn, Hyoungwon Cho, Jaewon Min, Wooseok Jang, Jungwoo Kim, SeonHwa Kim, Hyun Hee Park, Kyong Hwan Jin 和 Seungryong Kim 的論文 《基於擾動注意力引導的自校正擴散取樣》 中引入。

論文摘要如下:

最近的研究表明,擴散模型能夠生成高質量樣本,但其質量嚴重依賴於取樣引導技術,例如分類器引導 (CG) 和無分類器引導 (CFG)。這些技術通常不適用於無條件生成或各種下游任務,如影像修復。在本文中,我們提出了一種新的取樣引導方法,稱為擾動注意力引導 (PAG),它在無條件和條件設定下都能提高擴散樣本質量,無需額外訓練或整合外部模組。PAG 旨在在整個去噪過程中逐步增強樣本結構。它透過將擴散 U-Net 中選定的自注意力圖替換為單位矩陣,考慮到自注意力機制捕捉結構資訊的能力,並引導去噪過程遠離這些降級樣本,從而生成具有降級結構的中間樣本。在 ADM 和 Stable Diffusion 中,PAG 令人驚訝地提高了條件甚至無條件場景下的樣本質量。此外,PAG 顯著提高了現有引導(如 CG 或 CFG)無法充分利用的各種下游任務的基線效能,包括帶有空提示的 ControlNet 以及影像修復(如影像修補和去模糊)。

可以透過在例項化 PAG 管道時將 `pag_applied_layers` 指定為引數來使用 PAG。它可以是單個字串或字串列表。每個字串可以是唯一的層識別符號或用於標識一個或多個層的正則表示式。

  • 作為普通字串的完整識別符號:`down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor`
  • 作為正則表示式的完整識別符號:`down_blocks.2.(attentions|motion_modules).0.transformer_blocks.0.attn1.processor`
  • 作為正則表示式的部分識別符號:`down_blocks.2` 或 `attn1`
  • 識別符號列表(可以是字串和正則表示式的組合):`["blocks.1", "blocks.(14|20)", r"down_blocks\.(2,3)"]`

由於支援正則表示式作為匹配層識別符號的方式,因此正確使用它至關重要,否則可能會出現意外行為。推薦的使用 PAG 方式是將層指定為 `blocks.{layer_index}` 和 `blocks.({layer_index_1|layer_index_2|...})`。以任何其他方式使用它雖然可行,但可能會繞過我們的基本驗證檢查並給出意外結果。

AnimateDiffPAGPipeline

class diffusers.AnimateDiffPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter scheduler: KarrasDiffusionSchedulers feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid_block.*attn1' )

引數

使用 AnimateDiff擾動注意力引導 進行文字到影片生成的管道。

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

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

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None num_frames: typing.Optional[int] = 16 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_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 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'] decode_chunk_size: int = 16 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) AnimateDiffPipelineOutput or tuple

引數

  • prompt (str or 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_frames (int, 可選, 預設為 16) — 生成的影片幀數。預設為 16 幀,按每秒 8 幀計算,相當於 2 秒影片。
  • 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 進行取樣以生成潛在張量。潛在表示的形狀應為 (batch_size, num_channel, num_frames, height, width)
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示加權)。如果未提供,則文字嵌入從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入(提示加權)。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選): 與 IP 介面卡配合使用的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — 預生成的 IP-Adapter 影像嵌入。它應該是一個長度與 IP-adapter 數量相同的列表。每個元素都應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負影像嵌入。如果未提供,則從 ip_adapter_image 輸入引數計算嵌入。
  • output_type (str, 可選, 預設為 "pil") — 生成影片的輸出格式。在 torch.TensorPIL.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 TextToVideoSDPipelineOutput 而不是普通的元組。
  • 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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

AnimateDiffPipelineOutputtuple

如果 return_dictTrue,則返回 AnimateDiffPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的幀列表。

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

示例

>>> import torch
>>> from diffusers import AnimateDiffPAGPipeline, MotionAdapter, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-2"
>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id)
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id, subfolder="scheduler", beta_schedule="linear", steps_offset=1, clip_sample=False
... )
>>> pipe = AnimateDiffPAGPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     scheduler=scheduler,
...     pag_applied_layers=["mid"],
...     torch_dtype=torch.float16,
... ).to("cuda")

>>> video = pipe(
...     prompt="car, futuristic cityscape with neon lights, street, no human",
...     negative_prompt="low quality, bad quality",
...     num_inference_steps=25,
...     guidance_scale=6.0,
...     pag_scale=3.0,
...     generator=torch.Generator().manual_seed(42),
... ).frames[0]

>>> export_to_gif(video, "animatediff_pag.gif")

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 表示使用倒數第二層的輸出計算提示嵌入。

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

HunyuanDiTPAGPipeline

class diffusers.HunyuanDiTPAGPipeline

< >

( vae: AutoencoderKL text_encoder: BertModel tokenizer: BertTokenizer transformer: HunyuanDiT2DModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None requires_safety_checker: bool = True text_encoder_2: typing.Optional[transformers.models.t5.modeling_t5.T5EncoderModel] = None tokenizer_2: typing.Optional[transformers.models.mt5.tokenization_mt5.MT5Tokenizer] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。我們使用 sdxl-vae-fp16-fix
  • text_encoder (Optional[~transformers.BertModel, ~transformers.CLIPTextModel]) — 凍結文字編碼器 (clip-vit-large-patch14)。HunyuanDiT 使用一個經過微調的 [bilingual CLIP]。
  • tokenizer (Optional[~transformers.BertTokenizer, ~transformers.CLIPTokenizer]) — 用於文字分詞的 BertTokenizerCLIPTokenizer
  • transformer (HunyuanDiT2DModel) — 騰訊混元設計的 HunyuanDiT 模型。
  • text_encoder_2 (T5EncoderModel) — mT5 嵌入器。具體來說,它是 't5-v1_1-xxl'。
  • tokenizer_2 (MT5Tokenizer) — mT5 嵌入器的分詞器。
  • scheduler (DDPMScheduler) — 與 HunyuanDiT 結合使用,用於對編碼影像潛在表示去噪的排程器。

使用 HunyuanDiT 和擾動注意力引導進行中英文影像生成。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

HunyuanDiT 使用兩個文字編碼器:mT5 和 [雙語 CLIP](我們自己微調的)

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = 50 guidance_scale: typing.Optional[float] = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[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 prompt_embeds_2: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None prompt_attention_mask_2: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = (1024, 1024) target_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) use_resolution_binning: bool = True pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 引導影像生成的提示。如果未定義,則需要傳遞 prompt_embeds
  • height (int) — 生成影像的高度(畫素)。
  • width (int) — 生成影像的寬度(畫素)。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會導致更高質量的影像,但推理速度會變慢。此引數受 strength 調製。
  • 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,用於使生成具有確定性。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可以輕鬆調整文字輸入(提示權重)。如果未提供,則文字嵌入將從 prompt 輸入引數生成。
  • prompt_embeds_2 (torch.Tensor, 可選) — 預生成的文字嵌入。可以輕鬆調整文字輸入(提示權重)。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可以輕鬆調整文字輸入(提示權重)。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • negative_prompt_embeds_2 (torch.Tensor, 可選) — 預生成的負文字嵌入。可以輕鬆調整文字輸入(提示權重)。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • prompt_attention_mask (torch.Tensor, 可選) — 提示的注意力掩碼。當直接傳遞 prompt_embeds 時,此引數為必需。
  • prompt_attention_mask_2 (torch.Tensor, 可選) — 提示的注意力掩碼。當直接傳遞 prompt_embeds_2 時,此引數為必需。
  • negative_prompt_attention_mask (torch.Tensor, 可選) — 負提示的注意力掩碼。當直接傳遞 negative_prompt_embeds 時,此引數為必需。
  • negative_prompt_attention_mask_2 (torch.Tensor, 可選) — 負提示的注意力掩碼。當直接傳遞 negative_prompt_embeds_2 時,此引數為必需。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • callback_on_step_end (Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks, 可選) — 在每個去噪步驟結束時呼叫的回撥函式或回撥函式列表。
  • callback_on_step_end_tensor_inputs (List[str], 可選) — 應該傳遞給回撥函式的張量輸入列表。如果未定義,則所有張量輸入都將被傳遞。
  • guidance_rescale (float, 可選, 預設為 0.0) — 根據 guidance_rescale 重新縮放 noise_cfg。基於 Common Diffusion Noise Schedules and Sample Steps are Flawed 的發現。參見第 3.4 節
  • original_size (Tuple[int, int], 可選, 預設為 (1024, 1024)) — 影像的原始大小。用於計算時間 ID。
  • target_size (Tuple[int, int], optional) — 影像的目標大小。用於計算時間 ID。
  • crops_coords_top_left (Tuple[int, int], optional, defaults to (0, 0)) — 裁剪的左上角座標。用於計算時間 ID。
  • use_resolution_binning (bool, optional, defaults to True) — 是否使用解析度分箱。如果為 True,輸入解析度將對映到最接近的標準解析度。支援的解析度為 1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768 和 768x1280。建議設定為 True
  • pag_scale (float, optional, defaults to 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, optional, defaults to 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw)內容的 bool 列表。

使用 HunyuanDiT 生成的管線呼叫函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=[14],
... ).to("cuda")

>>> # prompt = "an astronaut riding a horse"
>>> prompt = "一個宇航員在騎馬"
>>> image = pipe(prompt, guidance_scale=4, pag_scale=3).images[0]

encode_prompt

< >

( prompt: str device: device = None dtype: dtype = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None max_sequence_length: typing.Optional[int] = None text_encoder_index: int = 0 )

引數

  • prompt (strList[str], 可選) — 要編碼的提示詞
  • device — (torch.device): torch 裝置
  • dtype (torch.dtype) — 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 輸入引數生成。
  • prompt_attention_mask (torch.Tensor, 可選) — 提示詞的注意力掩碼。當直接傳入 prompt_embeds 時必需。
  • negative_prompt_attention_mask (torch.Tensor, 可選) — 負面提示詞的注意力掩碼。當直接傳入 negative_prompt_embeds 時必需。
  • max_sequence_length (int, 可選) — 用於提示詞的最大序列長度。
  • text_encoder_index (int, 可選) — 要使用的文字編碼器索引。0 表示 clip,1 表示 T5。

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

KolorsPAGPipeline

diffusers.KolorsPAGPipeline

< >

( vae: AutoencoderKL text_encoder: ChatGLMModel tokenizer: ChatGLMTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = False pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (ChatGLMModel) — 凍結文字編碼器。Kolors 使用 ChatGLM3-6B
  • tokenizer (ChatGLMTokenizer) — 類 ChatGLMTokenizer 的分詞器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的條件 U-Net 架構。
  • scheduler (SchedulerMixin) — 一個與 unet 結合使用的排程器,用於對編碼影像潛在表示進行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可選, 預設為 "False") — 是否強制將負面提示嵌入始終設定為 0。另請參閱 Kwai-Kolors/Kolors-diffusers 的配置。
  • pag_applied_layers (strList[str]``, *可選*, 預設為 “mid”`) — 設定應用擾動注意力引導的 transformer 注意力層。可以是字串或字串列表,包括“down”、“mid”、“up”、整個 transformer 塊或特定的 transformer 塊注意力層,例如:[“mid”][“down”, “mid”] [“down”, “mid”, “up.block_1”][“down”, “mid”, “up.block_1.attentions_0”, “up.block_1.attentions_1”]

使用 Kolors 進行文字到影像生成的管線。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.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.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 max_sequence_length: int = 256 ) ~pipelines.kolors.KolorsPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 引導影像生成的提示詞。如果未定義,則必須傳入 prompt_embeds
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳結果,預設設定為 1024。對於 Kwai-Kolors/Kolors-diffusers 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都無法正常工作。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳結果,預設設定為 1024。對於 Kwai-Kolors/Kolors-diffusers 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都無法正常工作。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會生成更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步長,適用於支援 set_timesteps 方法中 timesteps 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,適用於支援 set_timesteps 方法中 sigmas 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。
  • denoising_end (float, 可選) — 指定時,確定在故意提前終止之前要完成的總去噪過程的比例(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留由排程器選擇的離散時間步長確定的相當數量的噪聲。當此管線構成“去噪器混合”多管線設定的一部分時,應理想地使用 denoising_end 引數,如 最佳化影像輸出 中所詳述。
  • guidance_scale (float, 可選, 預設為 5.0) — 如 Classifier-Free Diffusion Guidance 中所定義的引導比例。guidance_scale 定義為 Imagen Paper 中公式 2 的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例鼓勵生成與文字 prompt 密切相關的影像,但通常會犧牲影像質量。
  • negative_prompt (strList[str], 可選) — 不引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1 則忽略),此引數將被忽略。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞生成的影像數量。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。
  • latents (torch.Tensor, 可選) — 預先生成的噪聲潛在變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示詞調整相同的生成。如果未提供,將透過使用提供的隨機 generator 取樣生成一個潛在變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化負面提示嵌入將從 negative_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: PIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.kolors.KolorsPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將作為 self.processor 中定義的 AttentionProcessor 的引數傳遞到 diffusers.models.attention_processor
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 original_sizetarget_size 不同,影像將顯示為縮小或放大。如果未指定,original_size 預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 中 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — crops_coords_top_left 可用於生成從 crops_coords_top_left 位置向下“裁剪”的影像。透過將 crops_coords_top_left 設定為 (0, 0),通常可以獲得有利的、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 中 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size 應設定為生成影像的所需高度和寬度。如果未指定,它將預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 中 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於根據特定影像解析度對生成過程進行負向條件。作為 SDXL 微觀條件的一部分,詳見 https://huggingface.co/papers/2307.01952 第 2.2 節。欲瞭解更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 用於根據特定裁剪座標對生成過程進行負向條件。作為 SDXL 微觀條件的一部分,詳見 https://huggingface.co/papers/2307.01952 第 2.2 節。欲瞭解更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於根據目標影像解析度對生成過程進行負向條件。在大多數情況下,它應該與 target_size 相同。作為 SDXL 微觀條件的一部分,詳見 https://huggingface.co/papers/2307.01952 第 2.2 節。欲瞭解更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類。引數如下: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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale
  • max_sequence_length (int 預設為 256) — 與 prompt 一起使用的最大序列長度。

返回

~pipelines.kolors.KolorsPipelineOutputtuple

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

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Kwai-Kolors/Kolors-diffusers",
...     variant="fp16",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["down.block_2.attentions_1", "up.block_0.attentions_1"],
... )
>>> pipe = pipe.to("cuda")

>>> prompt = (
...     "A photo of a ladybug, macro, zoom, high quality, film, holding a wooden sign with the text 'KOLORS'"
... )
>>> image = pipe(prompt, guidance_scale=5.5, pag_scale=1.5).images[0]

encode_prompt

< >

( prompt device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 256 )

引數

  • 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.FloatTensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化 negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • max_sequence_length (int 預設為 256) — 與 prompt 一起使用的最大序列長度。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導尺度的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 待生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionPAGInpaintPipeline

class diffusers.StableDiffusionPAGInpaintPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於文字分詞的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於去噪編碼影像潛在的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 用於與 unet 結合去噪編碼影像潛在的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一個。
  • safety_checker (StableDiffusionSafetyChecker) — 評估生成影像是否可能具有冒犯性或有害的分類模組。有關模型潛在危害的更多詳細資訊,請參閱模型卡
  • feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的 CLIPImageProcessor;用作 safety_checker 的輸入。

用於使用 Stable Diffusion 進行文字到影像生成的管道。

此模型繼承自 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 mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 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 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 guidance_rescale: float = 0.0 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

引數

  • 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, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會生成更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步長,適用於在 set_timesteps 方法中支援 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,適用於在 set_timesteps 方法中支援 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • 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 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選): 用於 IP 介面卡的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — 預生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負向影像嵌入。如果未提供,嵌入將從 ip_adapter_image 輸入引數計算。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。選擇 PIL.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是純元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給 self.processor 中定義的 AttentionProcessor
  • guidance_rescale (float, 可選, 預設為 0.0) — 來自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的引導重縮放因子。當使用零終端 SNR 時,引導重縮放因子應修復過曝。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 中跳過的層數。值為 1 表示將使用預最終層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類,帶有以下引數: 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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,將不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw)內容的 bool 列表。

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

示例

>>> import torch
>>> from diffusers import AutoPipelineForInpainting

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=0.8,
...     num_inference_steps=50,
...     guidance_scale=guidance_scale,
...     generator=generator,
...     pag_scale=pag_scale,
... ).images[0]

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 輸入引數生成 negative_prompt_embeds。
  • lora_scale (float, 可選) — 如果載入了 LoRA 層,則應用於文字編碼器所有 LoRA 層的 LoRA 比例。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導尺度的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入的維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionPAGPipeline

diffusers.StableDiffusionPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於對文字進行分詞的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 與 unet 結合使用的排程器,用於對編碼影像潛在表示進行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分類模組,用於評估生成的影像是否可能被認為是冒犯性或有害的。有關模型潛在危害的更多詳細資訊,請參閱模型卡
  • feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的 CLIPImageProcessor;用作 safety_checker 的輸入。

用於使用 Stable Diffusion 進行文字到影像生成的管道。

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

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 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 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 guidance_rescale: float = 0.0 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

引數

  • 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, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步,適用於在其 set_timesteps 方法中支援 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigma,適用於在其 set_timesteps 方法中支援 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • 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 輸入引數生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, 可選): 與 IP 介面卡配合使用的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — 預生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 數量相同。每個元素應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負影像嵌入。如果未提供,嵌入將從 ip_adapter_image 輸入引數計算。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。選擇 PIL.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將傳遞給 self.processor 中定義的 AttentionProcessor
  • guidance_rescale (float, 可選, 預設為 0.0) — 來自《常見擴散噪聲排程和取樣步驟的缺陷》的引導重縮放因子。引導重縮放因子應該在零終端 SNR 時修復過度曝光。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類,具有以下引數: 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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw)內容的 bool 列表。

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

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

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 表示將使用倒數第二層的輸出計算提示詞嵌入。

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

get_guidance_scale_embedding

< 來源 >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成帶有指定引導比例的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionPAGImg2ImgPipeline

class diffusers.StableDiffusionPAGImg2ImgPipeline

< 來源 >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於標記文字的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於去噪編碼影像潛在的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 用於與 unet 結合以去噪編碼影像潛在的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分類模組,用於估計生成的影像是否可能具有攻擊性或有害。有關模型潛在危害的更多詳細資訊,請參閱模型卡
  • feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的 CLIPImageProcessor;用作 safety_checker 的輸入。

用於使用 Stable Diffusion 進行文字引導的影像到影像生成管道。

此模型繼承自 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 strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: typing.Optional[float] = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_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: int = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutput or tuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則需要傳遞 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image、numpy 陣列或表示要用作起點的影像批次的張量。對於 numpy 陣列和 pytorch 張量,預期值範圍在 [0, 1] 之間。如果是張量或張量列表,則預期形狀應為 (B, C, H, W)(C, H, W)。如果是 numpy 陣列或陣列列表,則預期形狀應為 (B, H, W, C)(H, W, C)。它也可以接受影像潛在表示作為 image,但如果直接傳遞潛在表示,則不會再次對其進行編碼。
  • strength (float, 可選, 預設為 0.8) — 指示轉換參考 image 的程度。必須介於 0 和 1 之間。image 用作起點,strength 越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當 strength 為 1 時,新增的噪聲最大,去噪過程將執行 num_inference_steps 中指定的完整迭代次數。值為 1 基本上忽略了 image
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會導致更高質量的影像,但推理速度會變慢。此引數受 strength 調製。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步,適用於其 set_timesteps 方法支援 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,適用於其 set_timesteps 方法支援 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • 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
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示詞權重)。如果未提供,則根據 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入(提示詞權重)。如果未提供,則根據 negative_prompt 輸入引數生成 negative_prompt_embeds
  • 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.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給 self.processor 中定義的 AttentionProcessor
  • clip_skip (int, 可選) — 在計算提示詞嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類,具有以下引數: 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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw)內容的 bool 列表。

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

示例

>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

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 表示將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成帶有指定引導尺度的嵌入向量,以便後續豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionControlNetPAGPipeline

diffusers.StableDiffusionControlNetPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於標記文字的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於對編碼影像潛變數去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪過程中為 unet 提供額外條件。如果您將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出會相加,以建立一個組合的額外條件。
  • scheduler (SchedulerMixin) — 與 unet 結合使用以對編碼影像潛變數去噪的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一種。
  • safety_checker (StableDiffusionSafetyChecker) — 用於評估生成的影像是否可能具有冒犯性或有害性的分類模組。有關模型潛在危害的更多詳細資訊,請參閱 模型卡
  • feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的 CLIPImageProcessor;用作 safety_checker 的輸入。

使用 Stable Diffusion 和 ControlNet 引導的文字到影像生成管道。

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

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

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 表示將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成帶有指定引導尺度的嵌入向量,以便後續豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionControlNetPAGInpaintPipeline

diffusers.StableDiffusionControlNetPAGInpaintPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於標記文字的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於對編碼影像潛變數去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪過程中為 unet 提供額外條件。如果您將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出會相加,以建立一個組合的額外條件。
  • scheduler (SchedulerMixin) — 與 unet 結合使用以對編碼影像潛變數去噪的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一種。
  • safety_checker (StableDiffusionSafetyChecker) — 用於評估生成的影像是否可能具有冒犯性或有害性的分類模組。有關模型潛在危害的更多詳細資訊,請參閱 模型卡
  • feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的 CLIPImageProcessor;用作 safety_checker 的輸入。

使用 Stable Diffusion 和 ControlNet 引導的影像修復管道。

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

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

此管道可用於專門為修復微調過的檢查點 (runwayml/stable-diffusion-inpainting) 以及預設的文字到影像 Stable Diffusion 檢查點 (runwayml/stable-diffusion-v1-5)。預設的文字到影像 Stable Diffusion 檢查點可能更適合那些基於它們進行微調的 ControlNet,例如 lllyasviel/control_v11p_sd15_inpaint

__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 mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 guidance_scale: float = 7.5 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 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.5 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,您需要傳遞 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], — List[PIL.Image.Image]List[np.ndarray]): Image、NumPy 陣列或表示要用作起始點的影像批處理的張量。對於 NumPy 陣列和 PyTorch 張量,預期值範圍在 [0, 1] 之間。如果是張量或張量列表,則預期形狀應為 (B, C, H, W)(C, H, W)。如果是 NumPy 陣列或陣列列表,則預期形狀應為 (B, H, W, C)(H, W, C)。它也可以接受影像潛變數作為 image,但如果直接傳遞潛變數,則不會再次編碼。
  • mask_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], — List[PIL.Image.Image]List[np.ndarray]): Image、NumPy 陣列或表示要遮罩 image 的影像批處理的張量。遮罩中白色畫素會重繪,而黑色畫素會保留。如果 mask_image 是 PIL 影像,它在使用前會轉換為單通道(亮度)。如果是 NumPy 陣列或 PyTorch 張量,它應該包含一個顏色通道 (L) 而不是 3 個,因此 PyTorch 張量的預期形狀為 (B, 1, H, W)(B, H, W)(1, H, W)(H, W)。對於 NumPy 陣列,則為 (B, H, W, 1)(B, H, W)(H, W, 1)(H, W)
  • control_image (torch.Tensor, PIL.Image.Image, List[torch.Tensor], List[PIL.Image.Image], — List[List[torch.Tensor]]List[List[PIL.Image.Image]]): ControlNet 輸入條件,為 unet 提供生成指導。如果型別指定為 torch.Tensor,則直接傳遞給 ControlNet。PIL.Image.Image 也可以作為影像接受。輸出影像的尺寸預設為 image 的尺寸。如果傳遞了 height 和/或 width,image 將相應地調整大小。如果在 init 中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確批處理以輸入到單個 ControlNet。
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。
  • padding_mask_crop (int, 可選, 預設為 None) — 應用於影像和遮罩的裁剪邊距大小。如果為 None,則不應用裁剪。如果 padding_mask_crop 不為 None,它將首先找到一個與影像長寬比相同幷包含所有遮罩區域的矩形區域,然後根據 padding_mask_crop 擴充套件該區域。然後,影像和遮罩影像將根據擴充套件區域進行裁剪,再調整大小到原始影像尺寸進行修復。當遮罩區域很小而影像很大且包含與修復無關的資訊(例如背景)時,這很有用。
  • strength (float, 可選, 預設為 1.0) — 表示轉換參考 image 的程度。必須介於 0 和 1 之間。image 用作起點,strength 越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當 strength 為 1 時,新增的噪聲最大,去噪過程將執行 num_inference_steps 中指定的完整迭代次數。值為 1 基本忽略 image
  • 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 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選):與 IP 介面卡配合使用的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負影像嵌入。如果未提供,則根據 ip_adapter_image 輸入引數計算嵌入。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。可選擇 PIL.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將傳遞給 self.processor 中定義的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 0.5) — ControlNet 的輸出在新增到原始 unet 中的殘差之前,乘以 controlnet_conditioning_scale。如果 init 中指定了多個 ControlNet,您可以將相應的比例設定為列表。
  • control_guidance_start (floatList[float], 可選, 預設為 0.0) — ControlNet 開始應用的步驟總數的百分比。
  • control_guidance_end (floatList[float], 可選, 預設為 1.0) — ControlNet 停止應用的步驟總數的百分比。
  • clip_skip (int, 可選) — 在計算提示嵌入時,要從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類,具有以下引數: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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw)內容的 bool 列表。

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

示例

>>> # !pip install transformers accelerate
>>> import cv2
>>> from diffusers import AutoPipelineForInpainting, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> from PIL import Image
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))


>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image


>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, enable_pag=True
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     pag_scale=0.3,
... ).images[0]

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):PyTorch 裝置
  • 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 表示將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導比例的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLPAGPipeline

class diffusers.StableDiffusionXLPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 變分自動編碼器(VAE)模型,用於將影像編碼和解碼為潛在表示。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字部分,特別是 clip-vit-large-patch14 變體。
  • text_encoder_2 (CLIPTextModelWithProjection) — 第二個凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字和池化部分,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。
  • tokenizer (CLIPTokenizer) — 類別 CLIPTokenizer 的分詞器。
  • tokenizer_2 (CLIPTokenizer) — 第二個類別 CLIPTokenizer 的分詞器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在變數進行去噪的條件 U-Net 架構。
  • scheduler (SchedulerMixin) — 用於與 unet 結合使用的排程器,以對編碼影像潛在變數進行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可選, 預設為 "True") — 負面提示嵌入是否應始終強制設定為 0。另請參閱 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可選) — 是否使用 invisible_watermark 庫 為輸出影像新增水印。如果未定義,如果安裝了該軟體包,則預設為 True,否則不使用水印。

用於使用 Stable Diffusion XL 進行文字到影像生成的管道。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞 prompt_embeds
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定義,則 prompt 將用於這兩個文字編碼器。
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。為獲得最佳效果,預設設定為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的模型檢查點,低於 512 畫素的任何值都無法很好地工作。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。為獲得最佳效果,預設設定為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的模型檢查點,低於 512 畫素的任何值都無法很好地工作。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 自定義時間步長,用於去噪過程,適用於其 set_timesteps 方法支援 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 自定義 sigma,用於去噪過程,適用於其 set_timesteps 方法支援 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • denoising_end (float, 可選) — 指定後,確定在故意提前終止之前要完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留由排程器選擇的離散時間步長確定的噪聲量。當此管道作為“去噪器混合”多管道設定的一部分使用時,理想情況下應使用 denoising_end 引數,如影像輸出最佳化中所述。
  • guidance_scale (float, 可選, 預設為 5.0) — 無分類器擴散引導中定義的引導比例。guidance_scaleImagen 論文的公式 2 中定義為 w。透過設定 guidance_scale > 1 啟用引導比例。較高的引導比例鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲較低影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1),則忽略。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成併發送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定義,則 negative_prompt 將用於這兩個文字編碼器。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示要生成的影像數量。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成確定。
  • latents (torch.Tensor, 可選) — 預生成的帶噪聲隱變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成隱變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,負文字嵌入將從 negative_prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化負文字嵌入將從 negative_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") — 生成影像的輸出格式。選擇 PILPIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,則作為 AttentionProcessor 傳遞給 diffusers.models.attention_processor 中的 self.processor
  • guidance_rescale (float, 可選, 預設為 0.0) — 常見擴散噪聲排程和取樣步長存在缺陷中提出的引導重定標因子。guidance_scale常見擴散噪聲排程和取樣步長存在缺陷的公式 16 中定義為 φ。引導重定標因子應在零末端信噪比(SNR)下修復過度曝光問題。
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 original_sizetarget_size 不同,影像將顯示為縮小或放大。如果未指定,original_size 預設為 (height, width)。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — crops_coords_top_left 可用於生成從 crops_coords_top_left 位置向下“裁剪”的影像。通常透過將 crops_coords_top_left 設定為 (0, 0) 來獲得有利的、居中的影像。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size 應設定為生成影像的期望高度和寬度。如果未指定,則預設為 (height, width)。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於基於特定影像解析度對生成過程進行負條件。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 用於基於特定裁剪座標對生成過程進行負條件。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於基於目標影像解析度對生成過程進行負條件。在大多數情況下應與 target_size 相同。作為 SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • 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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

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

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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 lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

引數

  • prompt (strList[str], 可選) — 要編碼的提示
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定義,則 prompt 將用於這兩個文字編碼器。
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示應生成的影像數量
  • do_classifier_free_guidance (bool) — 是否使用無分類器引導
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1),則忽略。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成併發送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定義,則 negative_prompt 將用於這兩個文字編碼器。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,負文字嵌入將從 negative_prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從`negative_prompt`輸入引數生成池化負向提示詞嵌入。
  • lora_scale (float, optional) — 如果載入了LoRA層,則應用於文字編碼器所有LoRA層的LoRA比例。
  • clip_skip (int, optional) — 從CLIP中跳過的層數,用於計算提示詞嵌入。值為1表示使用倒數第二層的輸出計算提示詞嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導尺度的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, optional, 預設為512) — 要生成的嵌入的維度。
  • dtype (torch.dtype, optional, 預設為torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLPAGImg2ImgPipeline

class diffusers.StableDiffusionXLPAGImg2ImgPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器(VAE)模型。
  • text_encoder (CLIPTextModel) — 凍結文字編碼器。Stable Diffusion XL使用CLIP的文字部分,特別是clip-vit-large-patch14變體。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二個凍結文字編碼器。Stable Diffusion XL使用CLIP的文字和池化部分,特別是laion/CLIP-ViT-bigG-14-laion2B-39B-b160k變體。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 類的分詞器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 類的第二個分詞器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛變數進行去噪的條件U-Net架構。
  • scheduler (SchedulerMixin) — 一個與unet結合使用以去噪編碼影像潛變數的排程器。可以是DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler之一。
  • requires_aesthetics_score (bool, optional, 預設為"False") — unet在推理期間是否需要傳遞aesthetic_score條件。另請參閱stabilityai/stable-diffusion-xl-refiner-1-0的配置。
  • force_zeros_for_empty_prompt (bool, optional, 預設為"True") — 負向提示詞嵌入是否應始終強制設定為0。另請參閱stabilityai/stable-diffusion-xl-base-1-0的配置。
  • add_watermarker (bool, optional) — 是否使用invisible_watermark 庫為輸出影像新增水印。如果未定義,則在安裝了該軟體包的情況下預設為True,否則不使用水印器。

用於使用 Stable Diffusion XL 進行文字到影像生成的管道。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 strength: float = 0.3 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞或提示詞列表。如果未定義,則必須傳遞 prompt_embeds
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示詞或提示詞列表。如果未定義,則 prompt 將用於兩個文字編碼器。
  • image (torch.TensorPIL.Image.Imagenp.ndarrayList[torch.Tensor]List[PIL.Image.Image]List[np.ndarray]) — 要透過管道修改的影像。
  • strength (float, 可選, 預設為0.3) — 概念上表示對參考 image 的轉換程度。必須在0到1之間。image 將作為起點,strength 越大,新增的噪聲越多。去噪步數取決於最初新增的噪聲量。當 strength 為1時,新增的噪聲將達到最大值,去噪過程將執行 num_inference_steps 中指定的所有迭代次數。因此,值為1基本上會忽略 image。請注意,如果 denoising_start 被宣告為整數,則 strength 的值將被忽略。
  • num_inference_steps (int, 可選, 預設為50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步,適用於其 set_timesteps 方法支援 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義sigmas,適用於其 set_timesteps 方法支援 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • denoising_start (float, 可選) — 當指定時,表示在去噪過程開始前,要跳過的去噪過程總量的百分比(0.0到1.0之間)。因此,去噪過程的初始部分被跳過,並假定傳入的 image 是部分去噪的影像。請注意,當指定此引數時,強度將被忽略。denoising_start 引數在此管道整合到“去噪器混合”多管道設定中時特別有用,詳見最佳化影像質量
  • denoising_end (float, 可選) — 當指定時,確定在去噪過程有意提前終止之前要完成的去噪過程總量的百分比(0.0到1.0之間)。因此,返回的樣本仍將保留大量噪聲(大約還需要最後20%的時間步),應由設定了 denoising_start 為 0.8 的後續管道去噪,以便它只去噪排程器的最後20%。當此管道構成“去噪器混合”多管道設定的一部分時,應理想地利用 denoising_end 引數,如最佳化影像質量中所述。
  • guidance_scale (float, 可選, 預設為7.5) — 無分類器擴散引導中定義的引導比例。guidance_scale 定義為Imagen Paper中公式2的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例會促使生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞或提示詞列表。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即,如果 guidance_scale 小於 1 時)將被忽略。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成,要傳送到 tokenizer_2text_encoder_2 的提示詞或提示詞列表。如果未定義,則 negative_prompt 將用於兩個文字編碼器。
  • num_images_per_prompt (int, 可選, 預設為1) — 每個提示詞生成的影像數量。
  • eta (float, 可選, 預設為0.0) — 對應於DDIM論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。
  • latents (torch.Tensor, 可選) — 預生成的帶噪潛變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成潛變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化負向提示詞嵌入將從 negative_prompt 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選): 用於IP介面卡的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — IP-Adapter的預生成影像嵌入。它應該是一個列表,長度與IP-adapter的數量相同。每個元素都應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負向影像嵌入。如果未提供,嵌入將從 ip_adapter_image 輸入引數計算。
  • output_type (str, 可選, 預設為"pil") — 生成影像的輸出格式。選擇 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為True) — 是否返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將傳遞給 diffusers.models.attention_processor 中定義的 self.processorAttentionProcessor
  • guidance_rescale (float, 可選, 預設為 0.0) — 由 Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的指導重縮放因子,guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定義為 φ。當使用零終端信噪比時,指導重縮放因子應能解決過度曝光問題。
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 original_sizetarget_size 不同,影像將顯示為縮小或放大。如果未指定,original_size 預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — crops_coords_top_left 可用於生成一個看起來像是從 crops_coords_top_left 位置向下“裁剪”的影像。通常透過將 crops_coords_top_left 設定為 (0, 0) 來獲得良好、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size 應設定為生成影像的所需高度和寬度。如果未指定,它將預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 根據特定影像解析度對生成過程進行負面條件化。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 根據特定裁剪座標對生成過程進行負面條件化。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 根據目標影像解析度對生成過程進行負面條件化。在大多數情況下,它應該與 target_size 相同。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可選, 預設為 6.0) — 透過影響正文字條件來模擬生成影像的美學分數。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。
  • negative_aesthetic_score (float, 可選, 預設為 2.5) — SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 的 2.2 節所述。可用於透過影響負文字條件來模擬生成影像的美學分數。
  • clip_skip (int, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 一個函式或 PipelineCallbackMultiPipelineCallbacks 的子類,在推理期間每個去噪步驟結束時呼叫,引數如下: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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的縮放因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應縮放因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

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

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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 lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

引數

  • prompt (strList[str], 可選) — 要編碼的提示
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示。如果未定義,則 prompt 將在兩個文字編碼器中使用。
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示應生成的影像數量
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示。如果未定義,則必須傳遞 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1,則忽略)。
  • negative_prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的不用於引導影像生成的提示。如果未定義,則 negative_prompt 將在兩個文字編碼器中使用。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化負提示嵌入將從 negative_prompt 輸入引數生成。
  • lora_scale (float, 可選) — 一個將應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子(如果 LoRA 層已載入)。
  • clip_skip (int, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導尺度的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLPAGInpaintPipeline

class diffusers.StableDiffusionXLPAGInpaintPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器(VAE)模型。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字部分,特別是 clip-vit-large-patch14 變體。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二個凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字和池化部分,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 類的分詞器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 類的第二個分詞器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在進行去噪的條件 U-Net 架構。
  • scheduler (SchedulerMixin) — 與 unet 結合使用以對編碼影像潛在進行去噪的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • requires_aesthetics_score (bool, 可選, 預設為 "False") — unet 在推理期間是否需要傳遞美學分數條件。另請參見 stabilityai/stable-diffusion-xl-refiner-1-0 的配置。
  • force_zeros_for_empty_prompt (bool, 可選, 預設為 "True") — 是否強制將負提示嵌入始終設定為 0。另請參見 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可選) — 是否使用 invisible_watermark 庫 為輸出影像新增水印。如果未定義,則在安裝該軟體包時預設為 True,否則不使用水印。

用於使用 Stable Diffusion XL 進行文字到影像生成的管道。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示。如果未定義,則必須傳遞 prompt_embeds
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示。如果未定義,則 prompt 將在兩個文字編碼器中使用。
  • 影像 (PIL.Image.Image) — 影像,或表示影像批次的張量,將進行修復,即影像的某些部分將用 mask_image 遮罩並根據 prompt 重新繪製。
  • mask_image (PIL.Image.Image) — 影像,或表示影像批次的張量,用於遮罩 image。遮罩中的白色畫素將被重新繪製,而黑色畫素將保留。如果 mask_image 是 PIL 影像,則在使用前將轉換為單通道(亮度)。如果是張量,則應包含一個顏色通道(L)而不是 3 個,因此預期形狀為 (B, H, W, 1)
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳效果,預設設定為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何值都不會很好地工作。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳效果,預設設定為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何值都不會很好地工作。
  • padding_mask_crop (int, 可選, 預設為 None) — 對影像和遮罩應用的裁剪邊距大小。如果為 None,則不對影像和 mask_image 應用裁剪。如果 padding_mask_crop 不為 None,它將首先找到一個與影像縱橫比相同且包含所有遮罩區域的矩形區域,然後根據 padding_mask_crop 擴充套件該區域。然後將影像和 mask_image 根據擴充套件區域進行裁剪,然後調整大小以適應原始影像大小進行修復。當遮罩區域較小而影像較大且包含與修復無關的資訊(例如背景)時,這很有用。
  • strength (float, 可選, 預設為 0.9999) — 概念上,表示參考 image 的遮罩部分轉換程度。必須介於 0 和 1 之間。image 將用作起點,strength 越大,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當 strength 為 1 時,新增的噪聲將最大,去噪過程將執行 num_inference_steps 中指定的全部迭代次數。因此,值為 1 基本上會忽略參考 image 的遮罩部分。請注意,如果 denoising_start 宣告為整數,則將忽略 strength 的值。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度較慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步,適用於支援 set_timesteps 方法中 timesteps 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,適用於支援 set_timesteps 方法中 sigmas 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。
  • denoising_start (float, 可選) — 指定後,表示在去噪過程開始前跳過的總去噪過程的比例(0.0 到 1.0 之間)。因此,去噪過程的初始部分被跳過,並假定傳入的 image 是部分去噪的影像。請注意,當指定此引數時,將忽略 strength。denoising_start 引數在將此管道整合到“混合去噪器”多管道設定中時特別有用,如 最佳化影像輸出 中所詳述。
  • denoising_end (float, 可選) — 指定後,決定在去噪過程有意提前終止前完成的總去噪過程的比例(0.0 到 1.0 之間)。因此,返回的樣本仍將保留大量噪聲(大約最後 20% 的時間步仍需),並且應由一個將 denoising_start 設定為 0.8 的後續管道去噪,以便它只去噪排程器的最後 20%。denoising_end 引數理想情況下應在此管道作為“去噪器混合”多管道設定的一部分時使用,如 最佳化影像輸出 中所詳述。
  • guidance_scale (float, 可選, 預設為 7.5) — 分類器自由擴散引導中定義的引導比例。guidance_scale 定義為 Imagen Paper 方程 2 中的 w。透過設定 guidance_scale > 1 來啟用引導比例。更高的引導比例鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示。如果未定義,則必須傳入 negative_prompt_embeds。在不使用引導時忽略(即,如果 guidance_scale 小於 1 則忽略)。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成,將傳送到 tokenizer_2text_encoder_2 的提示。如果未定義,則在兩個文字編碼器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將根據 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將根據 negative_prompt 輸入引數生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將根據 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將根據 negative_prompt 輸入引數生成池化負文字嵌入。
  • ip_adapter_image — (PipelineImageInput, 可選): 與 IP 介面卡配合使用的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — IP-Adapter 預生成的影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負影像嵌入。如果未提供,則從 ip_adapter_image 輸入引數計算嵌入。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示生成的影像數量。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.Generator, 可選) — 一個或多個 torch 生成器,使生成具有確定性。
  • latents (torch.Tensor, 可選) — 預生成的帶噪潛像,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示調整相同的生成。如果未提供,則將透過使用提供的隨機 generator 取樣生成一個潛像張量。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。選擇 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。當返回元組時,第一個元素是包含生成影像的列表。
  • cross_attention_kwargs (dict, 可選) — 一個 kwargs 字典,如果指定,將作為 AttentionProcessor 傳遞給 diffusers.models.attention_processor 中定義的 self.processor
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 original_sizetarget_size 不相同,影像將顯示為下采樣或上取樣。如果未指定,original_size 預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — crops_coords_top_left 可用於生成一個影像,該影像顯示為從 crops_coords_top_left 位置向下“裁剪”。通常透過將 crops_coords_top_left 設定為 (0, 0) 來獲得有利的、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size 應設定為生成影像的所需高度和寬度。如果未指定,它將預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於根據特定影像解析度對生成過程進行負面調節。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 用於根據特定裁剪座標對生成過程進行負面調節。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於根據目標影像解析度對生成過程進行負面調節。在大多數情況下,它應該與 target_size 相同。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可選, 預設為 6.0) — 透過影響正向文字條件來模擬生成影像的美學分數。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • negative_aesthetic_score (float, 可選, 預設為 2.5) — SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。可用於透過影響負文字條件來模擬生成影像的美學分數。
  • clip_skip (int, 可選) — 計算提示嵌入時從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理期間每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類,具有以下引數: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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dict 為 True,則為 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否則為 tuple。當返回元組時,第一個元素是包含生成影像的列表。

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForInpainting
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     variant="fp16",
...     enable_pag=True,
... )
>>> pipe.to("cuda")

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     num_inference_steps=50,
...     strength=0.80,
...     pag_scale=0.3,
... ).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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 lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

引數

  • prompt (strList[str], 可選) — 待編碼的提示
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示。如果未定義,則在兩個文字編碼器中都使用 prompt
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示應生成的影像數量
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導
  • negative_prompt (strList[str], 可選) — 不用於指導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。當不使用指導時(即,如果 guidance_scale 小於 1 時),此引數會被忽略。
  • negative_prompt_2 (strList[str], 可選) — 不用於指導影像生成的提示詞,將傳送到 tokenizer_2text_encoder_2。如果未定義,則在兩個文字編碼器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據 negative_prompt 輸入引數生成負向提示詞嵌入。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據 negative_prompt 輸入引數生成池化負向提示詞嵌入。
  • lora_scale (float, 可選) — 如果載入了 LoRA 層,將應用於文字編碼器的所有 LoRA 層的 LoRA 縮放因子。
  • clip_skip (int, 可選) — 在計算提示詞嵌入時跳過 CLIP 層的數量。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定指導尺度的嵌入向量,以隨後豐富時間步長嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLControlNetPAGPipeline

class diffusers.StableDiffusionXLControlNetPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
  • text_encoder_2 (CLIPTextModelWithProjection) — 第二個凍結的文字編碼器 (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)。
  • tokenizer (CLIPTokenizer) — 用於標記化文字的 CLIPTokenizer
  • tokenizer_2 (CLIPTokenizer) — 用於標記化文字的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪過程中為 unet 提供額外條件。如果您將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將被相加,以建立組合的額外條件。
  • scheduler (SchedulerMixin) — 與 unet 結合使用的排程器,用於對編碼影像潛在表示進行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可選, 預設為 "True") — 是否應始終將負向提示詞嵌入設定為 0。另請參閱 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可選) — 是否使用 invisible_watermark 庫為輸出影像新增水印。如果未定義,則在安裝該包時預設為 True;否則不使用水印。

使用 Stable Diffusion XL 和 ControlNet 指導的文字到影像生成流水線。

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

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於指導影像生成的提示詞。如果未定義,需要傳入 prompt_embeds
  • prompt_2 (strList[str], 可選) — 傳送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則在兩個文字編碼器中都使用 prompt
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 的輸入條件,用於指導 unet 進行生成。如果型別指定為 torch.Tensor,則按原樣傳遞給 ControlNet。PIL.Image.Image 也可以作為影像接受。輸出影像的尺寸預設為 image 的尺寸。如果傳入了 height 和/或 width,則 image 將相應地調整大小。如果在 init 中指定了多個 ControlNet,則必須將影像作為列表傳入,以便列表的每個元素都可以正確地批處理以輸入到單個 ControlNet。
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何影像效果都不會很好。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何影像效果都不會很好。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步數。更多去噪步數通常會導致更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步長,適用於在 set_timesteps 方法中支援 timesteps 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigma 值,適用於在 set_timesteps 方法中支援 sigmas 引數的排程器。如果未定義,將使用傳入 num_inference_steps 時的預設行為。
  • denoising_end (float, 可選) — 指定時,決定在去噪過程有意提前終止之前完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留由排程器選擇的離散時間步長確定的相當數量的噪聲。當此流水線作為“去噪器混合”多流水線設定的一部分時,應理想地使用 denoising_end 引數,詳見 精煉影像輸出
  • guidance_scale (float, 可選, 預設為 5.0) — 較高的指導尺度值鼓勵模型生成與文字 prompt 緊密相關的影像,但會犧牲影像質量。當 guidance_scale > 1 時,啟用指導尺度。
  • negative_prompt (strList[str], 可選) — 用於指導影像生成時不包含的內容的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。當不使用指導時(guidance_scale < 1),此引數會被忽略。
  • negative_prompt_2 (strList[str], 可選) — 用於指導影像生成時不包含的內容的提示詞。此引數將傳送到 tokenizer_2text_encoder_2。如果未定義,則在兩個文字編碼器中都使用 negative_prompt
  • 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` 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,池化文字嵌入將從 `prompt` 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,池化 `negative_prompt_embeds` 將從 `negative_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.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, 可選) — 如果指定,則作為 kwargs 字典傳遞給 self.processor 中定義的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始 unet 中的殘差之前,將乘以 `controlnet_conditioning_scale`。如果在 `init` 中指定了多個 ControlNet,則可以將其對應的比例設定為列表。
  • control_guidance_start (floatList[float], 可選, 預設為 0.0) — ControlNet 開始應用的步數總百分比。
  • control_guidance_end (floatList[float], 可選, 預設為 1.0) — ControlNet 停止應用的步數總百分比。
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 `original_size` 與 `target_size` 不同,則影像將顯示為下采樣或上取樣。如果未指定,`original_size` 預設為 `(height, width)`。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — `crops_coords_top_left` 可用於生成從 `crops_coords_top_left` 位置向下“裁剪”的影像。通常透過將 `crops_coords_top_left` 設定為 (0, 0) 來獲得有利的、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,`target_size` 應該設定為生成影像的所需高度和寬度。如果未指定,它將預設為 `(height, width)`。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 根據特定影像解析度對生成過程進行負條件。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 根據特定的裁剪座標對生成過程進行負條件。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 根據目標影像解析度對生成過程進行負條件。在大多數情況下應與 `target_size` 相同。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題執行緒:https://github.com/huggingface/diffusers/issues/4208
  • clip_skip (int, 可選) — 計算提示嵌入時要跳過的CLIP層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 一個函式或 PipelineCallbackMultiPipelineCallbacks 的子類,在推理過程中每個去噪步驟結束時呼叫。引數如下:`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` 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 `pag_scale`。

返回

StableDiffusionPipelineOutputtuple

如果 `return_dict` 為 `True`,則返回 StableDiffusionPipelineOutput,否則返回包含輸出影像的 tuple

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

示例

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import AutoPipelineForText2Image, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image, pag_scale=0.3
... ).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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 lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

引數

  • prompt (strList[str], 可選) — 要編碼的提示。
  • prompt_2 (strList[str], 可選) — 要傳送給 `tokenizer_2` 和 `text_encoder_2` 的提示或提示列表。如果未定義,`prompt` 將用於兩個文字編碼器。
  • device — (torch.device):torch 裝置
  • num_images_per_prompt (int) — 每個提示應生成的影像數量。
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導。
  • negative_prompt (strList[str], 可選) — 不引導影像生成的提示或提示列表。如果未定義,則必須傳遞 `negative_prompt_embeds`。不使用引導時(即,如果 `guidance_scale` 小於 `1`),則忽略。
  • negative_prompt_2 (strList[str], 可選) — 不引導影像生成併發送給 `tokenizer_2` 和 `text_encoder_2` 的提示或提示列表。如果未定義,`negative_prompt` 將用於兩個文字編碼器。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從 `prompt` 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,`negative_prompt_embeds` 將從 `negative_prompt` 輸入引數生成。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從 `prompt` 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化 `negative_prompt_embeds` 將從 `negative_prompt` 輸入引數生成。
  • lora_scale (float, 可選) — 應用於文字編碼器所有 LoRA 層的 LoRA 比例(如果已載入 LoRA 層)。
  • clip_skip (int, 可選) — 計算提示嵌入時要跳過的CLIP層數。值為 1 意味著將使用倒數第二層的輸出計算提示嵌入。

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

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

引數

  • w (torch.Tensor) — 生成具有指定引導比例的嵌入向量,以隨後豐富時間步嵌入。
  • embedding_dim (int, 可選, 預設為 512) — 要生成的嵌入的維度。
  • dtype (torch.dtype, 可選, 預設為 torch.float32) — 生成嵌入的資料型別。

返回

torch.Tensor

形狀為 (len(w), embedding_dim) 的嵌入向量。

請參閱 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLControlNetPAGImg2ImgPipeline

class diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

引數

  • vae (AutoencoderKL) — 用於編碼和解碼影像到潛在表示的變分自動編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結文字編碼器。Stable Diffusion 使用 CLIP 的文字部分,特別是 clip-vit-large-patch14 變體。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二個凍結文字編碼器。Stable Diffusion XL 使用 CLIP 的文字和池化部分,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 類的分詞器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 類的第二個分詞器。
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在進行去噪的條件 U-Net 架構。
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪過程中為 unet 提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將相加,以建立一個組合的額外條件。
  • scheduler (SchedulerMixin) — 用於與 `unet` 結合對編碼影像潛在進行去噪的排程器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • requires_aesthetics_score (bool, 可選, 預設為 "False") — `unet` 在推理過程中是否需要傳遞 `aesthetic_score` 條件。另請參閱 `stabilityai/stable-diffusion-xl-refiner-1-0` 的配置。
  • force_zeros_for_empty_prompt (bool, 可選, 預設為 "True") — 是否強制將負提示嵌入始終設定為 0。另請參閱 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。
  • add_watermarker (bool, 可選) — 是否使用 invisible_watermark 庫 對輸出影像新增水印。如果未定義,如果安裝了該軟體包,則預設為 True,否則不使用水印。
  • feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的 CLIPImageProcessor;用作 `safety_checker` 的輸入。

使用 Stable Diffusion XL 和 ControlNet 引導的影像到影像生成管道。

此模型繼承自 DiffusionPipeline。有關庫為所有管道實現通用方法(例如下載或儲存、在特定裝置上執行等)的詳細資訊,請查閱超類文件。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 num_inference_steps: int = 50 guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳入 prompt_embeds
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則 prompt 將用於兩個文字編碼器。
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): 初始影像將作為影像生成過程的起點。如果直接傳入潛在變數,也可以接受影像潛在變數作為 image,它將不會再次編碼。
  • control_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 輸入條件。ControlNet 使用此輸入條件來生成對 Unet 的引導。如果型別指定為 torch.Tensor,則按原樣傳遞給 ControlNet。PIL.Image.Image 也可以作為影像接受。輸出影像的尺寸預設為 image 的尺寸。如果傳入 height 和/或 width,則 image 將根據它們調整大小。如果在初始化中指定了多個 ControlNet,則影像必須作為列表傳入,以便列表的每個元素可以正確批處理以輸入到單個 ControlNet。
  • height (int, 可選, 預設為 control_image 的大小) — 生成影像的畫素高度。低於 512 畫素的任何影像對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點效果不佳。
  • width (int, 可選, 預設為 control_image 的大小) — 生成影像的畫素寬度。低於 512 畫素的任何影像對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點效果不佳。
  • strength (float, 可選, 預設為 0.8) — 指示轉換參考 image 的程度。必須介於 0 和 1 之間。image 用作起點,strength 越高,新增的噪聲越多。去噪步驟的數量取決於初始新增的噪聲量。當 strength 為 1 時,新增的噪聲最大,去噪過程將執行 num_inference_steps 中指定的全部迭代次數。值為 1 基本上忽略了 image
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會生成更高質量的影像,但會以較慢的推理速度為代價。
  • guidance_scale (float, 可選, 預設為 7.5) — 如 Classifier-Free Diffusion Guidance 中定義的引導尺度。guidance_scale 定義為 Imagen Paper 中公式 2 的 w。透過設定 guidance_scale > 1 啟用引導尺度。較高的引導尺度鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。在不使用引導時忽略(即,如果 guidance_scale 小於 1 則忽略)。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成併發送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則 negative_prompt 將用於兩個文字編碼器。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞要生成的影像數量。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對於其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成過程具有確定性。
  • latents (torch.Tensor, 可選) — 預生成的帶噪聲潛在變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成潛在變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從 negative_prompt 輸入引數生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化 negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選): 與 IP 介面卡配合使用的可選影像輸入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可選) — 預生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 的數量相同。每個元素應該是一個形狀為 (batch_size, num_images, emb_dim) 的張量。如果 do_classifier_free_guidance 設定為 True,它應該包含負影像嵌入。如果未提供,嵌入將從 ip_adapter_image 輸入引數計算。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。選擇 PILPIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是純元組。
  • cross_attention_kwargs (dict, 可選) — 如果指定,此 kwargs 字典將傳遞給 diffusers.models.attention_processorself.processor 定義的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始 unet 中的殘差之前乘以 controlnet_conditioning_scale。如果在初始化中指定了多個 ControlNet,則可以將其相應的比例設定為列表。
  • guess_mode (bool, 可選, 預設為 False) — 在此模式下,即使您刪除所有提示詞,ControlNet 編碼器也會盡力識別輸入影像的內容。建議 guidance_scale 在 3.0 到 5.0 之間。
  • control_guidance_start (floatList[float], 可選, 預設為 0.0) — ControlNet 開始應用的總體步驟的百分比。
  • control_guidance_end (floatList[float], 可選, 預設為 1.0) — ControlNet 停止應用的總體步驟的百分比。
  • original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 如果 original_sizetarget_size 不相同,則影像將顯示為下采樣或上取樣。如果未指定,original_size 預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — crops_coords_top_left 可用於生成一個影像,該影像看起來像是從 crops_coords_top_left 位置向下“裁剪”的。通常透過將 crops_coords_top_left 設定為 (0, 0) 來獲得有利的、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size 應設定為生成影像所需的寬高。如果未指定,則預設為 (height, width)。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • negative_original_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於基於特定影像解析度對生成過程進行負面條件設定。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。更多資訊請參閱此 issue 執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可選, 預設為 (0, 0)) — 用於基於特定裁剪座標對生成過程進行負面條件設定。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。更多資訊請參閱此 issue 執行緒:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可選, 預設為 (1024, 1024)) — 用於基於目標影像解析度對生成過程進行負面條件設定。在大多數情況下,它應該與 target_size 相同。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。更多資訊請參閱此 issue 執行緒:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可選, 預設為 6.0) — 透過影響正文字條件來模擬生成影像的美學分數。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。
  • negative_aesthetic_score (float, 可選, 預設為 2.5) — SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。可用於透過影響負文字條件來模擬生成影像的美學分數。
  • clip_skip (int, 可選) — 計算提示詞嵌入時要從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式或 PipelineCallbackMultiPipelineCallbacks 的子類。引數如下: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 屬性中列出的變數。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的比例因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應比例因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dict 為 True,則為 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否則為包含輸出影像的 tuple

呼叫管道進行生成時呼叫的函式。

示例

>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image


>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors="True",
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()


>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image


>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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 lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

引數

  • prompt (strList[str], 可選) — 要編碼的提示詞
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則 prompt 將用於兩個文字編碼器。
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示詞應生成的影像數量
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導。
  • negative_prompt (strList[str], 可選) — 不引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。在不使用引導時忽略(即,如果 guidance_scale 小於 1 則忽略)。
  • negative_prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的不引導影像生成的提示詞。如果未定義,則在兩個文字編碼器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 negative_prompt 輸入引數生成負面提示詞嵌入。
  • pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可選) — 預生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 negative_prompt 輸入引數生成池化負面提示詞嵌入。
  • lora_scale (float, 可選) — 將應用於文字編碼器的所有 LoRA 層的 LoRA 縮放因子(如果已載入 LoRA 層)。
  • clip_skip (int, 可選) — 計算提示詞嵌入時要跳過的 CLIP 層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。

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

StableDiffusion3PAGPipeline

class diffusers.StableDiffusion3PAGPipeline

< >

( transformer: SD3Transformer2DModel scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModelWithProjection tokenizer: CLIPTokenizer text_encoder_2: CLIPTextModelWithProjection tokenizer_2: CLIPTokenizer text_encoder_3: T5EncoderModel tokenizer_3: T5TokenizerFast pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

引數

  • transformer (SD3Transformer2DModel) — 用於對編碼影像潛在空間進行去噪的條件 Transformer (MMDiT) 架構。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 與 transformer 結合使用的排程器,用於對編碼影像潛在空間進行去噪。
  • vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
  • text_encoder (CLIPTextModelWithProjection) — CLIP,特別是 clip-vit-large-patch14 變體,增加了投影層,其初始化為以 hidden_size 為維度的對角矩陣。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。
  • text_encoder_3 (T5EncoderModel) — 凍結文字編碼器。Stable Diffusion 3 使用 T5,特別是 t5-v1_1-xxl 變體。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 類的分詞器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 類的第二個分詞器。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 類的分詞器。

PAG pipeline 用於使用 Stable Diffusion 3 進行文字到影像生成。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None 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.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_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'] max_sequence_length: int = 256 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 引導影像生成的提示詞。如果未定義,則必須傳入 prompt_embeds
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則將使用 prompt
  • prompt_3 (strList[str], 可選) — 要傳送到 tokenizer_3text_encoder_3 的提示詞。如果未定義,則將使用 prompt
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。為獲得最佳效果,此值預設為 1024。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。為獲得最佳效果,此值預設為 1024。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,與支援 sigmas 引數的排程器結合使用,在其 set_timesteps 方法中。如果未定義,將使用傳入 num_inference_steps 時的預設行為。
  • guidance_scale (float, 可選, 預設為 7.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale 定義為 Imagen Paper 方程式 2 中的 w。透過設定 guidance_scale > 1 啟用引導比例。較高的引導比例鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。在不使用引導時忽略(即,如果 guidance_scale 小於 1 則忽略)。
  • negative_prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的不引導影像生成的提示詞。如果未定義,則將使用 negative_prompt
  • negative_prompt_3 (strList[str], 可選) — 要傳送到 tokenizer_3text_encoder_3 的不引導影像生成的提示詞。如果未定義,則將使用 negative_prompt
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞生成的影像數量。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch generator(s),用於使生成具有確定性。
  • latents (torch.FloatTensor, 可選) — 預生成的帶噪潛在空間,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則將透過使用提供的隨機 generator 進行取樣來生成潛在空間張量。
  • prompt_embeds (torch.FloatTensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • negative_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負面提示詞嵌入將從 negative_prompt 輸入引數生成。
  • pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將從 prompt 輸入引數生成。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化負面提示詞嵌入將從 negative_prompt 輸入引數生成。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL: PIL.Image.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元組。
  • joint_attention_kwargs (dict, 可選) — 如果指定,則傳遞給 diffusers.models.attention_processorself.processor 下定義的 AttentionProcessor 的 kwargs 字典。
  • 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 屬性中列出的變數。
  • max_sequence_length (int 預設為 256) — 與 prompt 一起使用的最大序列長度。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的縮放因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應縮放因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

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

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt, guidance_scale=5.0, pag_scale=0.7).images[0]
>>> image.save("sd3_pag.png")

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] prompt_3: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None clip_skip: typing.Optional[int] = None max_sequence_length: int = 256 lora_scale: typing.Optional[float] = None )

引數

  • prompt (strList[str], 可選) — 待編碼的提示詞。
  • prompt_2 (strList[str], 可選) — 傳送給 tokenizer_2text_encoder_2 的提示詞。如果未定義,則在所有文字編碼器中使用 prompt
  • prompt_3 (strList[str], 可選) — 傳送給 tokenizer_3text_encoder_3 的提示詞。如果未定義,則在所有文字編碼器中使用 prompt
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示詞應生成的影像數量。
  • do_classifier_free_guidance (bool) — 是否使用無分類器引導。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即,如果 guidance_scale 小於 1 時)忽略。
  • negative_prompt_2 (strList[str], 可選) — 傳送給 tokenizer_2text_encoder_2 的不用於引導影像生成的提示詞。如果未定義,則在所有文字編碼器中使用 negative_prompt
  • negative_prompt_3 (strList[str], 可選) — 傳送給 tokenizer_3text_encoder_3 的不用於引導影像生成的提示詞。如果未定義,則在所有文字編碼器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 negative_prompt 輸入引數生成負文字嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 negative_prompt 輸入引數生成負池化文字嵌入。
  • clip_skip (int, 可選) — 計算提示詞嵌入時從 CLIP 跳過的層數。值為 1 表示使用倒數第二層的輸出計算提示詞嵌入。
  • lora_scale (float, 可選) — 如果載入了 LoRA 層,將應用於文字編碼器的所有 LoRA 層的 LoRA 縮放因子。

StableDiffusion3PAGImg2ImgPipeline

class diffusers.StableDiffusion3PAGImg2ImgPipeline

< >

( transformer: SD3Transformer2DModel scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModelWithProjection tokenizer: CLIPTokenizer text_encoder_2: CLIPTextModelWithProjection tokenizer_2: CLIPTokenizer text_encoder_3: T5EncoderModel tokenizer_3: T5TokenizerFast pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

引數

  • transformer (SD3Transformer2DModel) — 用於對編碼影像潛變數進行去噪的條件變換器 (MMDiT) 架構。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 與 transformer 結合使用的排程器,用於對編碼影像潛變數進行去噪。
  • vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
  • text_encoder (CLIPTextModelWithProjection) — CLIP,特別是 clip-vit-large-patch14 變體,附加了一個投影層,該層使用其維度為 hidden_size 的對角矩陣初始化。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。
  • text_encoder_3 (T5EncoderModel) — 凍結文字編碼器。Stable Diffusion 3 使用 T5,特別是 t5-v1_1-xxl 變體。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 類的分詞器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 類的第二個分詞器。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 類的分詞器。

PAG 影像到影像生成管道,使用 Stable Diffusion 3。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = 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 strength: float = 0.6 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None 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.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_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'] max_sequence_length: int = 256 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳遞 prompt_embeds
  • prompt_2 (strList[str], 可選) — 傳送給 tokenizer_2text_encoder_2 的提示詞。如果未定義,則將使用 prompt
  • prompt_3 (strList[str], 可選) — 傳送給 tokenizer_3text_encoder_3 的提示詞。如果未定義,則將使用 prompt
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image]List[np.ndarray]) — 用作起點的影像批處理的 Image、numpy 陣列或張量。對於 numpy 陣列和 pytorch 張量,預期值範圍在 [0, 1] 之間。如果是張量或張量列表,預期形狀應為 (B, C, H, W)(C, H, W)。如果是 numpy 陣列或陣列列表,預期形狀應為 (B, H, W, C)(H, W, C)。它也可以接受影像潛變數作為 image,但如果直接傳遞潛變數,則不會再次編碼。
  • strength (float, 可選, 預設為 0.8) — 指示轉換參考 image 的程度。必須介於 0 和 1 之間。image 用作起點,strength 越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當 strength 為 1 時,新增的噪聲最大,去噪過程將執行 num_inference_steps 中指定的全部迭代次數。值為 1 基本上會忽略 image
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,與支援 sigmas 引數的排程器一起使用。如果未定義,則將使用傳遞 num_inference_steps 時的預設行為。
  • guidance_scale (float, 可選, 預設為 7.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale 定義為 Imagen Paper 方程 2 中的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲較低影像質量為代價。
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即,如果 guidance_scale 小於 1 時)忽略。
  • negative_prompt_2 (strList[str], 可選) — 傳送給 tokenizer_2text_encoder_2 的不用於引導影像生成的提示詞。如果未定義,則將使用 negative_prompt
  • negative_prompt_3 (strList[str], 可選) — 傳送給 tokenizer_3text_encoder_3 的不用於引導影像生成的提示詞。如果未定義,則將使用 negative_prompt
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞生成的影像數量。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。
  • latents (torch.FloatTensor, 可選) — 預生成的帶噪聲潛變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將透過使用提供的隨機 generator 進行取樣來生成潛變數張量。
  • prompt_embeds (torch.FloatTensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 negative_prompt 輸入引數生成負文字嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從 negative_prompt 輸入引數生成負池化文字嵌入。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。可選擇 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元組。
  • joint_attention_kwargs (dict, 可選) — 如果指定,將傳遞給 AttentionProcessor 的 kwargs 字典,如 diffusers.models.attention_processor 中的 self.processor 所定義。
  • 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 屬性中列出的變數。
  • max_sequence_length (int 預設為 256) — 與 prompt 一起使用的最大序列長度。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的縮放因子。如果設定為 0.0,則不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應縮放因子。如果設定為 0.0,則使用 pag_scale

返回

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

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

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import StableDiffusion3PAGImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusion3PAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> image = pipe(prompt, image=init_image, guidance_scale=5.0, pag_scale=0.7).images[0]

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] prompt_3: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None clip_skip: typing.Optional[int] = None max_sequence_length: int = 256 lora_scale: typing.Optional[float] = None )

引數

  • prompt (strList[str], 可選) — 待編碼的提示詞。
  • prompt_2 (strList[str], 可選) — 要傳送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則在所有文字編碼器中使用 prompt
  • prompt_3 (strList[str], 可選) — 要傳送到 tokenizer_3text_encoder_3 的提示詞。如果未定義,則在所有文字編碼器中使用 prompt
  • device — (torch.device): torch 裝置
  • num_images_per_prompt (int) — 每個提示詞應生成的影像數量
  • do_classifier_free_guidance (bool) — 是否使用分類器自由引導
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即如果 guidance_scale 小於 1 時)將被忽略。
  • negative_prompt_2 (strList[str], 可選) — 不用於引導影像生成併發送到 tokenizer_2text_encoder_2 的提示詞。如果未定義,則在所有文字編碼器中使用 negative_prompt
  • negative_prompt_3 (strList[str], 可選) — 不用於引導影像生成併發送到 tokenizer_3text_encoder_3 的提示詞。如果未定義,則在所有文字編碼器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 negative_prompt 輸入引數生成負面提示詞嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 prompt 輸入引數生成池化文字嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可選) — 預生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 negative_prompt 輸入引數生成池化負面提示詞嵌入。
  • clip_skip (int, 可選) — 在計算提示詞嵌入時跳過的 CLIP 層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
  • lora_scale (float, 可選) — 應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子(如果載入了 LoRA 層)。

PixArtSigmaPAGPipeline

class diffusers.PixArtSigmaPAGPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKL transformer: PixArtTransformer2DModel scheduler: KarrasDiffusionSchedulers pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

PAG pipeline,用於使用 PixArt-Sigma 生成文字到影像。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 num_images_per_prompt: typing.Optional[int] = 1 height: typing.Optional[int] = None width: typing.Optional[int] = None 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 prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: 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 clean_caption: bool = True use_resolution_binning: bool = True max_sequence_length: int = 300 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ImagePipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 引導影像生成的提示詞。如果未定義,則必須傳遞 prompt_embeds
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即如果 guidance_scale 小於 1 時)將被忽略。
  • num_inference_steps (int, 可選, 預設為 100) — 去噪步數。更多去噪步數通常會產生更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步,適用於支援在其 set_timesteps 方法中包含 timesteps 引數的排程器。如果未定義,則使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigma,適用於支援在其 set_timesteps 方法中包含 sigmas 引數的排程器。如果未定義,則使用傳遞 num_inference_steps 時的預設行為。
  • guidance_scale (float, 可選, 預設為 4.5) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale 定義為 Imagen Paper 中公式 2 的 w。透過將 guidance_scale 設定為 > 1 來啟用引導比例。更高的引導比例會鼓勵生成與文字 prompt 更緊密相關的影像,通常以犧牲較低影像質量為代價。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞要生成的影像數量。
  • height (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的高度(畫素)。
  • width (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的寬度(畫素)。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。
  • latents (torch.Tensor, 可選) — 預生成的帶噪聲隱變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成隱變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將從 prompt 輸入引數生成文字嵌入。
  • prompt_attention_mask (torch.Tensor, 可選) — 文字嵌入的預生成注意力掩碼。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。對於 PixArt-Sigma,此負面提示詞應為空字串。如果未提供,則將從 negative_prompt 輸入引數生成負面提示詞嵌入。
  • negative_prompt_attention_mask (torch.Tensor, 可選) — 負面文字嵌入的預生成注意力掩碼。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。選擇 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元組。
  • callback (Callable, 可選) — 一個函式,在推理過程中每 callback_steps 步都會被呼叫。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — 呼叫 callback 函式的頻率。如果未指定,回撥將在每一步都被呼叫。
  • clean_caption (bool, 可選, 預設為 True) — 是否在建立嵌入之前清理標題。需要安裝 beautifulsoup4ftfy。如果未安裝這些依賴項,嵌入將從原始提示詞建立。
  • use_resolution_binning (bool 預設為 True) — 如果設定為 True,請求的高度和寬度將首先使用 ASPECT_RATIO_1024_BIN 對映到最接近的解析度。生成的隱變數解碼成影像後,它們將被重新調整大小到請求的解析度。對於生成非方形影像非常有用。
  • max_sequence_length (int 預設為 300) — 與 prompt 一起使用的最大序列長度。
  • pag_scale (float, 可選, 預設為 3.0) — 擾動注意力引導的縮放因子。如果設定為 0.0,將不使用擾動注意力引導。
  • pag_adaptive_scale (float, 可選, 預設為 0.0) — 擾動注意力引導的自適應縮放因子。如果設定為 0.0,則使用 pag_scale

返回

ImagePipelineOutputtuple

如果 return_dictTrue,則返回 ImagePipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表。

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.14"],
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "A small cactus with a happy face in the Sahara desert"
>>> image = pipe(prompt, pag_scale=4.0, guidance_scale=1.0).images[0]

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None clean_caption: bool = False max_sequence_length: int = 300 **kwargs )

引數

  • prompt (strList[str], 可選) — 要編碼的提示詞
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時(即如果 guidance_scale 小於 1 時)將被忽略。對於 PixArt-Alpha,這應該為空字串。
  • do_classifier_free_guidance (bool, 可選, 預設為 True) — 是否使用分類器自由引導。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞應生成的影像數量。
  • device — (torch.device, 可選): 放置結果嵌入的 torch 裝置。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,則將根據 `prompt` 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負向文字嵌入。對於 PixArt-Alpha,它應該是空字串的嵌入。
  • clean_caption (bool, 預設為 False) — 如果為 True,函式將在編碼前預處理並清理提供的標題。
  • max_sequence_length (int, 預設為 300) — 用於提示詞的最大序列長度。

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

< > 在 GitHub 上更新

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