Diffusers 文档

ControlNet 与 Flux.1

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始入门

ControlNet 与 Flux.1

FluxControlNetPipeline 是 ControlNet 为 Flux.1 的一个实现。

ControlNet 在 Adding Conditional Control to Text-to-Image Diffusion Models 这篇论文中被介绍,作者是 Lvmin Zhang, Anyi Rao, 和 Maneesh Agrawala。

通过 ControlNet 模型,你可以提供额外的控制图像来调节和控制 Stable Diffusion 的生成。例如,如果你提供一个深度图,ControlNet 模型会生成一个保留深度图空间信息的图像。这是一种更灵活和精确的方式来控制图像生成过程。

论文的摘要如下:

我们提出了 ControlNet,一种神经网络架构,用于向大型预训练的文本到图像扩散模型添加空间条件控制。ControlNet 锁定了生产就绪的大型扩散模型,并重用其使用数十亿图像进行预训练的深度和鲁棒的编码层,作为学习各种条件控制的强大骨干。该神经网络架构与“零卷积”(零初始化的卷积层)相连,这些卷积层逐渐从零开始增加参数,并确保没有有害噪声会影响微调。我们使用 Stable Diffusion 测试了各种条件控制,例如,边缘、深度、分割、人体姿势等,使用单条件或多条件,有或没有 prompts。我们表明,ControlNets 的训练对于小型(<50k)和大型(>1m)数据集都是稳健的。广泛的结果表明,ControlNet 可以促进更广泛的应用以控制图像扩散模型。

此 controlnet 代码由 The InstantX Team 实现。你可以在下表中找到 Flux-ControlNet 的预训练 checkpoints

ControlNet 类型 开发者 链接
Canny The InstantX Team 链接
Depth The InstantX Team 链接
Union The InstantX Team 链接

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

ControlNet 类型 开发者 链接
Canny The XLabs Team 链接
Depth The XLabs Team 链接
HED The XLabs Team 链接

请务必查看 Schedulers 指南,了解如何探索 scheduler 速度和质量之间的权衡,并查看 跨 pipelines 重用组件 部分,了解如何有效地将相同的组件加载到多个 pipelines 中。

FluxControlNetPipeline

class diffusers.FluxControlNetPipeline

< >

( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel controlnet: typing.Union[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel, typing.List[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel] )

参数

  • 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 类的第二个分词器。

用于文本到图像生成的 Flux 管道。

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

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 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 control_mode: typing.Union[int, typing.List[int], NoneType] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_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 = 512 ) ~pipelines.flux.FluxPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传入 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则将使用 prompt 代替。
  • 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], 可选) — 用于支持在其 set_timesteps 方法中使用 sigmas 参数的调度器的去噪过程的自定义 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 (floatList[float], 可选, 默认为 0.0) — ControlNet 开始应用的步骤总数的百分比。
  • control_guidance_end (floatList[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]]): ControlNet 输入条件,为 unet 的生成提供引导。如果类型指定为 torch.Tensor,则按原样传递给 ControlNet。 PIL.Image.Image 也可以接受为图像。输出图像的尺寸默认为 image 的尺寸。如果传递了高度和/或宽度,则会相应地调整 image 的大小。如果在 init 中指定了多个 ControlNet,则必须将图像作为列表传递,以便列表的每个元素都可以正确批处理,以输入到单个 ControlNet。
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,会乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,则可以将相应的比例设置为列表。
  • control_mode (intList[int],, 可选, 默认为 None) — 应用 ControlNet-Union 时的控制模式。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成确定性的一个或多个 torch 生成器
  • latents (torch.FloatTensor, optional) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,将通过使用提供的随机 generator 采样来生成潜在变量张量。
  • prompt_embeds (torch.FloatTensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • 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 参数传递。你将只能包含在你的 pipeline 类的 ._callback_tensor_inputs 属性中列出的变量。
  • max_sequence_length (int defaults to 512) — 与 prompt 一起使用的最大序列长度。

返回

~pipelines.flux.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers.utils import load_image
>>> from diffusers import FluxControlNetPipeline
>>> from diffusers import FluxControlNetModel

>>> 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )

参数

  • prompt (str or List[str], optional) — 要编码的提示词
  • prompt_2 (str or List[str], optional) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则在所有文本编码器中使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • prompt_embeds (torch.FloatTensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • clip_skip (int, optional) — 从 CLIP 跳过的层数,用于计算提示词嵌入。值为 1 表示将使用预倒数第二层的输出计算提示词嵌入。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 lora 缩放比例。

FluxPipelineOutput

class diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput

< >

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

参数

  • images (List[PIL.Image.Image] or np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 numpy 数组。 PIL 图像或 numpy 数组表示扩散 pipeline 的去噪图像。

Stable Diffusion pipeline 的输出类。

< > 在 GitHub 上更新