Diffusers 文件

ControlNet

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

ControlNet

LoRA

ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《為文字到影像擴散模型新增條件控制》 中提出。

透過 ControlNet 模型,你可以提供額外的控制影像來條件化和控制 Stable Diffusion 的生成。例如,如果你提供一個深度圖,ControlNet 模型將生成一個保留深度圖空間資訊的影像。這是一種更靈活、更準確的影像生成控制方式。

論文摘要如下:

我們提出了 ControlNet,一種用於為大型預訓練文字到影像擴散模型新增空間條件控制的神經網路架構。ControlNet 鎖定即用型大型擴散模型,並重用它們在數十億影像上預訓練的深度且穩健的編碼層作為強大的主幹,以學習多樣化的條件控制。該神經網路架構透過“零卷積”(零初始化卷積層)連線,這些層逐步從零開始增長引數,並確保沒有有害噪聲會影響微調。我們使用 Stable Diffusion 測試了各種條件控制,例如邊緣、深度、分割、人體姿態等,可以使用單個或多個條件,帶或不帶提示。我們表明 ControlNets 的訓練在小型(<50k)和大型(>1m)資料集上都很穩健。大量結果表明,ControlNet 可以促進更廣泛的應用,以控制影像擴散模型。

此模型由 takuma104 貢獻。❤️

原始程式碼庫可在 lllyasviel/ControlNet 找到,你可以在 lllyasviel 的 Hub 配置檔案中找到官方 ControlNet 檢查點。

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

StableDiffusionControlNetPipeline

class diffusers.StableDiffusionControlNetPipeline

< >

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

引數

  • 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 的輸入。

用於使用 ControlNet 指導進行文字到影像生成的管道。

此模型繼承自 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 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 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 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'] **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], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 輸入條件,用於為 unet 提供生成指導。如果型別指定為 torch.Tensor,則直接傳遞給 ControlNet。PIL.Image.Image 也可以作為影像接受。輸出影像的尺寸預設為 image 的尺寸。如果傳入了高度和/或寬度,image 將相應地調整大小。如果在 init 中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表中的每個元素都可以正確地批次輸入到單個 ControlNet。當 prompt 是一個列表時,如果為單個 ControlNet 傳入影像列表,則每個影像都將與 prompt 列表中的每個提示配對。這也適用於多個 ControlNet,其中可以傳入影像列表的列表,以便為每個提示和每個 ControlNet 進行批次處理。
  • 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], 可選) — 用於去噪過程的自定義時間步,適用於支援 timesteps 引數的排程器,在其 set_timesteps 方法中。如果未定義,將使用傳入 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 sigmas,適用於支援 sigmas 引數的排程器,在其 set_timesteps 方法中。如果未定義,將使用傳入 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 Adapters 配合使用的可選影像輸入。
  • 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 而不是普通元組。
  • callback (Callable, 可選) — 在推理過程中每 callback_steps 步呼叫的函式。該函式呼叫時帶有以下引數:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — callback 函式被呼叫的頻率。如果未指定,則在每一步都呼叫回撥。
  • cross_attention_kwargs (dict, 可選) — 如果指定,一個 kwargs 字典將被傳遞給 self.processor 中定義的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始 unet 的殘差之前乘以 controlnet_conditioning_scale。如果在 init 中指定了多個 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 停止應用的總體步數百分比。
  • 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)內容。

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

示例

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

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

>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> image = np.array(image)

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

>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> # remove following line if xformers is not installed
>>> pipe.enable_xformers_memory_efficient_attention()

>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
...     "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
... ).images[0]

enable_attention_slicing

< >

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

引數

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

啟用切片注意力計算。啟用此選項後,注意力模組會將輸入張量分成多個切片,分步計算注意力。對於多個注意力頭,計算按每個頭順序執行。這有助於節省一些記憶體,但會略微降低速度。

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

示例

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

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

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

disable_attention_slicing

< >

( )

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

enable_vae_slicing

< >

( )

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

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing,此方法將返回一步計算解碼。

enable_xformers_memory_efficient_attention

< >

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

引數

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

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

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

示例

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

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

disable_xformers_memory_efficient_attention

< >

( )

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

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

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

StableDiffusionControlNetImg2ImgPipeline

