Diffusers 文件
ControlNet-XS 與 Stable Diffusion XL
並獲得增強的文件體驗
開始使用
ControlNet-XS 與 Stable Diffusion XL
ControlNet-XS 由 Denis Zavadski 和 Carsten Rother 在ControlNet-XS中引入。它的核心思想是,原始 ControlNet中的控制模型可以大大縮小,同時仍然能產生良好的結果。
與原始 ControlNet 模型一樣,您可以提供額外的控制影像來條件化和控制 Stable Diffusion 的生成。例如,如果您提供一張深度圖,ControlNet 模型將生成一張保留深度圖中空間資訊的影像。這是一種更靈活、更準確的影像生成控制方式。
ControlNet-XS 生成的影像質量與常規 ControlNet 相當,但速度快 20-25%(參見基準測試),並且記憶體使用量減少約 45%。
以下是專案頁面的概述:
隨著計算能力的提高,當前的模型架構似乎遵循了簡單地擴大所有元件而不驗證其必要性的趨勢。在這個專案中,我們研究了 ControlNet [Zhang et al., 2023] 的大小和架構設計,以控制基於 Stable Diffusion 的影像生成過程。我們表明,一個引數量僅為基礎模型 1% 的新架構能夠實現最先進的結果,在 FID 分數方面明顯優於 ControlNet。因此,我們將其命名為 ControlNet-XS。我們提供了用於控制 StableDiffusion-XL [Podell et al., 2023] (模型 B,48M 引數) 和 StableDiffusion 2.1 [Rombach et al. 2022] (模型 B,14M 引數) 的程式碼,所有這些都遵循 openrail 許可證。
該模型由UmerHA貢獻。❤️
🧪 許多 SDXL ControlNet 檢查點仍處於實驗階段,還有很大的改進空間。歡迎開啟Issue並留下您的反饋,告訴我們如何改進!
StableDiffusionXLControlNetXSPipeline
class diffusers.StableDiffusionXLControlNetXSPipeline
< 原始碼 >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.controlnets.controlnet_xs.UNetControlNetXSModel] controlnet: ControlNetXSAdapter scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = 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) — 用於建立 UNetControlNetXSModel 以對編碼影像潛在進行去噪的 UNet2DConditionModel。
- controlnet (
ControlNetXSAdapter
) — 一個ControlNetXSAdapter
,與unet
結合使用,用於對編碼影像潛在進行去噪。 - 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
;否則不使用水印器。
使用 ControlNet-XS 指導的 Stable Diffusion XL 文字到影像生成管道。
該模型繼承自DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights() 用於載入 LoRA 權重
- loaders.FromSingleFileMixin.from_single_file() 用於載入
.ckpt
檔案
__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 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 output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 control_guidance_start: float = 0.0 control_guidance_end: 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'] ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
或 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
) — 生成影像的高度(畫素)。任何低於 512 畫素的影像對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點都不會很好地工作。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的寬度(畫素)。任何低於 512 畫素的影像對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點都不會很好地工作。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會產生更高質量的影像,但推理速度會變慢。 - 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
輸入引數生成合並的negative_prompt_embeds
。 - 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
。 - control_guidance_start (
float
, 可選,預設為 0.0) — ControlNet 開始應用的步數總百分比。 - control_guidance_end (
float
, 可選,預設為 1.0) — ControlNet 停止應用的步數總百分比。 - 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 節所述。 - 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
屬性中列出的變數。
返回
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
或 tuple
如果 return_dict
為 True
,則返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput
,否則返回包含輸出影像的 tuple
。
用於生成的管道的呼叫函式。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionXLControlNetXSPipeline, ControlNetXSAdapter, 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
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> controlnet = ControlNetXSAdapter.from_pretrained(
... "UmerHA/Testing-ConrolNetXS-SDXL-canny", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, 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
< 來源 >( 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
輸入引數生成 negative_prompt_embeds。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的合併文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從prompt
輸入引數生成合並文字嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負合併文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從negative_prompt
輸入引數生成合並的 negative_prompt_embeds。 - 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 管道的輸出類。