Diffusers 文档

FluxControlInpaint

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

FluxControlInpaint

LoRA

FluxControlInpaintPipeline 是 Flux.1 深度/边缘检测模型的图像修复实现。它是一个允许您使用 Flux.1 深度/边缘检测模型修复图像的流水线。该流水线接收图像和遮罩作为输入,并返回修复后的图像。

FLUX.1 深度和边缘检测 [开发中] 是一个 120 亿参数的修正流转换器,能够根据文本描述生成图像,同时遵循给定输入图像的结构。**这不是一个 ControlNet 模型**。

控制类型 开发者 链接
深度 Black Forest Labs 链接
边缘检测 Black 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",
    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")

FluxControlInpaintPipeline

class diffusers.FluxControlInpaintPipeline

< >

( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel )

参数

用于使用 Flux-dev-Depth/Canny 进行图像修复的 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 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_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.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
  • 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]]): ControlNet 输入条件,用于为 unet 的生成提供指导。如果类型指定为 torch.Tensor,则直接将其传递给 ControlNet。也可以接受 PIL.Image.Image 作为图像。输出图像的尺寸默认为 image 的尺寸。如果传递了 height 和/或 width,则 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) 而不是 3 个,因此 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)
  • mask_image_latent (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) — 无分类器扩散引导中定义的引导比例。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导比例。更高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲较低图像质量为代价。
  • num_images_per_prompt (int可选,默认为 1) — 每个提示生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator]可选) — 一个或多个 torch generator(s),用于使生成具有确定性。
  • latents (torch.FloatTensor可选) — 预生成的带噪潜在空间,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同生成。如果未提供,将使用提供的随机 generator 进行采样生成一个潜在空间张量。
  • prompt_embeds (torch.FloatTensor可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • output_type (str可选,默认为 "pil") — 生成图像的输出格式。选择 PIL: PIL.Image.Imagenp.array
  • return_dict (bool可选,默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 AttentionProcessor,定义在 diffusers.models.attention_processor 中的 self.processor 下。
  • 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.FluxPipelineOutputtuple

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

调用管道进行生成时调用的函数。

示例

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

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing,此方法将返回一步计算解码。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling,此方法将恢复一步计算解码。

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成瓦片,分多步计算编码和解码。这对于节省大量内存和处理更大的图像非常有用。

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 (strList[str], 可选) — 待编码的提示词
  • prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_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

diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput

< >

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

参数

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

Stable Diffusion 管道的输出类。

< > 在 GitHub 上更新