class diffusers.StableDiffusionControlNetImg2ImgPipeline

< >

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

引數

  • 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。請查閱超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。

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

__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 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 = 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.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 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'] **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], — 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 輸入條件,用於為 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) — 生成影像的寬度(畫素)。
  • 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) — 較高的引導尺度值會促使模型生成與文字 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 介面卡數量相同。每個元素應該是一個形狀為 (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 的輸出乘以 controlnet_conditioning_scale,然後新增到原始 unet 中的殘差中。如果 init 中指定了多個 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 停止應用的步驟總數的百分比。
  • 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)內容。

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

示例

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

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

>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> np_image = np.array(image)

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

>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
...     "futuristic-looking woman",
...     num_inference_steps=20,
...     generator=generator,
...     image=image,
...     control_image=canny_image,
... ).images[0]

enable_attention_slicing

< >

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

引數

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

啟用切片注意力計算。啟用此選項後,注意力模組會將輸入張量分成多個切片,分步計算注意力。對於多個注意力頭,計算按每個頭順序執行。這有助於節省一些記憶體,但會略微降低速度。

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

示例

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

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

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

disable_attention_slicing

< >

( )

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

enable_vae_slicing

< >

( )

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

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing,此方法將返回一步計算解碼。

enable_xformers_memory_efficient_attention

< >

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

引數

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

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

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

示例

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

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

disable_xformers_memory_efficient_attention

< >

( )

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

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], 可選) — 覆蓋用於文字反轉權重的標記。如果 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 承載授權的令牌。如果為 True,則使用從 diffusers-cli login 生成的令牌(儲存在 ~/.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")

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

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

StableDiffusionControlNetInpaintPipeline

class diffusers.StableDiffusionControlNetInpaintPipeline

< >

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

引數

  • 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。請查閱超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。

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

此管道可與專門為影像修復微調過的檢查點(stable-diffusion-v1-5/stable-diffusion-inpainting)以及預設的文字到影像 Stable Diffusion 檢查點(stable-diffusion-v1-5/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 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 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'] **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]): 用作起點的影像批處理(PIL 影像、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]): PIL 影像、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,則不裁剪影像和 mask_image。如果 padding_mask_crop 不為 None,它將首先找到一個與影像長寬比相同且包含所有遮罩區域的矩形區域,然後根據 padding_mask_crop 擴充套件該區域。然後,影像和 mask_image 將根據擴充套件區域進行裁剪,再調整大小以用於影像修復。當遮罩區域很小而影像很大且包含與影像修復無關的資訊(例如背景)時,這很有用。
  • 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 輸入引數生成 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
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 0.5) — ControlNet 的輸出乘以 controlnet_conditioning_scale,然後新增到原始 unet 中的殘差。如果在 init 中指定了多個 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 停止應用的步驟總數百分比。
  • 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)內容。

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

示例

>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> 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 = StableDiffusionControlNetInpaintPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> 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,
... ).images[0]

enable_attention_slicing

< >

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

引數

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

啟用切片注意力計算。啟用此選項後,注意力模組會將輸入張量分成多個切片,分步計算注意力。對於多個注意力頭,計算按每個頭順序執行。這有助於節省一些記憶體,但會略微降低速度。

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

示例

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

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

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

disable_attention_slicing

< >

( )

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

enable_vae_slicing

< >

( )

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

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing,此方法將返回一步計算解碼。

enable_xformers_memory_efficient_attention

< >

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

引數

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

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

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

示例

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

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

disable_xformers_memory_efficient_attention

< >

