Diffusers 文件

影像到影像

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

影像到影像

LoRA

Stable Diffusion 模型還可以透過傳遞文字提示和初始影像來應用於影像到影像生成,以調節新影像的生成。

StableDiffusionImg2ImgPipeline 使用 Chenlin Meng、Yutong He、Yang Song、Jiaming Song、Jiajun Wu、Jun-Yan Zhu、Stefano Ermon 在 SDEdit: Guided Image Synthesis and Editing with Stochastic Differential Equations 中提出的擴散去噪機制。

論文摘要如下:

引導式影像合成使使用者能夠以最小的努力建立和編輯照片級影像。主要挑戰在於平衡對使用者輸入(例如,手繪彩色筆觸)的忠實度和合成影像的真實感。現有的基於 GAN 的方法試圖透過條件 GAN 或 GAN 逆向來達到這種平衡,這具有挑戰性,並且通常需要針對單個應用程式額外的訓練資料或損失函式。為了解決這些問題,我們引入了一種新的影像合成和編輯方法,隨機微分編輯 (SDEdit),它基於擴散模型生成先驗,透過隨機微分方程 (SDE) 迭代去噪來合成逼真影像。給定帶有任何型別使用者輸入的影像,SDEdit 首先向輸入新增噪聲,然後透過 SDE 先驗對生成的影像進行去噪,以提高其真實感。SDEdit 不需要特定於任務的訓練或逆向,並且可以自然地實現真實感和忠實度之間的平衡。根據一項人類感知研究,SDEdit 在影像合成和編輯以及影像合成等多個任務中,在真實感方面比最先進的基於 GAN 的方法高出 98.09%,在整體滿意度方面高出 91.72%。

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

StableDiffusionImg2ImgPipeline

class diffusers.StableDiffusionImg2ImgPipeline

< >

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

引數

  • 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'] **kwargs ) 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,但如果直接傳遞潛在空間,則不會再次編碼。
  • 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], 可選) — 用於支援在其 set_timesteps 方法中帶有 sigmas 引數的排程器進行去噪過程的自定義 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_embeds 將從 negative_prompt 輸入引數生成。
  • ip_adapter_image — (PipelineImageInput, 可選):用於IP Adapter的可選影像輸入。
  • 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 字典,如果指定,將作為 op 引數傳遞給 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 屬性中列出的變數。

返回

StableDiffusionPipelineOutputtuple

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

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

示例

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

>>> from diffusers import StableDiffusionImg2ImgPipeline

>>> device = "cuda"
>>> model_id_or_path = "stable-diffusion-v1-5/stable-diffusion-v1-5"
>>> pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
>>> pipe = pipe.to(device)

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

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

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

>>> images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
>>> images[0].save("fantasy_landscape.png")

enable_attention_slicing

< >

( slice_size: typing.Union[int, str, NoneType] = 'auto' )

引數

  • slice_size (strint, 可選,預設為 "auto") — 當設定為 "auto" 時,將輸入注意力頭的輸入減半,因此注意力將分兩步計算。如果設定為 "max",則透過一次只執行一個切片來節省最大記憶體。如果提供一個數字,則使用 attention_head_dim // slice_size 個切片。在這種情況下,attention_head_dim 必須是 slice_size 的倍數。

啟用切片注意力計算。當啟用此選項時,注意力模組將輸入張量分割成切片,分幾步計算注意力。對於多個注意力頭,計算按每個頭順序執行。這對於節省記憶體以換取小幅速度降低很有用。

⚠️ 如果您已經在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention (SDPA),請不要啟用注意力切片。這些注意力計算已經非常記憶體高效,因此您無需啟用此功能。如果您將注意力切片與 SDPA 或 xFormers 一起啟用,可能會導致嚴重的效能下降!

示例

>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

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

disable_attention_slicing

< >

( )

停用切片注意力計算。如果之前呼叫過 enable_attention_slicing,則注意力將一步計算完成。

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

引數

  • attention_op (Callable, 可選) — 覆蓋預設的 None 運算子,用作 xFormers 的 memory_efficient_attention() 函式的 op 引數。

