Diffusers 文件
ControlNet 與 Stable Diffusion XL
並獲得增強的文件體驗
開始使用
ControlNet 與 Stable Diffusion XL
ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《為文字到影像擴散模型新增條件控制》 中提出。
透過 ControlNet 模型,您可以提供額外的控制影像來調整和控制 Stable Diffusion 生成。例如,如果您提供深度圖,ControlNet 模型將生成一張保留深度圖空間資訊的影像。這是一種更靈活、更準確的影像生成控制方式。
論文摘要如下:
我們提出了 ControlNet,一種用於為大型預訓練文字到影像擴散模型新增空間條件控制的神經網路架構。ControlNet 鎖定生產級大型擴散模型,並重用其經過數十億影像預訓練的深層、穩健的編碼層作為強大的骨幹網路,以學習多樣化的條件控制。該神經網路架構透過“零卷積”(零初始化卷積層)連線,這些層逐步從零開始增長引數,並確保不會有害的噪聲影響微調。我們使用 Stable Diffusion 測試了各種條件控制,例如邊緣、深度、分割、人體姿態等,可以使用單個或多個條件,帶或不帶提示詞。我們展示了 ControlNet 的訓練在小(<50k)和大(>1m)資料集上均表現出穩健性。大量結果表明,ControlNet 可以促進影像擴散模型的更廣泛應用。
您可以在 🤗 Diffusers Hub 組織中找到其他較小的 Stable Diffusion XL (SDXL) ControlNet 檢查點,並在 Hub 上瀏覽 社群訓練的 檢查點。
🧪 許多 SDXL ControlNet 檢查點仍處於實驗階段,還有很大的改進空間。歡迎隨時提出 問題 並向我們提供改進建議!
如果您沒有找到您感興趣的檢查點,可以使用我們的 訓練指令碼 訓練您自己的 SDXL ControlNet。
StableDiffusionXLControlNetPipeline
class diffusers.StableDiffusionXLControlNetPipeline
< 原始碼 >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
- text_encoder_2 (CLIPTextModelWithProjection) — 第二個凍結的文字編碼器 (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)。
- tokenizer (CLIPTokenizer) — 用於文字分詞的
CLIPTokenizer
。 - tokenizer_2 (CLIPTokenizer) — 用於文字分詞的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛變數去噪的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪過程中為unet
提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出會相加,以建立一個組合的額外條件。 - scheduler (SchedulerMixin) — 用於與
unet
結合使用的排程器,以對編碼影像潛在變數去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 中的一個。 - force_zeros_for_empty_prompt (
bool
, 可選, 預設為"True"
) — 負面提示詞嵌入是否應始終設定為 0。另請參閱stabilityai/stable-diffusion-xl-base-1-0
的配置。 - add_watermarker (
bool
, 可選) — 是否使用 invisible_watermark 庫對輸出影像新增水印。如果未定義,則在安裝了該包的情況下預設為True
;否則不使用水印。
使用 Stable Diffusion XL 和 ControlNet 指導的文字到影像生成流水線。
該模型繼承自 DiffusionPipeline。請檢視超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__call__
< 原始碼 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None 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 ) → StableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞或提示詞列表。如果未定義,您需要傳遞prompt_embeds
。 - prompt_2 (
str
或List[str]
, 可選) — 將傳送到tokenizer_2
和text_encoder_2
的提示詞或提示詞列表。如果未定義,則在兩個文字編碼器中都使用prompt
。 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): 用於為unet
生成提供引導的 ControlNet 輸入條件。如果型別指定為torch.Tensor
,則直接傳遞給 ControlNet。也可以接受PIL.Image.Image
作為影像。輸出影像的尺寸預設為image
的尺寸。如果傳遞了 height 和/或 width,則image
會相應調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確地批次輸入到單個 ControlNet。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的高度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都將無法很好地工作。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的寬度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都將無法很好地工作。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會導致更高質量的影像,但推理速度會變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步長,適用於支援在其set_timesteps
方法中接受timesteps
引數的排程器。如果未定義,將使用傳入num_inference_steps
時的預設行為。必須按降序排列。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於支援在其set_timesteps
方法中接受sigmas
引數的排程器。如果未定義,將使用傳入num_inference_steps
時的預設行為。 - denoising_end (
float
, 可選) — 指定時,確定在去噪過程有意提前終止前完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留由排程器選擇的離散時間步長所決定的相當數量的噪聲。denoising_end
引數最好在以下情況下使用:當此管道作為“去噪器混合體”多管道設定的一部分時,如 最佳化影像輸出 中所詳述。 - guidance_scale (
float
, 可選, 預設為 5.0) — 較高的引導比例值鼓勵模型生成與文字prompt
緊密相關的影像,但會犧牲影像質量。當guidance_scale > 1
時,啟用引導比例。 - negative_prompt (
str
或List[str]
, 可選) — 用於指導影像生成中不應包含的內容的提示或多個提示。如果未定義,您需要傳遞negative_prompt_embeds
。當不使用引導時(guidance_scale < 1
),此引數將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 用於指導影像生成中不應包含的內容的提示或多個提示。此引數將傳送到tokenizer_2
和text_encoder_2
。如果未定義,negative_prompt
將用於兩個文字編碼器。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個torch.Generator
用於使生成具有確定性。 - latents (
torch.Tensor
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在變數,用作影像生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,則使用提供的隨機generator
進行取樣生成潛在張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,池化negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 與 IP 介面卡配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 用於 IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,則應包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇PIL.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 如果指定,則將作為 kwargs 字典傳遞給self.processor
中定義的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始unet
中的殘差之前乘以controlnet_conditioning_scale
。如果在init
中指定了多個 ControlNet,則可以將相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — 即使您刪除所有提示,ControlNet 編碼器也會嘗試識別輸入影像的內容。建議使用介於 3.0 和 5.0 之間的guidance_scale
值。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的步數佔總步數的百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的步數佔總步數的百分比。 - original_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 如果original_size
與target_size
不同,影像將顯示為縮小或放大。如果未指定,original_size
預設為(height, width)
。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。 - crops_coords_top_left (
Tuple[int]
, 可選, 預設為 (0, 0)) —crops_coords_top_left
可用於生成從crops_coords_top_left
位置向下“裁剪”的影像。透過將crops_coords_top_left
設定為 (0, 0),通常可以獲得效果良好、居中的影像。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。 - target_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size
應設定為生成影像的所需高度和寬度。如果未指定,它將預設為(height, width)
。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。 - negative_original_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 用於根據特定影像解析度對生成過程進行負面調節。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。有關更多資訊,請參閱此問題討論串: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可選, 預設為 (0, 0)) — 用於根據特定裁剪座標對生成過程進行負面調節。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。有關更多資訊,請參閱此問題討論串: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 用於根據目標影像解析度對生成過程進行負面調節。在大多數情況下應與target_size
相同。作為 SDXL 微條件化的一部分,如 https://huggingface.co/papers/2307.01952 的第 2.2 節所述。有關更多資訊,請參閱此問題討論串: https://github.com/huggingface/diffusers/issues/4208。 - clip_skip (
int
, 可選) — 計算提示嵌入時要從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可選) — 一個函式或PipelineCallback
或MultiPipelineCallbacks
的子類,在推理過程中每個去噪步驟結束時呼叫。引數為:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 StableDiffusionPipelineOutput,否則返回包含輸出影像的 tuple
。
用於生成的管道的呼叫函式。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )
>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)
>>> # generate image
>>> image = pipe(
... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
... ).images[0]
encode_prompt
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示 - prompt_2 (
str
或List[str]
, 可選) — 要傳送到tokenizer_2
和text_encoder_2
的提示或多個提示。如果未定義,prompt
將用於兩個文字編碼器。 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用無分類器引導 - negative_prompt (
str
或List[str]
, 可選) — 不用於指導影像生成的提示或多個提示。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 不用於指導影像生成併發送到tokenizer_2
和text_encoder_2
的提示或多個提示。如果未定義,negative_prompt
將用於兩個文字編碼器。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 將應用於文字編碼器所有 LoRA 層的 LoRA 比例(如果已載入 LoRA 層)。 - clip_skip (
int
, 可選) — 計算提示嵌入時要從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionXLControlNetImg2ImgPipeline
class diffusers.StableDiffusionXLControlNetImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器(VAE)模型。
- text_encoder (
CLIPTextModel
) — 凍結的文字編碼器。Stable Diffusion 使用 CLIP 的文字部分,特別是 clip-vit-large-patch14 變體。 - text_encoder_2 (
CLIPTextModelWithProjection
) — 第二個凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字和池化部分,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 類的分詞器。 - tokenizer_2 (
CLIPTokenizer
) — CLIPTokenizer 類的第二個分詞器。 - unet (UNet2DConditionModel) — 用於對編碼影像潛碼進行去噪的條件 U-Net 架構。
- controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪過程中為 unet 提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將相加,以建立一個組合的額外條件。 - scheduler (SchedulerMixin) — 與
unet
結合使用的排程器,用於對編碼影像潛碼進行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - requires_aesthetics_score (
bool
, 可選, 預設為"False"
) —unet
在推理過程中是否需要傳遞aesthetic_score
條件。另請參閱stabilityai/stable-diffusion-xl-refiner-1-0
的配置。 - force_zeros_for_empty_prompt (
bool
, 可選, 預設為"True"
) — 負面提示嵌入是否應強制始終設定為 0。另請參閱stabilityai/stable-diffusion-xl-base-1-0
的配置。 - add_watermarker (
bool
, 可選) — 是否使用 invisible_watermark 庫 為輸出影像新增水印。如果未定義,如果已安裝該包,則預設為 True,否則不使用水印器。 - feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
使用 Stable Diffusion XL 和 ControlNet 引導的影像到影像生成管道。
此模型繼承自 DiffusionPipeline。有關庫為所有管道(例如下載或儲存、在特定裝置上執行等)實現的通用方法,請查閱超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 num_inference_steps: int = 50 guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → StableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示或提示。如果未定義,則必須傳遞prompt_embeds
。 - prompt_2 (
str
或List[str]
, 可選) — 要傳送到tokenizer_2
和text_encoder_2
的提示或提示。如果未定義,則prompt
將用於兩個文字編碼器。 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): 初始影像將用作影像生成過程的起始點。如果直接傳遞潛在表示,也可以接受影像潛在表示作為image
,它將不會再次編碼。 - control_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): ControlNet 的輸入條件。ControlNet 使用此輸入條件為 Unet 生成引導。如果型別指定為torch.Tensor
,則按原樣傳遞給 ControlNet。PIL.Image.Image
也可以作為影像接受。輸出影像的尺寸預設為image
的尺寸。如果傳遞了高度和/或寬度,則image
會根據它們進行調整大小。如果在初始化中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確批處理以輸入到單個 ControlNet。 - height (
int
, 可選, 預設為 control_image 的大小) — 生成影像的高度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何內容都無法很好地工作。 - width (
int
, 可選, 預設為 control_image 的大小) — 生成影像的寬度(畫素)。對於 stabilityai/stable-diffusion-xl-base-1.0 以及未專門針對低解析度進行微調的檢查點,低於 512 畫素的任何內容都無法很好地工作。 - strength (
float
, 可選, 預設為 0.8) — 指示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起始點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的全部迭代次數。值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略此引數。 - negative_prompt_2 (
str
或List[str]
, 可選) — 要傳送到tokenizer_2
和text_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.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。 - latents (
torch.Tensor
, 可選) — 預生成的噪聲潛在表示,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,則將透過使用提供的隨機generator
進行取樣來生成潛在張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從negative_prompt
輸入引數生成負文字嵌入。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從prompt
輸入引數生成池化文字嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從negative_prompt
輸入引數生成池化負文字嵌入。 - ip_adapter_image — (
PipelineImageInput
, 可選): 與 IP 介面卡配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 的數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在 PIL:PIL.Image.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,則傳遞給 diffusers.models.attention_processor 中定義的self.processor
下的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — controlnet 的輸出在新增到原始 unet 中的殘差之前乘以controlnet_conditioning_scale
。如果在初始化中指定了多個 ControlNet,則可以將其相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — 在此模式下,即使您刪除了所有提示,ControlNet 編碼器也會盡力識別輸入影像的內容。建議guidance_scale
在 3.0 到 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — controlnet 開始應用的步驟總數的百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — controlnet 停止應用的步驟總數的百分比。 - original_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 如果original_size
與target_size
不同,影像將顯示為下采樣或上取樣。如果未指定,original_size
預設為(height, width)
。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。 - crops_coords_top_left (
Tuple[int]
, optional, defaults to (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]
, optional, defaults to (1024, 1024)) — 在大多數情況下,target_size
應設定為生成影像的所需高度和寬度。如果未指定,它將預設為(height, width)
。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。 - negative_original_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 根據特定影像解析度對生成過程進行負面條件化。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, optional, defaults to (0, 0)) — 根據特定裁剪座標對生成過程進行負面條件化。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, optional, defaults to (1024, 1024)) — 根據目標影像解析度對生成過程進行負面條件化。在大多數情況下,它應該與target_size
相同。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。更多資訊請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - aesthetic_score (
float
, optional, defaults to 6.0) — 透過影響正向文字條件來模擬生成影像的美學分數。這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。 - negative_aesthetic_score (
float
, optional, defaults to 2.5) — 這是 SDXL 微條件的一部分,詳見 https://huggingface.co/papers/2307.01952 的第 2.2 節。可用於透過影響負向文字條件來模擬生成影像的美學分數。 - clip_skip (
int
, optional) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, optional) — 在推理過程中,每個去噪步驟結束時呼叫的函式或PipelineCallback
或MultiPipelineCallbacks
的子類,具有以下引數: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
, optional) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
StableDiffusionPipelineOutput 或 tuple
StableDiffusionPipelineOutput 如果 return_dict
為 True,否則為包含輸出影像的 tuple
。
呼叫管道進行生成時呼叫的函式。
示例
>>> # pip install accelerate transformers safetensors diffusers
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from transformers import DPTImageProcessor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image
>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
... "diffusers/controlnet-depth-sdxl-1.0-small",
... variant="fp16",
... use_safetensors=True,
... torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetImg2ImgPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0",
... controlnet=controlnet,
... vae=vae,
... variant="fp16",
... use_safetensors=True,
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> def get_depth_map(image):
... image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
... with torch.no_grad(), torch.autocast("cuda"):
... depth_map = depth_estimator(image).predicted_depth
... depth_map = torch.nn.functional.interpolate(
... depth_map.unsqueeze(1),
... size=(1024, 1024),
... mode="bicubic",
... align_corners=False,
... )
... depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
... depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
... depth_map = (depth_map - depth_min) / (depth_max - depth_min)
... image = torch.cat([depth_map] * 3, dim=1)
... image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
... image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
... return image
>>> prompt = "A robot, 4k photo"
>>> image = load_image(
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
... "/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
>>> depth_image = get_depth_map(image)
>>> images = pipe(
... prompt,
... image=image,
... control_image=depth_image,
... strength=0.99,
... num_inference_steps=50,
... controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")
encode_prompt
< source >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
orList[str]
, optional) — 要編碼的提示 - prompt_2 (
str
orList[str]
, optional) — 要傳送到tokenizer_2
和text_encoder_2
的提示。如果未定義,prompt
將在兩個文字編碼器中使用。 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導 - negative_prompt (
str
orList[str]
, optional) — 不用於引導影像生成的提示。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即guidance_scale
小於1
時),此引數將被忽略。 - negative_prompt_2 (
str
orList[str]
, optional) — 不用於引導影像生成,要傳送到tokenizer_2
和text_encoder_2
的提示。如果未定義,negative_prompt
將在兩個文字編碼器中使用。 - prompt_embeds (
torch.Tensor
, optional) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 預先生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從negative_prompt
輸入引數生成負向文字嵌入。 - pooled_prompt_embeds (
torch.Tensor
, optional) — 預先生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, optional) — 預先生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化負向文字嵌入將從negative_prompt
輸入引數生成。 - lora_scale (
float
, optional) — 將應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子(如果載入了 LoRA 層)。 - clip_skip (
int
, optional) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
StableDiffusionXLControlNetInpaintPipeline
class diffusers.StableDiffusionXLControlNetInpaintPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None )
引數
- 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
結合使用以對編碼影像潛在量進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
用於使用 Stable Diffusion XL 進行文字到影像生成的管道。
此模型繼承自 DiffusionPipeline。有關庫為所有管道(例如下載或儲存、在特定裝置上執行等)實現的通用方法,請查閱超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], typing.List[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 = 0.9999 num_inference_steps: int = 50 denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None 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 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 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 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 aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
or tuple
引數
- prompt (
str
orList[str]
, optional) — 用於引導影像生成的提示。如果未定義,則必須傳遞prompt_embeds
。 - prompt_2 (
str
orList[str]
, optional) — 要傳送到tokenizer_2
和text_encoder_2
的提示。如果未定義,prompt
將在兩個文字編碼器中使用。 - image (
PIL.Image.Image
) — 要進行修復的Image
或表示影像批次的張量,即影像的某些部分將透過mask_image
遮罩並根據prompt
重新繪製。 - mask_image (
PIL.Image.Image
) —Image
或表示影像批次的張量,用於遮罩image
。遮罩中的白色畫素將被重新繪製,而黑色畫素將保留。如果mask_image
是 PIL 影像,它在使用前將轉換為單通道(亮度)。如果它是張量,它應該包含一個顏色通道 (L) 而不是 3 個,因此預期形狀為(B, H, W, 1)
。 - height (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。 - width (
int
, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。 - padding_mask_crop (
int
, optional, defaults toNone
) — 應用於影像和遮罩的裁剪邊緣大小。如果為None
,則不對影像和mask_image
應用裁剪。如果padding_mask_crop
不為None
,它將首先找到一個與影像長寬比相同且包含所有遮罩區域的矩形區域,然後根據padding_mask_crop
擴充套件該區域。然後將根據擴充套件區域裁剪影像和mask_image
,然後調整大小以適應原始影像大小進行修復。當遮罩區域很小而影像很大且包含與修復無關的資訊(例如背景)時,這很有用。 - strength (
float
, 可選, 預設為 0.9999) — 概念上,表示對參考image
中被遮罩部分進行轉換的程度。必須在 0 到 1 之間。image
將用作起點,strength
越大,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲將達到最大值,去噪過程將執行num_inference_steps
中指定的全部迭代次數。因此,值為 1 實際上會忽略參考image
中被遮罩的部分。請注意,如果denoising_start
被宣告為整數,則strength
的值將被忽略。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會導致更高質量的影像,但推理速度會變慢。 - denoising_start (
float
, 可選) — 指定時,表示在去噪過程開始之前要繞過的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,去噪過程的初始部分將被跳過,並且假定傳入的image
是部分去噪的影像。請注意,指定此引數時,strength 將被忽略。denoising_start
引數特別適用於將此管道整合到“去噪器混合”多管道設定中,詳細資訊請參見精煉影像輸出。 - denoising_end (
float
, 可選) — 指定時,確定在有意提前終止去噪過程之前要完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。結果,返回的樣本仍將保留大量的噪聲(大約需要排程器最後 20% 的時間步),並且應由denoising_start
設定為 0.8 的後續管道進行去噪,以便它只去噪排程器最後 20% 的時間步。當此管道作為“去噪器混合”多管道設定的一部分時,應理想地使用 denoising_end 引數,詳細資訊請參見精煉影像輸出。 - guidance_scale (
float
, 可選, 預設為 7.5) — 分類器自由擴散引導中定義的引導比例。Classifier-Free Diffusion Guidance。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),此引數將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 要傳送給tokenizer_2
和text_encoder_2
的不用於引導影像生成的提示詞。如果未定義,則在兩個文字編碼器中都使用negative_prompt
。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負向提示詞嵌入將根據negative_prompt
輸入引數生成。 - 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
輸入引數計算嵌入。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據prompt
輸入引數生成池化文字嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負向池化提示詞嵌入將根據negative_prompt
輸入引數生成。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
, 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。 - latents (
torch.Tensor
, 可選) — 預生成的帶噪聲潛變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機generator
取樣生成一個潛變數張量。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為self.processor
中定義的AttentionProcessor
的引數傳入 diffusers.models.attention_processor。 - original_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 如果original_size
與target_size
不相同,影像將顯示為下采樣或上取樣。如果未指定,original_size
預設為(width, height)
。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
應設定為生成影像所需的寬度和高度。如果未指定,它將預設為(width, height)
。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 節所述。可用於透過影響負向文字條件來模擬生成影像的美學分數。 - clip_skip (
int
, 可選) — 在計算提示詞嵌入時要跳過 CLIP 的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可選) — 在推理過程中每次去噪步驟結束時呼叫的函式或PipelineCallback
或MultiPipelineCallbacks
的子類,具有以下引數: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
屬性中列出的變數。
返回
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
或 tuple
如果 return_dict
為 True,則為 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
,否則為 tuple
。返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> from PIL import 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((1024, 1024))
>>> 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((1024, 1024))
>>> 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(
... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> 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]
encode_prompt
< 原始檔 >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示詞 - prompt_2 (
str
或List[str]
, 可選) — 要傳送給tokenizer_2
和text_encoder_2
的提示詞。如果未定義,則在兩個文字編碼器中都使用prompt
。 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示詞應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),此引數將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 要傳送給tokenizer_2
和text_encoder_2
的不用於引導影像生成的提示詞。如果未定義,則在兩個文字編碼器中都使用negative_prompt
。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負向文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負向提示詞嵌入將根據negative_prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將根據prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負向池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負向池化提示詞嵌入將根據negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 一個 LoRA 比例,如果載入了 LoRA 層,它將應用於文字編碼器的所有 LoRA 層。 - clip_skip (
int
, 可選) — 在計算提示詞嵌入時要跳過 CLIP 的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
將提示編碼為文字編碼器隱藏狀態。
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]] )
Stable Diffusion 管道的輸出類。