Buckets:
ControlNet with Flux.1
FluxControlNetPipeline is an implementation of ControlNet for Flux.1.
ControlNet was introduced in Adding Conditional Control to Text-to-Image Diffusion Models by Lvmin Zhang, Anyi Rao, and Maneesh Agrawala.
With a 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.
The abstract from the paper is:
We present ControlNet, a neural network architecture to add spatial conditioning controls to large, pretrained text-to-image diffusion models. ControlNet locks the production-ready large diffusion models, and reuses their deep and robust encoding layers pretrained with billions of images as a strong backbone to learn a diverse set of conditional controls. The neural architecture is connected with "zero convolutions" (zero-initialized convolution layers) that progressively grow the parameters from zero and ensure that no harmful noise could affect the finetuning. We test various conditioning controls, eg, edges, depth, segmentation, human pose, etc, with Stable Diffusion, using single or multiple conditions, with or without prompts. We show that the training of ControlNets is robust with small (1m) datasets. Extensive results show that ControlNet may facilitate wider applications to control image diffusion models.
This controlnet code is implemented by The InstantX Team. You can find pre-trained checkpoints for Flux-ControlNet in the table below:
| ControlNet type | Developer | Link |
|---|---|---|
| Canny | The InstantX Team | Link |
| Depth | The InstantX Team | Link |
| Union | The InstantX Team | Link |
XLabs ControlNets are also supported, which was contributed by the XLabs team.
| ControlNet type | Developer | Link |
|---|---|---|
| Canny | The XLabs Team | Link |
| Depth | The XLabs Team | Link |
| HED | The XLabs Team | Link |
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.
FluxControlNetPipeline[[diffusers.FluxControlNetPipeline]]
diffusers.FluxControlNetPipeline[[diffusers.FluxControlNetPipeline]]
The Flux pipeline for text-to-image generation.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
__call__diffusers.FluxControlNetPipeline.__call__https://github.com/huggingface/diffusers/blob/vr_12249/src/diffusers/pipelines/flux/pipeline_flux_controlnet.py#L677[{"name": "prompt", "val": ": typing.Union[str, typing.List[str]] = None"}, {"name": "prompt_2", "val": ": typing.Union[str, typing.List[str], NoneType] = None"}, {"name": "negative_prompt", "val": ": typing.Union[str, typing.List[str]] = None"}, {"name": "negative_prompt_2", "val": ": typing.Union[str, typing.List[str], NoneType] = None"}, {"name": "true_cfg_scale", "val": ": float = 1.0"}, {"name": "height", "val": ": typing.Optional[int] = None"}, {"name": "width", "val": ": typing.Optional[int] = None"}, {"name": "num_inference_steps", "val": ": int = 28"}, {"name": "sigmas", "val": ": typing.Optional[typing.List[float]] = None"}, {"name": "guidance_scale", "val": ": float = 7.0"}, {"name": "control_guidance_start", "val": ": typing.Union[float, typing.List[float]] = 0.0"}, {"name": "control_guidance_end", "val": ": typing.Union[float, typing.List[float]] = 1.0"}, {"name": "control_image", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None"}, {"name": "control_mode", "val": ": typing.Union[int, typing.List[int], NoneType] = None"}, {"name": "controlnet_conditioning_scale", "val": ": typing.Union[float, typing.List[float]] = 1.0"}, {"name": "num_images_per_prompt", "val": ": typing.Optional[int] = 1"}, {"name": "generator", "val": ": typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None"}, {"name": "latents", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "prompt_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "pooled_prompt_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "ip_adapter_image", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None"}, {"name": "ip_adapter_image_embeds", "val": ": typing.Optional[typing.List[torch.Tensor]] = None"}, {"name": "negative_ip_adapter_image", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None"}, {"name": "negative_ip_adapter_image_embeds", "val": ": typing.Optional[typing.List[torch.Tensor]] = None"}, {"name": "negative_prompt_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "negative_pooled_prompt_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "output_type", "val": ": typing.Optional[str] = 'pil'"}, {"name": "return_dict", "val": ": bool = True"}, {"name": "joint_attention_kwargs", "val": ": typing.Optional[typing.Dict[str, typing.Any]] = None"}, {"name": "callback_on_step_end", "val": ": typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None"}, {"name": "callback_on_step_end_tensor_inputs", "val": ": typing.List[str] = ['latents']"}, {"name": "max_sequence_length", "val": ": int = 512"}]- prompt (str or List[str], optional) --
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead.
- prompt_2 (
strorList[str], optional) -- The prompt or prompts to be sent totokenizer_2andtext_encoder_2. If not defined,promptis will be used instead - height (
int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) -- The height in pixels of the generated image. This is set to 1024 by default for the best results. - width (
int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) -- The width in pixels of the generated image. This is set to 1024 by default for the best results. - 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. - sigmas (
List[float], optional) -- Custom sigmas to use for the denoising process with schedulers which support asigmasargument in theirset_timestepsmethod. If not defined, the default behavior whennum_inference_stepsis passed will be used. - guidance_scale (
float, optional, defaults to 7.0) -- Guidance scale as defined in Classifier-Free Diffusion Guidance.guidance_scaleis defined aswof equation 2. of Imagen Paper. Guidance scale is enabled by settingguidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the textprompt, usually at the expense of lower image quality. - control_guidance_start (
floatorList[float], optional, defaults to 0.0) -- The percentage of total steps at which the ControlNet starts applying. - control_guidance_end (
floatorList[float], optional, defaults to 1.0) -- The percentage of total steps at which the ControlNet stops applying. - 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]]orList[List[PIL.Image.Image]]): The ControlNet input condition to provide guidance to theunetfor generation. If the type is specified astorch.Tensor, it is passed to ControlNet as is.PIL.Image.Imagecan also be accepted as an image. The dimensions of the output image defaults toimage's dimensions. If height and/or width are passed,imageis resized accordingly. If multiple ControlNets are specified ininit, images must be passed as a list such that each element of the list can be correctly batched for input to a single ControlNet. - controlnet_conditioning_scale (
floatorList[float], optional, defaults to 1.0) -- The outputs of the ControlNet are multiplied bycontrolnet_conditioning_scalebefore they are added to the residual in the originalunet. If multiple ControlNets are specified ininit, you can set the corresponding scale as a list. - control_mode (
intorList[int],, optional, defaults to None) -- The control mode when applying ControlNet-Union. - num_images_per_prompt (
int, optional, defaults to 1) -- The number of images to generate per prompt. - generator (
torch.GeneratororList[torch.Generator], optional) -- One or a list of torch generator(s) to make generation deterministic. - latents (
torch.FloatTensor, optional) -- Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will be generated by sampling using the supplied randomgenerator. - prompt_embeds (
torch.FloatTensor, 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 frompromptinput argument. - pooled_prompt_embeds (
torch.FloatTensor, 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 frompromptinput argument. - ip_adapter_image -- (
PipelineImageInput, optional): Optional image input to work with IP Adapters. - ip_adapter_image_embeds (
List[torch.Tensor], optional) -- Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters. Each element should be a tensor of shape(batch_size, num_images, emb_dim). If not provided, embeddings are computed from theip_adapter_imageinput argument. - negative_ip_adapter_image --
(
PipelineImageInput, optional): Optional image input to work with IP Adapters. - negative_ip_adapter_image_embeds (
List[torch.Tensor], optional) -- Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters. Each element should be a tensor of shape(batch_size, num_images, emb_dim). If not provided, embeddings are computed from theip_adapter_imageinput argument. - output_type (
str, optional, defaults to"pil") -- The output format of the generate image. Choose between PIL:PIL.Image.Imageornp.array. - return_dict (
bool, optional, defaults toTrue) -- Whether or not to return a~pipelines.flux.FluxPipelineOutputinstead of a plain tuple. - joint_attention_kwargs (
dict, optional) -- A kwargs dictionary that if specified is passed along to theAttentionProcessoras defined underself.processorin diffusers.models.attention_processor. - callback_on_step_end (
Callable, optional) -- A function that calls at the end of each denoising steps during the inference. The function is called with the following arguments:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargswill include a list of all tensors as specified bycallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
List, optional) -- The list of tensor inputs for thecallback_on_step_endfunction. The tensors specified in the list will be passed ascallback_kwargsargument. You will only be able to include variables listed in the._callback_tensor_inputsattribute of your pipeline class. - max_sequence_length (
intdefaults to 512) -- Maximum sequence length to use with theprompt.0~pipelines.flux.FluxPipelineOutputortuple``~pipelines.flux.FluxPipelineOutputifreturn_dictis True, otherwise atuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers.utils import load_image
>>> from diffusers import FluxControlNetPipeline
>>> from diffusers import FluxControlNetModel
>>> base_model = "black-forest-labs/FLUX.1-dev"
>>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny"
>>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
>>> pipe = FluxControlNetPipeline.from_pretrained(
... base_model, controlnet=controlnet, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
>>> prompt = "A girl in city, 25 years old, cool, futuristic"
>>> image = pipe(
... prompt,
... control_image=control_image,
... control_guidance_start=0.2,
... control_guidance_end=0.8,
... controlnet_conditioning_scale=1.0,
... num_inference_steps=28,
... guidance_scale=3.5,
... ).images[0]
>>> image.save("flux.png")
Parameters:
transformer (FluxTransformer2DModel) : Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
scheduler (FlowMatchEulerDiscreteScheduler) : A scheduler to be used in combination with transformer to denoise the encoded image latents.
vae (AutoencoderKL) : Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
text_encoder (CLIPTextModel) : CLIP, specifically the clip-vit-large-patch14 variant.
text_encoder_2 (T5EncoderModel) : T5, specifically the google/t5-v1_1-xxl variant.
tokenizer (CLIPTokenizer) : Tokenizer of class CLIPTokenizer.
tokenizer_2 (T5TokenizerFast) : Second Tokenizer of class T5TokenizerFast.
Returns:
~pipelines.flux.FluxPipelineOutput` or `tuple
~pipelines.flux.FluxPipelineOutput if return_dict
is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated
images.
encode_prompt[[diffusers.FluxControlNetPipeline.encode_prompt]]
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 all text-encoders
device : (torch.device): torch device
num_images_per_prompt (int) : number of images that should be generated per prompt
prompt_embeds (torch.FloatTensor, 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.
pooled_prompt_embeds (torch.FloatTensor, 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.
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.
lora_scale (float, optional) : A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]
diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]
Output class for Flux image generation pipelines.
Parameters:
images (List[PIL.Image.Image] or torch.Tensor or np.ndarray) : List of denoised PIL images of length batch_size or numpy array or torch tensor of shape (batch_size, height, width, num_channels). PIL images or numpy array present the denoised images of the diffusion pipeline. Torch tensors can represent either the denoised images or the intermediate latents ready to be passed to the decoder.
Xet Storage Details
- Size:
- 18.8 kB
- Xet hash:
- 590b86317f3ff58e41ba07dc013f3376c951d9c9f73206ad84ef406e03ad9b47
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.