( )

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

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 承載授權的令牌。如果為 True,則使用 diffusers-cli login 生成的令牌(儲存在 ~/.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")

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

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

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 管道的輸出類。

FlaxStableDiffusionControlNetPipeline

class diffusers.FlaxStableDiffusionControlNetPipeline

< >

( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel controlnet: FlaxControlNetModel 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,用於對編碼影像的潛在表示進行去噪。
  • controlnet (FlaxControlNetModel — 在去噪過程中為 unet 提供額外的條件。
  • scheduler (SchedulerMixin) — 與 unet 結合使用的排程器,用於對編碼影像的潛在表示進行去噪。可以是 FlaxDDIMSchedulerFlaxLMSDiscreteSchedulerFlaxPNDMSchedulerFlaxDPMSolverMultistepScheduler 之一。
  • safety_checker (FlaxStableDiffusionSafetyChecker) — 分類模組,用於評估生成的影像是否可能被視為冒犯性或有害。請參閱模型卡,瞭解有關模型潛在危害的更多詳細資訊。
  • feature_extractor (CLIPImageProcessor) — 一個 CLIPImageProcessor,用於從生成的影像中提取特徵;用作 safety_checker 的輸入。

基於 Flax 的管道,用於使用帶有 ControlNet Guidance 的 Stable Diffusion 進行文字到影像生成。

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

__call__

< >

( prompt_ids: Array image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None controlnet_conditioning_scale: typing.Union[float, jax.Array] = 1.0 return_dict: bool = True jit: bool = False ) FlaxStableDiffusionPipelineOutputtuple

引數

  • prompt_ids (jnp.ndarray) — 用於引導影像生成的提示詞。
  • image (jnp.ndarray) — 表示 ControlNet 輸入條件的陣列,用於為 unet 提供生成指導。
  • params (DictFrozenDict) — 包含模型引數/權重的字典。
  • prng_seed (jax.Array) — 包含隨機數生成器金鑰的陣列。
  • num_inference_steps (int, 可選, 預設為 50) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但會以更慢的推理速度為代價。
  • guidance_scale (float, 可選, 預設為 7.5) — 較高的指導比例值會促使模型生成與文字 prompt 緊密相關的影像,但會以較低的影像質量為代價。當 guidance_scale > 1 時,啟用指導比例。
  • latents (jnp.ndarray, 可選) — 從高斯分佈中取樣的預生成噪聲潛在變數,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則使用提供的隨機 generator 取樣生成潛在變數陣列。
  • controlnet_conditioning_scale (floatjnp.ndarray, 可選, 預設為 1.0) — ControlNet 的輸出乘以 controlnet_conditioning_scale 後,再新增到原始 unet 中的殘差。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通的元組。
  • jit (bool, 預設為 False) — 是否執行生成和安全評分函式的 pmap 版本。

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

返回

FlaxStableDiffusionPipelineOutputtuple

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

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

示例

>>> import jax
>>> import numpy as np
>>> import jax.numpy as jnp
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> from diffusers.utils import load_image, make_image_grid
>>> from PIL import Image
>>> from diffusers import FlaxStableDiffusionControlNetPipeline, FlaxControlNetModel


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


>>> rng = create_key(0)

>>> # get canny image
>>> canny_image = load_image(
...     "https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/blog_post_cell_10_output_0.jpeg"
... )

>>> prompts = "best quality, extremely detailed"
>>> negative_prompts = "monochrome, lowres, bad anatomy, worst quality, low quality"

>>> # load control net and stable diffusion v1-5
>>> controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
...     "lllyasviel/sd-controlnet-canny", from_pt=True, dtype=jnp.float32
... )
>>> pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     controlnet=controlnet,
...     revision="flax",
...     dtype=jnp.float32,
... )
>>> params["controlnet"] = controlnet_params

>>> num_samples = jax.device_count()
>>> rng = jax.random.split(rng, jax.device_count())

>>> prompt_ids = pipe.prepare_text_inputs([prompts] * num_samples)
>>> negative_prompt_ids = pipe.prepare_text_inputs([negative_prompts] * num_samples)
>>> processed_image = pipe.prepare_image_inputs([canny_image] * num_samples)

>>> p_params = replicate(params)
>>> prompt_ids = shard(prompt_ids)
>>> negative_prompt_ids = shard(negative_prompt_ids)
>>> processed_image = shard(processed_image)

>>> output = pipe(
...     prompt_ids=prompt_ids,
...     image=processed_image,
...     params=p_params,
...     prng_seed=rng,
...     num_inference_steps=50,
...     neg_prompt_ids=negative_prompt_ids,
...     jit=True,
... ).images

>>> output_images = pipe.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))
>>> output_images = make_image_grid(output_images, num_samples // 4, 4)
>>> output_images.save("generated_image.png")

FlaxStableDiffusionControlNetPipelineOutput

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.