Diffusers documentation

FluxControlInpaint

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

and get access to the augmented documentation experience

to get started

FluxControlInpaint

LoRA

FluxControlInpaintPipeline 是 Flux.1 Depth/Canny 模型的 Inpainting 实现。它是一个允许您使用 Flux.1 Depth/Canny 模型对图像进行修复的流水线。该流水线接收图像和掩码作为输入,并返回修复后的图像。

FLUX.1 Depth and Canny [dev] 是一个拥有 120 亿参数的 rectified flow transformer,能够根据文本描述生成图像,同时遵循给定输入图像的结构。这不是一个 ControlNet 模型。

控制类型开发者链接
深度Black Forest Labs链接
CannyBlack Forest Labs链接

Flux 在消费级硬件设备上运行可能成本较高。不过,你可以执行一系列优化,使其运行得更快且更节省内存。有关更多详细信息,请参阅本节。此外,Flux 可以通过量化来提升内存效率,但代价是推理延迟会增加。要了解更多信息,请参阅这篇博客文章。如需完整的资源列表,请查看此 gist。

import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580,300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save("output.png")

FluxControlInpaintPipeline

class diffusers.FluxControlInpaintPipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModel )

参数

  • 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-dev-Depth/Canny 进行图像修复的 Flux 流水线。

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

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrol_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemasked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonestrength: float = 0.6num_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.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] = 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 = ['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。
  • image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image、numpy 数组或张量,表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量,预期的取值范围为 [0, 1]。如果是张量或张量列表,预期的形状应为 (B, C, H, W) 或 (C, H, W)。如果是 numpy 数组或数组列表,预期的形状应为 (B, H, W, C) 或 (H, W, C)。它也可以接受图像潜变量作为 image,但如果直接传入潜变量,则不会再次进行编码。
  • 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 的输入。
  • mask_image (torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image、numpy 数组或张量,表示要用于遮罩 image 的图像批次。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,则在使用前会将其转换为单通道(亮度)。如果它是 numpy 数组或 PyTorch 张量,则应包含一个颜色通道(L)而不是三个,因此 PyTorch 张量的预期形状为 (B, 1, H, W)、(B, H, W)、(1, H, W) 或 (H, W)。而 numpy 数组的预期形状为 (B, H, W, 1)、(B, H, W)、(H, W, 1) 或 (H, W)。
  • masked_image_latents (torch.Tensor, list[torch.Tensor]) — Tensor,表示用于对 VAE 生成的 image 进行掩码处理的图像批次。如果未提供,掩码潜变量张量将由 mask_image 生成。
  • height (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • width (int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。
  • strength (float, 可选,默认为 1.0) — 指示对参考 image 进行变换的程度。取值必须在 0 到 1 之间。image 用作起始点,strength 越高,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。值为 1 时,基本上会忽略 image。
  • 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 紧密关联的图像,但通常以牺牲图像质量为代价。
  • 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 输入参数生成池化文本嵌入。
  • 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 import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor  # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    torch_dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580, 300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save(
    "output.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