啟用 xFormers 的記憶體高效注意力。啟用此選項後,您應該會觀察到較低的GPU記憶體使用量和推理期間的潛在速度提升。訓練期間的速度提升不予保證。

⚠️ 當記憶體高效注意力和切片注意力同時啟用時,記憶體高效注意力優先。

示例

>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)

disable_xformers_memory_efficient_attention

< >

( )

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

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狀態字典
  • 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, 可選) — 如果您在中國下載模型,為解決可訪問性問題而設定的映象源。我們不保證該源的及時性或安全性,您應參考映象站點以獲取更多資訊。

將文字反轉嵌入載入到 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")

from_single_file

< >

( pretrained_model_link_or_path **kwargs )

引數

  • pretrained_model_link_or_path (stros.PathLike, 可選) — 可以是以下之一:

    • Hub上的.ckpt檔案連結(例如"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt")。
    • 包含所有管道權重的檔案路徑。
  • torch_dtype (strtorch.dtype, 可選) — 覆蓋預設的 torch.dtype,並以另一種資料型別載入模型。
  • force_download (bool, 可選,預設為 False) — 是否強制(重新)下載模型權重和配置檔案,覆蓋現有快取版本。
  • cache_dir (Union[str, os.PathLike], 可選) — 如果不使用標準快取,則下載的預訓練模型配置的快取目錄路徑。
  • proxies (Dict[str, str], 可選) — 一個字典,包含按協議或端點使用的代理伺服器,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用於每個請求。
  • local_files_only (bool, 可選,預設為 False) — 是否只加載本地模型權重和配置檔案。如果設定為 True,模型將不會從 Hub 下載。
  • token (strbool, 可選) — 用作遠端檔案HTTP bearer授權的token。如果為 True,則使用 diffusers-cli login 生成的token(儲存在 ~/.huggingface 中)。
  • revision (str, 可選,預設為 "main") — 要使用的特定模型版本。它可以是分支名稱、標籤名稱、提交ID或Git允許的任何識別符號。
  • original_config_file (str, 可選) — 用於訓練模型的原始配置檔案路徑。如果未提供,配置檔案將從檢查點檔案推斷。
  • config (str, 可選) — 可以是以下之一:

    • Hub上預訓練管道的倉庫ID(例如CompVis/ldm-text2im-large-256)。
    • 包含Diffusers格式管道元件配置的目錄路徑(例如./my_pipeline_directory/)。
  • disable_mmap (‘bool’, 可選,預設為 ‘False’) — 載入 Safetensors 模型時是否停用mmap。當模型位於網路掛載或硬碟上時,此選項可能表現更好。
  • kwargs (剩餘的關鍵字引數字典,可選) — 可用於覆蓋可載入和可儲存的變數(特定管道類的管道元件)。被覆蓋的元件直接傳遞給管道的 __init__ 方法。更多資訊請參見下面的示例。

從以 .ckpt.safetensors 格式儲存的預訓練管道權重例項化 DiffusionPipeline。管道預設設定為評估模式 (model.eval())。

示例

>>> from diffusers import StableDiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
... )

>>> # Download pipeline from local file
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly.ckpt")

>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
...     torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")

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 引數。

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

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

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

引數

  • images (List[PIL.Image.Image]np.ndarray) — 長度為 batch_size 的去噪 PIL 影像列表,或形狀為 (batch_size, height, width, num_channels) 的 NumPy 陣列。
  • nsfw_content_detected (List[bool]) — 列表,指示生成的影像是否包含“不適合工作”(nsfw) 內容,如果無法執行安全檢查,則為 None

Stable Diffusion 管道的輸出類。

FlaxStableDiffusionImg2ImgPipeline

class diffusers.FlaxStableDiffusionImg2ImgPipeline

< >

( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_flax.FlaxDDIMScheduler, diffusers.schedulers.scheduling_pndm_flax.FlaxPNDMScheduler, diffusers.schedulers.scheduling_lms_discrete_flax.FlaxLMSDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep_flax.FlaxDPMSolverMultistepScheduler] safety_checker: FlaxStableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor dtype: dtype = <class 'jax.numpy.float32'> )

