Diffusers documentation

Flux.1 的 ControlNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Flux.1 的 ControlNet

LoRA

FluxControlNetPipeline 是 Flux.1 的 ControlNet 实现。

ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 中提出。

使用 ControlNet 模型,您可以提供一张额外的控制图像,以调节并控制 Stable Diffusion 的生成过程。例如,如果您提供一张深度图,ControlNet 模型将生成一张保留深度图中空间信息的图像。这是一种更灵活、更精确地控制图像生成过程的方式。

该论文的摘要如下:

我们提出了 ControlNet,一种用于为大型预训练文本到图像扩散模型添加空间条件控制的神经网络架构。ControlNet 锁定生产就绪的大型扩散模型,并复用其使用数十亿张图像预训练得到的深层且鲁棒的编码层作为强大的骨干网络,以学习多样化的条件控制。该神经架构通过“零卷积”(零初始化的卷积层)进行连接,这些层使参数从零开始逐步增长,并确保在微调过程中不会产生有害噪声。我们使用 Stable Diffusion 测试了多种条件控制,例如边缘、深度、分割、人体姿态等,支持使用单一或多个条件,以及有或无提示词的情况。我们展示了 ControlNet 的训练在小规模(<50k)和大规模(>1m)数据集上均具有鲁棒性。大量结果表明,ControlNet 有助于将图像扩散模型的应用扩展到更广泛的领域。

This controlnet code is implemented by The InstantX Team. You can find pre-trained checkpoints for Flux-ControlNet in the table below:

ControlNet 类型开发者链接
CannyInstantX 团队链接
深度InstantX 团队链接
UnionInstantX 团队链接

XLabs ControlNets 也得到支持,由 XLabs 团队 贡献。

ControlNet 类型开发者链接
CannyXLabs 团队链接
深度XLabs 团队链接
HEDXLabs 团队链接

请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

FluxControlNetPipeline

class diffusers.FluxControlNetPipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelcontrolnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )

参数

  • transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于与 transformer 配合,对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
  • text_encoder (CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。
  • text_encoder_2 (T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2(T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。

用于文本到图像生成的 Flux 流水线。

参考:https://blackforestlabs.ai/announcing-black-forest-labs/

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_mode: int | list[int] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,将使用 prompt。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时会被忽略(即当 true_cfg_scale 不大于 1 时会被忽略)。
  • negative_prompt_2 (str 或 list[str],可选) — 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则所有文本编码器都会使用 negative_prompt。
  • true_cfg_scale(float,可选,默认值为 1.0)— 当 true_cfg_scale > 1 且提供了 negative_prompt 时,将启用真正的无分类器引导(guidance scale)。
  • height (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • sigmas (list[float],可选) — 用于在支持 sigmas 参数的调度器的 set_timesteps 方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • control_guidance_start(float 或 list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。
  • control_guidance_end (float 或 list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。
  • 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]]): 用于为 unet 的生成过程提供引导的 ControlNet 输入条件。如果类型指定为 torch.Tensor,则会原样传递给 ControlNet。也可以接受 PIL.Image.Image 作为图像。输出图像的默认尺寸与 image 的尺寸相同。如果传入了高度和/或宽度,image 将相应地调整大小。如果在 init 中指定了多个 ControlNet,则必须以列表形式传入图像,以便列表中的每个元素都能被正确批处理,作为单个 ControlNet 的输入。
  • controlnet_conditioning_scale (float 或 list[float],可选,默认值为 1.0) — ControlNet 的输出在加到原始 unet 的残差之前,会先乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,可以将对应的缩放系数设置为列表。
  • control_mode (int 或 list[int],可选,默认为 None) — 应用 ControlNet-Union 时的控制模式。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果未提供,则从 ip_adapter_image 输入参数计算嵌入。
  • negative_ip_adapter_image — (PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。
  • negative_ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果未提供,则从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • callback_on_step_end (Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用: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 属性中列出的变量。
  • max_sequence_length(int,默认为 512)— 与 prompt 配合使用的最大序列长度。

返回值

~pipelines.flux.FluxPipelineOutput 或 tuple

~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例:

>>> 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")

encode_prompt

< >

( prompt: str | list[str]prompt_2: str | list[str] | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonemax_sequence_length: int = 512lora_scale: float | None = 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) — 每个提示词应生成的图像数量
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

FluxPipelineOutput

class diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

参数

  • images (list[PIL.Image.Image] 或 torch.Tensor 或 np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 numpy 数组或 torch 张量。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。Torch 张量可以表示去噪后的图像,也可以表示准备传递给解码器的中间潜变量。

Flux 图像生成流水线的输出类。

Update on GitHub