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 測試了各種條件控制,例如邊緣、深度、分割、人體姿態等,可以使用單個或多個條件,帶或不帶提示詞。我們表明 ControlNet 的訓練在小型(<50k)和大型(>1m)資料集上都具有魯棒性。廣泛的結果表明 ControlNet 可能促進更廣泛的應用,以控制影像擴散模型。

此流水線由 ishan24 貢獻。❤️ 原始程式碼庫可以在 NVlabs/Sana 找到,您可以在 Efficient-Large-Model 的 Hub 配置檔案中找到官方 ControlNet 檢查點。

SanaControlNetPipeline

class diffusers.SanaControlNetPipeline

< >

( tokenizer: typing.Union[transformers.models.gemma.tokenization_gemma.GemmaTokenizer, transformers.models.gemma.tokenization_gemma_fast.GemmaTokenizerFast] text_encoder: Gemma2PreTrainedModel vae: AutoencoderDC transformer: SanaTransformer2DModel controlnet: SanaControlNetModel scheduler: DPMSolverMultistepScheduler )

使用 Sana 進行文字到影像生成的流水線。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 height: int = 1024 width: int = 1024 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 prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True clean_caption: bool = False use_resolution_binning: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 300 complex_human_instruction: typing.List[str] = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) SanaPipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳入 prompt_embeds
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1 時),此引數將被忽略。
  • num_inference_steps (int, 可選, 預設為 20) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 自定義時間步長,用於支援 timesteps 引數的排程器的去噪過程。如果未定義,將使用傳入 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 自定義 sigmas,用於支援 sigmas 引數的排程器的去噪過程。如果未定義,將使用傳入 num_inference_steps 時的預設行為。
  • guidance_scale (float, 可選, 預設為 4.5) — 如 Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale 定義為 Imagen Paper 方程 2 中的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例鼓勵生成與文字 prompt 緊密相關的影像,通常以犧牲影像質量為代價。
  • 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。
  • controlnet_conditioning_scale (floatList[float], 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始 unet 中的殘差之前,將乘以 controlnet_conditioning_scale。如果在 init 中指定了多個 ControlNet,則可以以列表形式設定相應的比例。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞生成的影像數量。
  • height (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的高度(畫素)。
  • width (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的寬度(畫素)。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文 https://huggingface.co/papers/2010.02502 中的引數 eta (η)。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成確定性。
  • latents (torch.Tensor, 可選) — 預先生成的噪聲潛在變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成一個潛在張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如 提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • prompt_attention_mask (torch.Tensor, 可選) — 文字嵌入的預生成注意力掩碼。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。對於 PixArt-Sigma,此負面提示應為 ""。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • negative_prompt_attention_mask (torch.Tensor, optional) — 為負文字嵌入預先生成的注意力掩碼。
  • output_type (str, optional, 預設為 "pil") — 生成影像的輸出格式。在 PIL: PIL.Image.Imagenp.array 之間選擇。
  • return_dict (bool, optional, 預設為 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元組。
  • attention_kwargs — 一個 kwargs 字典,如果指定,將作為引數傳遞給 diffusers.models.attention_processor 中定義的 self.processor 下的 AttentionProcessor
  • clean_caption (bool, optional, 預設為 True) — 在建立嵌入之前是否清理標題。需要安裝 beautifulsoup4ftfy。如果未安裝依賴項,則將從原始提示建立嵌入。
  • use_resolution_binning (bool 預設為 True) — 如果設定為 True,則請求的高度和寬度首先使用 ASPECT_RATIO_1024_BIN 對映到最接近的解析度。生成的潛在圖解碼為影像後,它們將調整回請求的解析度。適用於生成非方形影像。
  • callback_on_step_end (Callable, optional) — 在推理過程中,在每個去噪步驟結束時呼叫的函式。該函式以以下引數呼叫: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 屬性中列出的變數。
  • max_sequence_length (int 預設為 300) — 用於 prompt 的最大序列長度。
  • complex_human_instruction (List[str], optional) — 複雜人工指令:https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55

返回

SanaPipelineOutputtuple

如果 return_dictTrue,則返回 SanaPipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import SanaControlNetPipeline
>>> from diffusers.utils import load_image

>>> pipe = SanaControlNetPipeline.from_pretrained(
...     "ishan24/Sana_600M_1024px_ControlNetPlus_diffusers",
...     variant="fp16",
...     torch_dtype={"default": torch.bfloat16, "controlnet": torch.float16, "transformer": torch.float16},
...     device_map="balanced",
... )
>>> cond_image = load_image(
...     "https://huggingface.co/ishan24/Sana_600M_1024px_ControlNet_diffusers/resolve/main/hed_example.png"
... )
>>> prompt = 'a cat with a neon sign that says "Sana"'
>>> image = pipe(
...     prompt,
...     control_image=cond_image,
... ).images[0]
>>> image.save("output.png")

disable_vae_slicing

< >

( )

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

disable_vae_tiling

< >

( )

停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling,此方法將恢復一步計算解碼。

enable_vae_slicing

< >

( )

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

enable_vae_tiling

< >

( )

啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None clean_caption: bool = False max_sequence_length: int = 300 complex_human_instruction: typing.Optional[typing.List[str]] = None lora_scale: typing.Optional[float] = None )

引數

  • prompt (strList[str], optional) — 要編碼的提示
  • negative_prompt (strList[str], optional) — 不用於引導影像生成的提示。如果未定義,則必須傳遞 negative_prompt_embeds。在不使用引導時忽略(即,如果 guidance_scale 小於 1 則忽略)。對於 PixArt-Alpha,這應為空字串。
  • do_classifier_free_guidance (bool, optional, 預設為 True) — 是否使用無分類器引導
  • num_images_per_prompt (int, optional, 預設為 1) — 每個提示應生成的影像數量
  • device — (torch.device, optional): 放置結果嵌入的 torch 裝置
  • prompt_embeds (torch.Tensor, optional) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 預生成的負文字嵌入。對於 Sana,它應該是 "" 字串的嵌入。
  • clean_caption (bool, 預設為 False) — 如果為 True,函式將在編碼前預處理和清理提供的標題。
  • max_sequence_length (int, 預設為 300) — 用於提示的最大序列長度。
  • complex_human_instruction (list[str], 預設為 complex_human_instruction) — 如果 complex_human_instruction 不為空,函式將使用複雜的人工指令作為提示。

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

SanaPipelineOutput

class diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput

< >

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

引數

  • images (List[PIL.Image.Image]np.ndarray) — 長度為 batch_size 的去噪 PIL 影像列表或形狀為 (batch_size, height, width, num_channels) 的 numpy 陣列。PIL 影像或 numpy 陣列表示擴散管道的去噪影像。

Sana 管道的輸出類。

< > 在 GitHub 上更新

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