Diffusers 文件

InstructPix2Pix

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

InstructPix2Pix

LoRA

InstructPix2Pix: 學習遵循影像編輯指令 由 Tim Brooks、Aleksander Holynski 和 Alexei A. Efros 提出。

論文摘要如下:

我們提出了一種根據人類指令編輯影像的方法:給定一個輸入影像和一份書面指令,告訴模型要做什麼,我們的模型會遵循這些指令編輯影像。為了獲得該問題的訓練資料,我們結合了兩個大型預訓練模型(一個語言模型 GPT-3 和一個文字到影像模型 Stable Diffusion)的知識,以生成一個大型影像編輯示例資料集。我們的條件擴散模型 InstructPix2Pix 在我們生成的資料上進行訓練,並泛化到推理時的真實影像和使用者編寫的指令。由於它在正向傳播中執行編輯,並且不需要針對每個示例進行微調或反轉,因此我們的模型可以在幾秒鐘內快速編輯影像。我們展示了針對各種輸入影像和書面指令的引人注目的編輯結果。

您可以在專案頁面原始程式碼庫上找到有關 InstructPix2Pix 的更多資訊,並可在演示中試用。

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

StableDiffusionInstructPix2PixPipeline

class diffusers.StableDiffusionInstructPix2PixPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None requires_safety_checker: bool = True )