引數

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

基於 Flax 的 Stable Diffusion 文字引導影像到影像生成流水線。

此模型繼承自 FlaxDiffusionPipeline。有關所有流水線實現的通用方法(下載、儲存、在特定裝置上執行等)請檢視超類文件。

__call__

< >

( prompt_ids: Array image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array strength: float = 0.8 num_inference_steps: int = 50 height: typing.Optional[int] = None width: typing.Optional[int] = None guidance_scale: typing.Union[float, jax.Array] = 7.5 noise: Array = None neg_prompt_ids: Array = None return_dict: bool = True jit: bool = False ) FlaxStableDiffusionPipelineOutputtuple

引數

  • prompt_ids (jnp.ndarray) — 用於引導影像生成的提示詞。
  • image (jnp.ndarray) — 表示用作起點的影像批處理陣列。
  • params (DictFrozenDict) — 包含模型引數/權重的字典。
  • prng_seed (jax.Arrayjax.Array) — 包含隨機數生成器金鑰的陣列。
  • strength (float, 可選, 預設為 0.8) — 指示轉換參考 image 的程度。必須介於 0 到 1 之間。image 用作起點,strength 越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當 strength 為 1 時,新增的噪聲最大,去噪過程將執行 num_inference_steps 中指定的全部迭代次數。值為 1 基本上會忽略 image
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。此引數受 strength 調製。
  • height (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。
  • width (int, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。
  • guidance_scale (float, 可選, 預設為 7.5) — 較高的引導比例值鼓勵模型生成與文字 prompt 緊密相關的影像,但影像質量較低。當 guidance_scale > 1 時,啟用引導比例。
  • noise (jnp.ndarray, 可選) — 從高斯分佈中取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。該陣列透過使用提供的隨機 generator 進行取樣來生成。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元組。
  • jit (bool, 預設為 False) — 是否執行生成和安全評分函式的 pmap 版本。

    此引數存在是因為 __call__ 尚未實現端到端的 pmap。它將在未來版本中移除。

返回

FlaxStableDiffusionPipelineOutputtuple

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

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

示例

>>> import jax
>>> import numpy as np
>>> import jax.numpy as jnp
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> import requests
>>> from io import BytesIO
>>> from PIL import Image
>>> from diffusers import FlaxStableDiffusionImg2ImgPipeline


>>> def create_key(seed=0):
...     return jax.random.PRNGKey(seed)


>>> rng = create_key(0)

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> init_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_img = init_img.resize((768, 512))

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

>>> pipeline, params = FlaxStableDiffusionImg2ImgPipeline.from_pretrained(
...     "CompVis/stable-diffusion-v1-4",
...     revision="flax",
...     dtype=jnp.bfloat16,
... )

>>> num_samples = jax.device_count()
>>> rng = jax.random.split(rng, jax.device_count())
>>> prompt_ids, processed_image = pipeline.prepare_inputs(
...     prompt=[prompts] * num_samples, image=[init_img] * num_samples
... )
>>> p_params = replicate(params)
>>> prompt_ids = shard(prompt_ids)
>>> processed_image = shard(processed_image)

>>> output = pipeline(
...     prompt_ids=prompt_ids,
...     image=processed_image,
...     params=p_params,
...     prng_seed=rng,
...     strength=0.75,
...     num_inference_steps=50,
...     jit=True,
...     height=512,
...     width=768,
... ).images

>>> output_images = pipeline.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))

FlaxStableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput

< >

( images: ndarray nsfw_content_detected: typing.List[bool] )

引數

  • images (np.ndarray) — 形狀為 (batch_size, height, width, num_channels) 的去噪影像陣列。
  • nsfw_content_detected (List[bool]) — 列表,指示生成的影像是否包含“不適合工作”(nsfw) 內容,如果無法執行安全檢查,則為 None

Flax-based Stable Diffusion 管道的輸出類。

替換

< >

( **updates )

返回一個新物件,用新值替換指定的欄位。

< > 在 GitHub 上更新

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