Buckets:

hf-doc-build/doc-dev / diffusers /pr_12652 /en /api /pipelines /controlnetxs_sdxl.md
rtrm's picture
|
download
raw
16.9 kB

ControlNet-XS with Stable Diffusion XL

ControlNet-XS was introduced in ControlNet-XS by Denis Zavadski and Carsten Rother. It is based on the observation that the control model in the original ControlNet can be made much smaller and still produce good results.

Like the original ControlNet model, you can provide an additional control image to condition and control Stable Diffusion generation. For example, if you provide a depth map, the ControlNet model generates an image that'll preserve the spatial information from the depth map. It is a more flexible and accurate way to control the image generation process.

ControlNet-XS generates images with comparable quality to a regular ControlNet, but it is 20-25% faster (see benchmark) and uses ~45% less memory.

Here's the overview from the project page:

With increasing computing capabilities, current model architectures appear to follow the trend of simply upscaling all components without validating the necessity for doing so. In this project we investigate the size and architectural design of ControlNet [Zhang et al., 2023] for controlling the image generation process with stable diffusion-based models. We show that a new architecture with as little as 1% of the parameters of the base model achieves state-of-the art results, considerably better than ControlNet in terms of FID score. Hence we call it ControlNet-XS. We provide the code for controlling StableDiffusion-XL [Podell et al., 2023] (Model B, 48M Parameters) and StableDiffusion 2.1 [Rombach et al. 2022] (Model B, 14M Parameters), all under openrail license.

This model was contributed by UmerHA. ❤️

🧪 Many of the SDXL ControlNet checkpoints are experimental, and there is a lot of room for improvement. Feel free to open an Issue and leave us feedback on how we can improve!

Make sure to check out the Schedulers guide to learn how to explore the tradeoff between scheduler speed and quality, and see the reuse components across pipelines section to learn how to efficiently load the same components into multiple pipelines.

StableDiffusionXLControlNetXSPipeline[[diffusers.StableDiffusionXLControlNetXSPipeline]]

diffusers.StableDiffusionXLControlNetXSPipeline[[diffusers.StableDiffusionXLControlNetXSPipeline]]

Source

Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet-XS guidance.

This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

The pipeline also inherits the following loading methods:

__call__diffusers.StableDiffusionXLControlNetXSPipeline.__call__https://github.com/huggingface/diffusers/blob/vr_12652/src/diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py#L717[{"name": "prompt", "val": ": str | list[str] = None"}, {"name": "prompt_2", "val": ": str | list[str] | None = None"}, {"name": "image", "val": ": PIL.Image.Image | numpy.ndarray | torch.Tensor | list[PIL.Image.Image] | list[numpy.ndarray] | list[torch.Tensor] = None"}, {"name": "height", "val": ": int | None = None"}, {"name": "width", "val": ": int | None = None"}, {"name": "num_inference_steps", "val": ": int = 50"}, {"name": "guidance_scale", "val": ": float = 5.0"}, {"name": "negative_prompt", "val": ": str | list[str] | None = None"}, {"name": "negative_prompt_2", "val": ": str | list[str] | None = None"}, {"name": "num_images_per_prompt", "val": ": int | None = 1"}, {"name": "eta", "val": ": float = 0.0"}, {"name": "generator", "val": ": torch._C.Generator | list[torch._C.Generator] | None = None"}, {"name": "latents", "val": ": torch.Tensor | None = None"}, {"name": "prompt_embeds", "val": ": torch.Tensor | None = None"}, {"name": "negative_prompt_embeds", "val": ": torch.Tensor | None = None"}, {"name": "pooled_prompt_embeds", "val": ": torch.Tensor | None = None"}, {"name": "negative_pooled_prompt_embeds", "val": ": torch.Tensor | None = None"}, {"name": "output_type", "val": ": str | None = 'pil'"}, {"name": "return_dict", "val": ": bool = True"}, {"name": "cross_attention_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "controlnet_conditioning_scale", "val": ": float | list[float] = 1.0"}, {"name": "control_guidance_start", "val": ": float = 0.0"}, {"name": "control_guidance_end", "val": ": float = 1.0"}, {"name": "original_size", "val": ": tuple = None"}, {"name": "crops_coords_top_left", "val": ": tuple = (0, 0)"}, {"name": "target_size", "val": ": tuple = None"}, {"name": "negative_original_size", "val": ": tuple[int, int] | None = None"}, {"name": "negative_crops_coords_top_left", "val": ": tuple = (0, 0)"}, {"name": "negative_target_size", "val": ": tuple[int, int] | None = None"}, {"name": "clip_skip", "val": ": int | None = None"}, {"name": "callback_on_step_end", "val": ": typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None"}, {"name": "callback_on_step_end_tensor_inputs", "val": ": list = ['latents']"}]- prompt (str or list[str], optional) -- The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds.

  • prompt_2 (str or list[str], optional) -- The prompt or prompts to be sent to tokenizer_2 and text_encoder_2. If not defined, prompt is used in both text-encoders.
  • 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]] or list[list[PIL.Image.Image]]): The ControlNet input condition to provide guidance to the unet for generation. If the type is specified as torch.Tensor, it is passed to ControlNet as is. PIL.Image.Image can also be accepted as an image. The dimensions of the output image defaults to image's dimensions. If height and/or width are passed, image is resized accordingly. If multiple ControlNets are specified in init, images must be passed as a list such that each element of the list can be correctly batched for input to a single ControlNet.
  • height (int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) -- The height in pixels of the generated image. Anything below 512 pixels won't work well for stabilityai/stable-diffusion-xl-base-1.0 and checkpoints that are not specifically fine-tuned on low resolutions.
  • width (int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) -- The width in pixels of the generated image. Anything below 512 pixels won't work well for stabilityai/stable-diffusion-xl-base-1.0 and checkpoints that are not specifically fine-tuned on low resolutions.
  • num_inference_steps (int, optional, defaults to 50) -- The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
  • guidance_scale (float, optional, defaults to 5.0) -- A higher guidance scale value encourages the model to generate images closely linked to the text prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1.
  • negative_prompt (str or list[str], optional) -- The prompt or prompts to guide what to not include in image generation. If not defined, you need to pass negative_prompt_embeds instead. Ignored when not using guidance (guidance_scale 0pipelines.stable_diffusion.StableDiffusionXLPipelineOutputortupleIf return_dictisTrue, pipelines.stable_diffusion.StableDiffusionXLPipelineOutputis returned, otherwise atuple` is returned containing the output images.

The call function to the pipeline for generation.

Examples:

>>> # !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://hf.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]

Parameters:

vae (AutoencoderKL) : Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.

text_encoder (CLIPTextModel) : Frozen text-encoder (clip-vit-large-patch14).

text_encoder_2 (CLIPTextModelWithProjection) : Second frozen text-encoder (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k).

tokenizer (CLIPTokenizer) : A CLIPTokenizer to tokenize text.

tokenizer_2 (CLIPTokenizer) : A CLIPTokenizer to tokenize text.

unet (UNet2DConditionModel) : A UNet2DConditionModel used to create a UNetControlNetXSModel to denoise the encoded image latents.

controlnet (ControlNetXSAdapter) : A ControlNetXSAdapter to be used in combination with unet to denoise the encoded image latents.

scheduler (SchedulerMixin) : A scheduler to be used in combination with unet to denoise the encoded image latents. Can be one of DDIMScheduler, LMSDiscreteScheduler, or PNDMScheduler.

force_zeros_for_empty_prompt (bool, optional, defaults to "True") : Whether the negative prompt embeddings should always be set to 0. Also see the config of stabilityai/stable-diffusion-xl-base-1-0.

add_watermarker (bool, optional) : Whether to use the invisible_watermark library to watermark output images. If not defined, it defaults to True if the package is installed; otherwise no watermarker is used.

Returns:

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` or `tuple

If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput is returned, otherwise a tuple is returned containing the output images.

encode_prompt[[diffusers.StableDiffusionXLControlNetXSPipeline.encode_prompt]]

Source

Encodes the prompt into text encoder hidden states.

Parameters:

prompt (str or list[str], optional) : prompt to be encoded

prompt_2 (str or list[str], optional) : The prompt or prompts to be sent to the tokenizer_2 and text_encoder_2. If not defined, prompt is used in both text-encoders

device : (torch.device): torch device

num_images_per_prompt (int) : number of images that should be generated per prompt

do_classifier_free_guidance (bool) : whether to use classifier free guidance or not

negative_prompt (str or list[str], optional) : The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

negative_prompt_2 (str or list[str], optional) : The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and text_encoder_2. If not defined, negative_prompt is used in both text-encoders

prompt_embeds (torch.Tensor, optional) : Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

negative_prompt_embeds (torch.Tensor, optional) : Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

pooled_prompt_embeds (torch.Tensor, optional) : Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, pooled text embeddings will be generated from prompt input argument.

negative_pooled_prompt_embeds (torch.Tensor, optional) : Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt input argument.

lora_scale (float, optional) : A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.

clip_skip (int, optional) : Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings.

StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

Source

Output class for Stable Diffusion pipelines.

Parameters:

images (list[PIL.Image.Image] or np.ndarray) : list of denoised PIL images of length batch_size or NumPy array of shape (batch_size, height, width, num_channels).

nsfw_content_detected (list[bool]) : list indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or None if safety checking could not be performed.

Xet Storage Details

Size:
16.9 kB
·
Xet hash:
7fa58a7677fff9baef55e6ecf5ae664a06c7de47950303bb28b8cd795c46841c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.