引數

  • vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用於對文字進行分詞的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 與 unet 結合使用的排程器,用於對編碼影像潛在表示進行去噪。可以是 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 num_inference_steps: int = 100 guidance_scale: float = 7.5 image_guidance_scale: float = 1.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 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'] cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs ) StableDiffusionPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞或提示詞列表。如果未定義,您需要傳遞 prompt_embeds
  • image (torch.Tensor np.ndarray, PIL.Image.Image, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image 或表示影像批次的張量,根據 prompt 進行重新繪製。也可以接受影像潛在表示作為 image,但如果直接傳遞潛在表示,則不會再次編碼。
  • num_inference_steps (int, 可選, 預設為 100) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • guidance_scale (float, 可選, 預設為 7.5) — 較高的引導比例值會鼓勵模型生成與文字 prompt 緊密相關的影像,但會犧牲較低的影像質量。當 guidance_scale > 1 時啟用引導比例。
  • image_guidance_scale (float, 可選, 預設為 1.5) — 將生成的影像推向初始 image。透過設定 image_guidance_scale > 1 啟用影像引導比例。較高的影像引導比例會鼓勵生成的影像與源 image 緊密相關,但通常會犧牲較低的影像質量。此管道要求值至少為 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.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 介面卡配合使用的可選影像輸入。
  • output_type (str, 可選,預設為 "pil") — 生成影像的輸出格式。選擇 PIL.Imagenp.array
  • return_dict (bool, 可選,預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • 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 屬性中列出的變數。
  • cross_attention_kwargs (dict, 可選) — 如果指定,則作為 kwargs 字典傳遞給 self.processor 中定義的 AttentionProcessor

返回

StableDiffusionPipelineOutputtuple

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

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

示例

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

>>> from diffusers import StableDiffusionInstructPix2PixPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"

>>> image = download_image(img_url).resize((512, 512))

>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
...     "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]

load_textual_inversion

< >

( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[str, typing.List[str], NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )

引數

  • pretrained_model_name_or_path (stros.PathLikeList[str 或 os.PathLike]DictList[Dict]) — 可以是以下之一或它們的列表:

    • Hub 上託管的預訓練模型的字串,即模型 ID(例如 sd-concepts-library/low-poly-hd-logos-icons)。
    • 包含文字反轉權重的目錄路徑(例如 ./my_text_inversion_directory/)。
    • 包含文字反轉權重的檔案路徑(例如 ./my_text_inversions.pt)。
    • 一個 torch state dict
  • token (strList[str], 可選) — 覆蓋用於文字反轉權重的 token。如果 pretrained_model_name_or_path 是一個列表,則 token 也必須是等長的列表。
  • text_encoder (CLIPTextModel, 可選) — 凍結的文字編碼器 (clip-vit-large-patch14)。如果未指定,函式將使用 self.tokenizer。
  • tokenizer (CLIPTokenizer, 可選) — CLIPTokenizer 類的分詞器。如果未指定,函式將使用 self.tokenizer。
  • weight_name (str, 可選) — 自定義權重檔案的名稱。應在以下情況下使用:

    • 儲存的文字反轉檔案是 🤗 Diffusers 格式,但以特定權重名稱(例如 text_inv.bin)儲存。
    • 儲存的文字反轉檔案是 Automatic1111 格式。
  • cache_dir (Union[str, os.PathLike], 可選) — 如果不使用標準快取,則下載的預訓練模型配置的快取目錄路徑。
  • force_download (bool, 可選,預設為 False) — 是否強制(重新)下載模型權重和配置檔案,如果存在則覆蓋快取版本。
  • proxies (Dict[str, str], 可選) — 按協議或端點使用的代理伺服器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用於每個請求。
  • local_files_only (bool, 可選,預設為 False) — 是否只加載本地模型權重和配置檔案。如果設定為 True,則不會從 Hub 下載模型。
  • hf_token (strbool, 可選) — 用作遠端檔案 HTTP bearer 授權的 token。如果為 True,則使用從 diffusers-cli login 生成的 token(儲存在 ~/.huggingface 中)。
  • revision (str, 可選,預設為 "main") — 要使用的特定模型版本。它可以是分支名稱、標籤名稱、提交 ID 或 Git 允許的任何識別符號。
  • subfolder (str, 可選,預設為 "") — Hub 上或本地較大模型儲存庫中模型檔案的子資料夾位置。
  • mirror (str, 可選) — 解決在中國下載模型時的可訪問性問題的映象源。我們不保證該源的及時性或安全性,您應參考映象網站獲取更多資訊。

將 Textual Inversion 嵌入載入到 StableDiffusionPipeline 的文字編碼器中(支援 🤗 Diffusers 和 Automatic1111 格式)。

示例

載入 🤗 Diffusers 格式的文字反轉嵌入向量

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

要載入 Automatic1111 格式的文字反轉嵌入向量,請務必先下載該向量(例如從 civitAI),然後載入該向量

本地

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

load_lora_weights

< >

( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name: typing.Optional[str] = None hotswap: bool = False **kwargs )

引數

  • pretrained_model_name_or_path_or_dict (stros.PathLikedict) — 請參見 lora_state_dict()
  • adapter_name (str, 可選) — 用於引用已載入介面卡模型的介面卡名稱。如果未指定,將使用 default_{i},其中 i 是正在載入的介面卡總數。
  • low_cpu_mem_usage (bool, 可選) — 透過僅載入預訓練的 LoRA 權重而不初始化隨機權重來加快模型載入速度。
  • hotswap (bool, 可選) — 預設為 False。是否用新載入的介面卡就地替換現有(LoRA)介面卡。這意味著,不是載入額外的介面卡,而是將現有介面卡權重替換為新介面卡的權重。這可以更快、更節省記憶體。然而,熱插拔的主要優點是,當模型使用 torch.compile 編譯時,載入新介面卡不需要重新編譯模型。使用熱插拔時,傳遞的 adapter_name 應該是已載入介面卡的名稱。

    如果新介面卡和舊介面卡具有不同的秩和/或 LoRA alpha(即縮放),則需要在載入介面卡之前呼叫一個額外的方法:

pretrained_model_name_or_path_or_dict 中指定的 LoRA 權重載入到 self.unetself.text_encoder 中。

所有 kwargs 都轉發到 self.lora_state_dict

有關如何載入 state dict 的更多詳細資訊,請參閱 lora_state_dict()

有關如何將 state dict 載入到 self.unet 中的更多詳細資訊,請參閱 load_lora_into_unet()

有關如何將 state dict 載入到 self.text_encoder 中的更多詳細資訊,請參閱 load_lora_into_text_encoder()

save_lora_weights

< >

( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None text_encoder_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = True unet_lora_adapter_metadata = None text_encoder_lora_adapter_metadata = None )

引數

  • save_directory (stros.PathLike) — LoRA 引數儲存目錄。如果不存在,將建立該目錄。
  • unet_lora_layers (Dict[str, torch.nn.Module]Dict[str, torch.Tensor]) — 對應於 unet 的 LoRA 層狀態字典。
  • text_encoder_lora_layers (Dict[str, torch.nn.Module]Dict[str, torch.Tensor]) — 對應於 text_encoder 的 LoRA 層狀態字典。必須顯式傳遞文字編碼器 LoRA 狀態字典,因為它來自 🤗 Transformers。
  • is_main_process (bool, 可選,預設為 True) — 呼叫此過程是否為主過程。在分散式訓練期間很有用,您需要在所有過程上呼叫此函式。在這種情況下,僅在主過程上設定 is_main_process=True 以避免競態條件。
  • save_function (Callable) — 用於儲存狀態字典的函式。在分散式訓練期間需要將 torch.save 替換為其他方法時很有用。可透過環境變數 DIFFUSERS_SAVE_MODE 進行配置。
  • safe_serialization (bool, 可選,預設為 True) — 是否使用 safetensors 而不是傳統的 PyTorch 方式(使用 pickle)儲存模型。
  • unet_lora_adapter_metadata — 與 unet 相關的 LoRA 介面卡元資料,將與狀態字典一起序列化。
  • text_encoder_lora_adapter_metadata — 與文字編碼器相關的 LoRA 介面卡元資料,將與狀態字典一起序列化。

儲存對應於 UNet 和文字編碼器的 LoRA 引數。

StableDiffusionXLInstructPix2PixPipeline

class diffusers.StableDiffusionXLInstructPix2PixPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None is_cosxl_edit: typing.Optional[bool] = False )

引數

  • 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 在推理過程中是否需要傳遞 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,否則不使用水印器。
  • is_cosxl_edit (bool, 可選) — 設定後,影像潛在表示將被縮放。

根據文字指令進行畫素級影像編輯的管道。基於 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 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 100 denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 image_guidance_scale: float = 1.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 output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None 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 ) ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

引數

  • 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]) — 要使用管道修改的影像。
  • 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) — 去噪步數。更多去噪步數通常會生成更高質量的影像,但推理速度會變慢。
  • denoising_end (float, 可選) — 指定時,確定在有意提前終止之前要完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留大量噪聲,由排程程式選擇的離散時間步長決定。denoising_end 引數應在管道作為“去噪器混合”多管道設定的一部分時使用,如Refining the Image Output中詳述。
  • guidance_scale (float, 可選, 預設為 5.0) — Classifier-Free Diffusion Guidance中定義的引導比例。guidance_scale 定義為 Imagen Paper中公式 2 的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例會促使生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • image_guidance_scale (float, 可選, 預設為 1.5) — 影像引導比例旨在將生成的影像推向初始影像 image。透過設定 image_guidance_scale > 1 啟用影像引導比例。更高的影像引導比例會促使生成與源影像 image 緊密相關的影像,通常以犧牲影像質量為代價。此管道要求值至少為 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 (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch generator(s),用於使生成具有確定性。
  • 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 輸入引數生成。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL: PIL.Image.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput 而不是普通元組。
  • callback (Callable, 可選) — 在推理過程中,每 callback_steps 步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — 呼叫 callback 函式的頻率。如果未指定,回撥將在每一步呼叫。
  • 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_scale 定義為 Common 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 節所述。
  • 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 節所述。可用於透過影響負面文字條件來模擬生成影像的美學分數。

返回

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

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

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

示例

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

>>> resolution = 768
>>> image = load_image(
...     "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"

>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
...     "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")

>>> edited_image = pipe(
...     prompt=edit_instruction,
...     image=image,
...     height=resolution,
...     width=resolution,
...     guidance_scale=3.0,
...     image_guidance_scale=1.5,
...     num_inference_steps=30,
... ).images[0]
>>> edited_image

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 )

引數

  • 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 層已載入)。

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

< > 在 GitHub 上更新

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