Diffusers 文件

ControlNet-XS

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

ControlNet-XS

LoRA

ControlNet-XS 由 Denis Zavadski 和 Carsten Rother 在 ControlNet-XS 中引入。它的基礎觀察是,原始 ControlNet 中的控制模型可以做得更小,並且仍然能產生良好的結果。

與原始 ControlNet 模型一樣,您可以提供額外的控制影像來條件化和控制 Stable Diffusion 生成。例如,如果您提供深度圖,ControlNet 模型會生成一張影像,該影像將保留深度圖中的空間資訊。這是一種更靈活、更準確的影像生成控制方式。

ControlNet-XS 生成的影像質量與常規 ControlNet 相當,但速度快 20-25%(使用 StableDiffusion-XL 請參見基準測試),並且記憶體使用量減少約 45%。

以下是來自專案頁面的概述:

隨著計算能力的不斷增強,當前的模型架構似乎遵循著簡單地擴大所有元件而不驗證其必要性的趨勢。在這個專案中,我們研究了 ControlNet [Zhang 等,2023] 在控制基於 Stable Diffusion 的影像生成過程中的大小和架構設計。我們表明,一個引數量僅為基礎模型 1% 的新架構可以實現最先進的結果,在 FID 分數方面顯著優於 ControlNet。因此,我們將其命名為 ControlNet-XS。我們提供了控制 StableDiffusion-XL [Podell 等,2023](模型 B,48M 引數)和 StableDiffusion 2.1 [Rombach 等,2022](模型 B,14M 引數)的程式碼,所有這些程式碼均在 OpenRail 許可證下發布。

該模型由 UmerHA 貢獻。❤️

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

StableDiffusionControlNetXSPipeline

class diffusers.StableDiffusionControlNetXSPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.controlnets.controlnet_xs.UNetControlNetXSModel] controlnet: ControlNetXSAdapter scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )

引數

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

使用帶有 ControlNet-XS 引導的 Stable Diffusion 進行文字到影像生成的流水線。

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

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None 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 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 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'] ) 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 的尺寸相同。如果傳遞了 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) — 生成影像的寬度(畫素)。
  • 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
  • output_type (str, 可選,預設為 "pil") — 生成影像的輸出格式。在 PIL.Imagenp.array 之間選擇。
  • return_dict (bool, 可選,預設為 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。
  • cross_attention_kwargs (dict, optional) — 一個 kwargs 字典,如果指定,則作為引數傳遞給 self.processor 中定義的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 1.0) — ControlNet 的輸出乘以 controlnet_conditioning_scale 後新增到原始 unet 中的殘差。如果在 init 中指定了多個 ControlNet,您可以將相應的比例設定為列表。
  • 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) 的 bool 列表。

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

示例

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetXSPipeline, ControlNetXSAdapter
>>> 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

>>> controlnet = ControlNetXSAdapter.from_pretrained(
...     "UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1-base", 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 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 管道的輸出類。

< > 在 GitHub 上更新

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