Diffusers 文档

Flux

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Flux

LoRA MPS

Flux 是一系列基于扩散变换器的文本到图像生成模型。要了解更多关于 Flux 的信息,请查看 Flux 的创建者 Black Forest Labs 发布的原始博客文章

Flux 的原始模型检查点可以在这里找到。原始推理代码可以在这里找到。

Flux 在消费级硬件设备上运行可能会非常昂贵。但是,您可以执行一系列优化,使其运行更快,并以更节省内存的方式运行。有关更多详细信息,请查看此部分。此外,Flux 可以受益于量化以提高内存效率,但会牺牲推理延迟。请参阅此博客文章了解更多信息。有关资源的详尽列表,请查看此要点

Flux 提供以下变体:

模型类型 模型 ID
时间步长蒸馏 black-forest-labs/FLUX.1-schnell
引导蒸馏 black-forest-labs/FLUX.1-dev
填充修复/外画(引导蒸馏) black-forest-labs/FLUX.1-Fill-dev
Canny 控制(引导蒸馏) black-forest-labs/FLUX.1-Canny-dev
深度控制(引导蒸馏) black-forest-labs/FLUX.1-Depth-dev
Canny 控制 (LoRA) black-forest-labs/FLUX.1-Canny-dev-lora
深度控制 (LoRA) black-forest-labs/FLUX.1-Depth-dev-lora
Redux(适配器) black-forest-labs/FLUX.1-Redux-dev

所有检查点都有不同的用法,我们将在下面详细介绍。

时间步长蒸馏

  • max_sequence_length 不能超过 256。
  • guidance_scale 需设置为 0。
  • 由于这是一个时间步长蒸馏模型,因此它受益于更少的采样步长。
import torch
from diffusers import FluxPipeline

pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()

prompt = "A cat holding a sign that says hello world"
out = pipe(
    prompt=prompt,
    guidance_scale=0.,
    height=768,
    width=1360,
    num_inference_steps=4,
    max_sequence_length=256,
).images[0]
out.save("image.png")

引导蒸馏

  • 引导蒸馏变体需要大约 50 个采样步骤才能生成高质量图像。
  • 它对 max_sequence_length 没有任何限制。
import torch
from diffusers import FluxPipeline

pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()

prompt = "a tiny astronaut hatching from an egg on the moon"
out = pipe(
    prompt=prompt,
    guidance_scale=3.5,
    height=768,
    width=1360,
    num_inference_steps=50,
).images[0]
out.save("image.png")

填充修复/外画

  • Flux Fill 管道不需要像常规图像修复管道那样将 strength 作为输入。
  • 它同时支持图像修复和外画。
import torch
from diffusers import FluxFillPipeline
from diffusers.utils import load_image

image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png")
mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png")

repo_id = "black-forest-labs/FLUX.1-Fill-dev"
pipe = FluxFillPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to("cuda")

image = pipe(
    prompt="a white paper cup",
    image=image,
    mask_image=mask,
    height=1632,
    width=1232,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0]
image.save(f"output.png")

Canny 控制

注意:black-forest-labs/Flux.1-Canny-dev 不是 ControlNetModel 模型。ControlNet 模型是 UNet/Transformer 的独立组件,其残差被添加到实际的基础模型中。Canny Control 是一种替代架构,通过使用通道级串联和输入控制条件,并确保 Transformer 尽可能紧密地遵循条件来学习结构控制,从而达到与 ControlNet 模型相同的效果。

# !pip install -U controlnet-aux
import torch
from controlnet_aux import CannyDetector
from diffusers import FluxControlPipeline
from diffusers.utils import load_image

pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16).to("cuda")

prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)

image = pipe(
    prompt=prompt,
    control_image=control_image,
    height=1024,
    width=1024,
    num_inference_steps=50,
    guidance_scale=30.0,
).images[0]
image.save("output.png")

Canny 控制也可以通过此条件的 LoRA 变体实现。用法如下:

# !pip install -U controlnet-aux
import torch
from controlnet_aux import CannyDetector
from diffusers import FluxControlPipeline
from diffusers.utils import load_image

pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Canny-dev-lora")

prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)

image = pipe(
    prompt=prompt,
    control_image=control_image,
    height=1024,
    width=1024,
    num_inference_steps=50,
    guidance_scale=30.0,
).images[0]
image.save("output.png")

深度控制

注意:black-forest-labs/Flux.1-Depth-dev 不是一个 ControlNet 模型。ControlNetModel 模型是 UNet/Transformer 的独立组件,其残差被添加到实际的基础模型中。深度控制是一种替代架构,通过使用通道级串联和输入控制条件,并确保 Transformer 尽可能紧密地遵循条件来学习结构控制,从而达到与 ControlNet 模型相同的效果。

# !pip install git+https://github.com/huggingface/image_gen_aux
import torch
from diffusers import FluxControlPipeline, FluxTransformer2DModel
from diffusers.utils import load_image
from image_gen_aux import DepthPreprocessor

pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Depth-dev", torch_dtype=torch.bfloat16).to("cuda")

prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

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

image = pipe(
    prompt=prompt,
    control_image=control_image,
    height=1024,
    width=1024,
    num_inference_steps=30,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")

深度控制也可以通过此条件的 LoRA 变体实现。用法如下:

# !pip install git+https://github.com/huggingface/image_gen_aux
import torch
from diffusers import FluxControlPipeline, FluxTransformer2DModel
from diffusers.utils import load_image
from image_gen_aux import DepthPreprocessor

pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora")

prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

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

image = pipe(
    prompt=prompt,
    control_image=control_image,
    height=1024,
    width=1024,
    num_inference_steps=30,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")

Redux

  • Flux Redux 管道是 FLUX.1 基础模型的适配器。它可以与 flux-dev 和 flux-schnell 一起用于图像到图像生成。
  • 您可以先使用 FluxPriorReduxPipeline 获取 prompt_embedspooled_prompt_embeds,然后将它们输入到 FluxPipeline 中进行图像到图像生成。
  • 当将 FluxPriorReduxPipeline 与基础管道一起使用时,您可以在基础管道中设置 text_encoder=Nonetext_encoder_2=None,以节省 VRAM。
import torch
from diffusers import FluxPriorReduxPipeline, FluxPipeline
from diffusers.utils import load_image
device = "cuda"
dtype = torch.bfloat16


repo_redux = "black-forest-labs/FLUX.1-Redux-dev"
repo_base = "black-forest-labs/FLUX.1-dev" 
pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(repo_redux, torch_dtype=dtype).to(device)
pipe = FluxPipeline.from_pretrained(
    repo_base, 
    text_encoder=None,
    text_encoder_2=None,
    torch_dtype=torch.bfloat16
).to(device)

image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png")
pipe_prior_output = pipe_prior_redux(image)
images = pipe(
    guidance_scale=2.5,
    num_inference_steps=50,
    generator=torch.Generator("cpu").manual_seed(0),
    **pipe_prior_output,
).images
images[0].save("flux-redux.png")

将 Flux Turbo LoRA 与 Flux Control、Fill 和 Redux 结合使用

我们可以将 Flux Turbo LoRA 与 Flux Control 和其他管道(如 Fill 和 Redux)结合使用,以实现少量步骤的推理。下面的示例展示了如何对深度和来自 ByteDance/Hyper-SD 的 Turbo LoRA 的 Flux Control LoRA 执行此操作。

from diffusers import FluxControlPipeline
from image_gen_aux import DepthPreprocessor
from diffusers.utils import load_image
from huggingface_hub import hf_hub_download
import torch

control_pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
control_pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora", adapter_name="depth")
control_pipe.load_lora_weights(
    hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"), adapter_name="hyper-sd"
)
control_pipe.set_adapters(["depth", "hyper-sd"], adapter_weights=[0.85, 0.125])
control_pipe.enable_model_cpu_offload()

prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

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

image = control_pipe(
    prompt=prompt,
    control_image=control_image,
    height=1024,
    width=1024,
    num_inference_steps=8,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")

使用 Flux LoRA 时关于 unload_lora_weights() 的注意事项

卸载 Control LoRA 权重时,请调用 pipe.unload_lora_weights(reset_to_overwritten_params=True) 以将 pipe.transformer 完全重置回其原始形式。然后可以将生成的管道与 DiffusionPipeline.from_pipe() 等方法一起使用。有关此参数的更多详细信息,请参阅 此 PR

IP-Adapter

请查看IP-Adapter以了解 IP-Adapter 的工作原理。

IP-Adapter 允许您除了文本提示外,还使用图像来提示 Flux。当描述仅通过文本难以表达的复杂概念,并且您有参考图像时,这尤其有用。

import torch
from diffusers import FluxPipeline
from diffusers.utils import load_image

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
).to("cuda")

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux_ip_adapter_input.jpg").resize((1024, 1024))

pipe.load_ip_adapter(
    "XLabs-AI/flux-ip-adapter",
    weight_name="ip_adapter.safetensors",
    image_encoder_pretrained_model_name_or_path="openai/clip-vit-large-patch14"
)
pipe.set_ip_adapter_scale(1.0)

image = pipe(
    width=1024,
    height=1024,
    prompt="wearing sunglasses",
    negative_prompt="",
    true_cfg_scale=4.0,
    generator=torch.Generator().manual_seed(4444),
    ip_adapter_image=image,
).images[0]

image.save('flux_ip_adapter_output.jpg')
带有提示“戴墨镜”的 IP-Adapter 示例

优化

Flux 是一个非常大的模型,加载所有模型组件需要大约 50GB 的 RAM/VRAM。启用以下一些优化以降低内存要求。

组卸载

组卸载 通过卸载内部层组而不是整个模型或权重来降低 VRAM 使用。您需要在管道的所有模型组件上使用 apply_group_offloading()offload_type 参数允许您在块级和叶级卸载之间切换。将其设置为 leaf_level 会将最低叶级参数卸载到 CPU,而不是在模块级别卸载。

在支持异步数据流的 CUDA 设备上,设置 use_stream=True 可重叠数据传输和计算以加速推理。

可以在管道的不同组件中混合使用块级和叶级卸载。

import torch
from diffusers import FluxPipeline
from diffusers.hooks import apply_group_offloading

model_id = "black-forest-labs/FLUX.1-dev"
dtype = torch.bfloat16
pipe = FluxPipeline.from_pretrained(
	model_id,
	torch_dtype=dtype,
)

apply_group_offloading(
    pipe.transformer,
    offload_type="leaf_level",
    offload_device=torch.device("cpu"),
    onload_device=torch.device("cuda"),
    use_stream=True,
)
apply_group_offloading(
    pipe.text_encoder, 
    offload_device=torch.device("cpu"),
    onload_device=torch.device("cuda"),
    offload_type="leaf_level",
    use_stream=True,
)
apply_group_offloading(
    pipe.text_encoder_2, 
    offload_device=torch.device("cpu"),
    onload_device=torch.device("cuda"),
    offload_type="leaf_level",
    use_stream=True,
)
apply_group_offloading(
    pipe.vae, 
    offload_device=torch.device("cpu"),
    onload_device=torch.device("cuda"),
    offload_type="leaf_level",
    use_stream=True,
)

prompt="A cat wearing sunglasses and working as a lifeguard at pool."

generator = torch.Generator().manual_seed(181201)
image = pipe(
    prompt,
    width=576,
    height=1024,
    num_inference_steps=30,
    generator=generator
).images[0]
image

运行 FP16 推理

Flux 可以使用 FP16(即加速 Turing/Volta GPU 上的推理)生成高质量图像,但与 FP32/BF16 相比,会产生不同的输出。问题在于文本编码器中的某些激活在 FP16 中运行时必须被剪裁,这会影响整体图像。因此,强制文本编码器使用 FP32 推理可以消除这种输出差异。有关详细信息,请参阅此处

FP16 推理代码

import torch
from diffusers import FluxPipeline

pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) # can replace schnell with dev
# to run on low vram GPUs (i.e. between 4 and 32 GB VRAM)
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

pipe.to(torch.float16) # casting here instead of in the pipeline constructor because doing so in the constructor loads all models into CPU memory at once

prompt = "A cat holding a sign that says hello world"
out = pipe(
    prompt=prompt,
    guidance_scale=0.,
    height=768,
    width=1360,
    num_inference_steps=4,
    max_sequence_length=256,
).images[0]
out.save("image.png")

量化

量化有助于通过以较低精度数据类型存储模型权重来减少大型模型的内存需求。但是,量化对视频质量的影响可能因视频模型而异。

请参阅量化概述,了解有关支持的量化后端以及选择适合您用例的量化后端的更多信息。以下示例演示了如何使用 bitsandbytes 加载量化的 FluxPipeline 进行推理。

import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    subfolder="text_encoder_2",
    quantization_config=quant_config,
    torch_dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = FluxTransformer2DModel.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    subfolder="transformer",
    quantization_config=quant_config,
    torch_dtype=torch.float16,
)

pipeline = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    text_encoder_2=text_encoder_8bit,
    transformer=transformer_8bit,
    torch_dtype=torch.float16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt, guidance_scale=3.5, height=768, width=1360, num_inference_steps=50).images[0]
image.save("flux.png")

FluxTransformer2DModel 的单一文件加载

FluxTransformer2DModel 支持加载 Black Forest Labs 提供的原始格式的检查点。当尝试加载社区发布的模型的微调或量化版本时,这也很有用。

根据您使用的 GPU 类型、CUDA 版本和 `torch` 版本,`FP8` 推理可能会不稳定。建议您使用 `optimum-quanto` 库在您的机器上运行 FP8 推理。

以下示例演示了如何使用小于 16GB 的 VRAM 运行 Flux。

首先安装 optimum-quanto

pip install optimum-quanto

然后运行以下示例

import torch
from diffusers import FluxTransformer2DModel, FluxPipeline
from transformers import T5EncoderModel, CLIPTextModel
from optimum.quanto import freeze, qfloat8, quantize

bfl_repo = "black-forest-labs/FLUX.1-dev"
dtype = torch.bfloat16

transformer = FluxTransformer2DModel.from_single_file("https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", torch_dtype=dtype)
quantize(transformer, weights=qfloat8)
freeze(transformer)

text_encoder_2 = T5EncoderModel.from_pretrained(bfl_repo, subfolder="text_encoder_2", torch_dtype=dtype)
quantize(text_encoder_2, weights=qfloat8)
freeze(text_encoder_2)

pipe = FluxPipeline.from_pretrained(bfl_repo, transformer=None, text_encoder_2=None, torch_dtype=dtype)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2

pipe.enable_model_cpu_offload()

prompt = "A cat holding a sign that says hello world"
image = pipe(
    prompt,
    guidance_scale=3.5,
    output_type="pil",
    num_inference_steps=20,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0]

image.save("flux-fp8-dev.png")

FluxPipeline

class diffusers.FluxPipeline

< >

( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None )

参数

用于文本到图像生成的 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 negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 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 = 3.5 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_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
  • negative_prompt (strList[str], 可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。如果未使用引导(即,如果 true_cfg_scale 不大于 1),则忽略。
  • negative_prompt_2 (strList[str], 可选) — 将发送到 tokenizer_2text_encoder_2 的不引导图像生成的提示词。如果未定义,所有文本编码器都将使用 negative_prompt
  • true_cfg_scale (float, 可选, 默认为 1.0) — 当 > 1.0 且提供了 negative_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 参数)的自定义 sigma 值。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 3.5) — 无分类器扩散引导 中定义的引导比例。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 输入参数生成。
  • 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 Adapters 的可选图像输入。
  • negative_ip_adapter_image_embeds (List[torch.Tensor], 可选) — 预先生成的 IP-Adapter 图像嵌入。它应该是一个列表,长度与 IP-Adapter 数量相同。每个元素应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果未提供,嵌入将从 ip_adapter_image 输入参数计算。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化 negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 如果指定,将作为 kwargs 字典传递给 diffusers.models.attention_processorself.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.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers import FluxPipeline

>>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
>>> image.save("flux.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 层)。

FluxImg2ImgPipeline

class diffusers.FluxImg2ImgPipeline

< >

( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None )

参数

用于图像修复的 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 negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 image: 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_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]) — 用作起点的图像、Numpy 数组或表示图像批次的张量。对于 Numpy 数组和 PyTorch 张量,预期值范围在 [0, 1] 之间。如果它是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果它是 Numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜在表示作为 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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成潜在张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 用于 IP 适配器的可选图像输入。
  • 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 适配器的可选图像输入。
  • 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.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中定义的 self.processorAttentionProcessor
  • 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 FluxImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> device = "cuda"
>>> pipe = FluxImg2ImgPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
>>> pipe = pipe.to(device)

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> init_image = load_image(url).resize((1024, 1024))

>>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"

>>> images = pipe(
...     prompt=prompt, image=init_image, num_inference_steps=4, strength=0.95, guidance_scale=0.0
... ).images[0]

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 层)。

FluxInpaintPipeline

class diffusers.FluxInpaintPipeline

< >

( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = 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 类的第二个分词器。

用于图像修复的 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 negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 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 padding_mask_crop: 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_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]) — 用作起点的图像、Numpy 数组或表示图像批次的张量。对于 Numpy 数组和 PyTorch 张量,预期值范围在 [0, 1] 之间。如果它是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果它是 Numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜在表示作为 image,但如果直接传递潜在表示,则不会再次编码。
  • mask_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — 用于遮盖 image 的图像、Numpy 数组或表示图像批次的张量。遮罩中白色像素的部分将被重新绘制,而黑色像素的部分将被保留。如果 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]) — 表示由 VAE 生成的用于遮盖 image 的图像批次的 Tensor。如果未提供,遮罩潜在张量将由 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。
  • padding_mask_crop (int, 可选, 默认为 None) — 应用于图像和遮罩的裁剪边距大小。如果为 None,则不对图像和 mask_image 应用裁剪。如果 padding_mask_crop 不为 None,它将首先找到与图像宽高比相同且包含所有遮罩区域的矩形区域,然后根据 padding_mask_crop 扩展该区域。然后将根据扩展区域裁剪图像和 mask_image,再调整大小到原始图像大小以进行修复。当遮罩区域较小而图像较大且包含与修复无关的信息(例如背景)时,这很有用。
  • 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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜在量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将通过使用提供的随机 generator 进行采样来生成潜在量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • ip_adapter_image — (PipelineImageInput, 可选):用于与 IP 适配器配合使用的可选图像输入。
  • 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 适配器配合使用的可选图像输入。
  • 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.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 self.processorAttentionProcessor
  • 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 FluxInpaintPipeline
>>> from diffusers.utils import load_image

>>> pipe = FluxInpaintPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> source = load_image(img_url)
>>> mask = load_image(mask_url)
>>> image = pipe(prompt=prompt, image=source, mask_image=mask).images[0]
>>> image.save("flux_inpainting.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 (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 比例。

FluxControlNetInpaintPipeline

diffusers.FluxControlNetInpaintPipeline

< >

( 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] )

参数

用于图像修复的 Flux controlnet 流水线。

参考: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 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.Optional[torch.FloatTensor] = 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 height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 padding_mask_crop: typing.Optional[int] = None sigmas: typing.Optional[typing.List[float]] = None num_inference_steps: int = 28 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_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_2 (strList[str], 可选) — 要发送给 tokenizer_2text_encoder_2 的提示或提示列表。
  • image (PIL.Image.ImageList[PIL.Image.Image]torch.FloatTensor) — 要进行图像修复的图像。
  • mask_image (PIL.Image.ImageList[PIL.Image.Image]torch.FloatTensor) — 用于图像修复的遮罩图像。遮罩中的白色像素将被重新绘制,而黑色像素将被保留。
  • masked_image_latents (torch.FloatTensor, 可选) — 预生成的遮罩图像潜在量。
  • control_image (PIL.Image.ImageList[PIL.Image.Image]torch.FloatTensor) — ControlNet 输入条件。用于控制生成的图像。
  • height (int, 可选, 默认为 self.default_sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, 可选, 默认为 self.default_sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • strength (float, 可选, 默认为 0.6) — 概念上,指示对遮罩区域进行图像修复的程度。必须介于 0 和 1 之间。
  • padding_mask_crop (int, 可选) — 裁剪遮罩时要使用的填充大小。
  • num_inference_steps (int, 可选, 默认为 28) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。
  • sigmas (List[float], 可选) — 与支持 sigmas 参数的调度器一起用于去噪过程的自定义 sigmas。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.0) — Classifier-Free Diffusion Guidance 中定义的指导比例。
  • control_guidance_start (floatList[float], 可选, 默认为 0.0) — ControlNet 开始应用的步骤总数的百分比。
  • control_guidance_end (floatList[float], 可选, 默认为 1.0) — ControlNet 停止应用的步骤总数的百分比。
  • control_mode (intList[int], 可选) — ControlNet 的模式。如果使用多个 ControlNet,这应该是一个列表。
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 1.0) — ControlNet 的输出乘以 controlnet_conditioning_scale,然后添加到原始 Transformer 的残差中。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.FloatTensor, 可选) — 预生成的噪声潜在量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 对象,而不是普通元组。
  • joint_attention_kwargs (dict, optional) — 要传递给联合注意力机制的附加关键字参数。
  • callback_on_step_end (Callable, optional) — 推理过程中在每个去噪步骤结束时调用的函数。
  • callback_on_step_end_tensor_inputs (List[str], optional) — callback_on_step_end 函数的张量输入列表。
  • max_sequence_length (int, optional, defaults to 512) — 要生成的序列的最大长度。

返回

~pipelines.flux.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers import FluxControlNetInpaintPipeline
>>> from diffusers.models import FluxControlNetModel
>>> from diffusers.utils import load_image

>>> controlnet = FluxControlNetModel.from_pretrained(
...     "InstantX/FLUX.1-dev-controlnet-canny", torch_dtype=torch.float16
... )
>>> pipe = FluxControlNetInpaintPipeline.from_pretrained(
...     "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.to("cuda")

>>> control_image = load_image(
...     "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
... )
>>> init_image = load_image(
...     "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
... )
>>> mask_image = load_image(
...     "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
... )

>>> prompt = "A girl holding a sign that says InstantX"
>>> image = pipe(
...     prompt,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     control_guidance_start=0.2,
...     control_guidance_end=0.8,
...     controlnet_conditioning_scale=0.7,
...     strength=0.7,
...     num_inference_steps=28,
...     guidance_scale=3.5,
... ).images[0]
>>> image.save("flux_controlnet_inpaint.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 输入参数生成。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则应用于文本编码器所有 LoRA 层的 LoRA 比例。

FluxControlNetImg2ImgPipeline

class diffusers.FluxControlNetImg2ImgPipeline

< >

( 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] )

参数

用于图像到图像生成的 Flux ControlNet 管线。

参考: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 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 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 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.FluxPipelineOutput or tuple

参数

  • prompt (str or List[str], optional) — 用于指导图像生成的提示。
  • prompt_2 (str or List[str], optional) — 要发送给 tokenizer_2text_encoder_2 的提示。
  • image (PIL.Image.Image or List[PIL.Image.Image] or torch.FloatTensor) — 要通过管线修改的图像。
  • control_image (PIL.Image.Image or List[PIL.Image.Image] or torch.FloatTensor) — ControlNet 输入条件。用于控制生成的图像。
  • height (int, optional, defaults to self.default_sample_size * self.vae_scale_factor) — 生成图像的像素高度。
  • width (int, optional, defaults to self.default_sample_size * self.vae_scale_factor) — 生成图像的像素宽度。
  • strength (float, optional, defaults to 0.6) — 概念上表示对参考 image 进行转换的程度。必须介于 0 和 1 之间。
  • num_inference_steps (int, optional, defaults to 28) — 去噪步骤的数量。更多的去噪步骤通常会生成更高质量的图像,但推理速度会变慢。
  • sigmas (List[float], optional) — 自定义 sigma,用于支持 sigmas 参数的调度器进行去噪。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, optional, defaults to 7.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。
  • control_mode (int or List[int], optional) — ControlNet 的模式。如果使用多个 ControlNet,则应为一个列表。
  • controlnet_conditioning_scale (float or List[float], optional, defaults to 1.0) — ControlNet 的输出乘以 controlnet_conditioning_scale 后添加到原始 transformer 中的残差。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个提示要生成的图像数量。
  • generator (torch.Generator or List[torch.Generator], optional) — 一个或多个 torch 生成器,用于使生成确定性。
  • latents (torch.FloatTensor, optional) — 预生成的噪声潜在,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同生成。
  • prompt_embeds (torch.FloatTensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。
  • pooled_prompt_embeds (torch.FloatTensor, optional) — 预生成的池化文本嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 对象,而不是普通元组。
  • joint_attention_kwargs (dict, optional) — 要传递给联合注意力机制的附加关键字参数。
  • callback_on_step_end (Callable, optional) — 推理过程中在每个去噪步骤结束时调用的函数。
  • callback_on_step_end_tensor_inputs (List[str], optional) — callback_on_step_end 函数的张量输入列表。
  • max_sequence_length (int, optional, defaults to 512) — 要生成的序列的最大长度。

返回

~pipelines.flux.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers import FluxControlNetImg2ImgPipeline, FluxControlNetModel
>>> from diffusers.utils import load_image

>>> device = "cuda" if torch.cuda.is_available() else "cpu"

>>> controlnet = FluxControlNetModel.from_pretrained(
...     "InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16
... )

>>> pipe = FluxControlNetImg2ImgPipeline.from_pretrained(
...     "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
... )

>>> pipe.text_encoder.to(torch.float16)
>>> pipe.controlnet.to(torch.float16)
>>> pipe.to("cuda")

>>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
>>> init_image = load_image(
...     "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
... )

>>> prompt = "A girl in city, 25 years old, cool, futuristic"
>>> image = pipe(
...     prompt,
...     image=init_image,
...     control_image=control_image,
...     control_guidance_start=0.2,
...     control_guidance_end=0.8,
...     controlnet_conditioning_scale=1.0,
...     strength=0.7,
...     num_inference_steps=2,
...     guidance_scale=3.5,
... ).images[0]
>>> image.save("flux_controlnet_img2img.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 输入参数生成。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则应用于文本编码器所有 LoRA 层的 LoRA 比例。

FluxControlPipeline

class diffusers.FluxControlPipeline

< >

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

参数

用于可控文本到图像生成的 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 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 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 = 3.5 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
  • 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 的尺寸。如果传递了 height 和/或 width,则 image 会相应地调整大小。如果在 init 中指定了多个 ControlNet,则图像必须作为列表传递,以便列表的每个元素都可以正确批处理以输入到单个 ControlNet。
  • 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可选,默认为 3.5) — 如 Classifier-Free Diffusion Guidance 中定义的指导比例。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 启用指导比例。更高的指导比例会促使生成与文本 prompt 紧密相关的图像,但通常会牺牲图像质量。
  • num_images_per_prompt (int可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator]可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.FloatTensor可选) — 预生成的带噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示词调整同一生成。如果未提供,潜变量张量将通过使用提供的随机 generator 采样生成。
  • prompt_embeds (torch.FloatTensor可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • output_type (str可选,默认为 "pil") — 生成图像的输出格式。选择 PILPIL.Image.Imagenp.array
  • return_dict (bool可选,默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict可选) — 如果指定,将 kwargs 字典传递给 diffusers.models.attention_processor 中定义的 self.processorAttentionProcessor
  • 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 controlnet_aux import CannyDetector
>>> from diffusers import FluxControlPipeline
>>> from diffusers.utils import load_image

>>> pipe = FluxControlPipeline.from_pretrained(
...     "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16
... ).to("cuda")

>>> prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
>>> control_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png"
... )

>>> processor = CannyDetector()
>>> control_image = processor(
...     control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024
... )

>>> image = pipe(
...     prompt=prompt,
...     control_image=control_image,
...     height=1024,
...     width=1024,
...     num_inference_steps=50,
...     guidance_scale=30.0,
... ).images[0]
>>> image.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 层。

FluxControlImg2ImgPipeline

class diffusers.FluxControlImg2ImgPipeline

< >

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

参数

用于图像修复的 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 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]) — 用作起点的图像、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。
  • 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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预生成的带噪声的潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示微调同一生成。如果未提供,则将使用提供的随机 generator 采样生成潜在张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PILPIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.flux.FluxPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 如果指定,将 kwargs 字典传递给 diffusers.models.attention_processorself.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.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from controlnet_aux import CannyDetector
>>> from diffusers import FluxControlImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = FluxControlImg2ImgPipeline.from_pretrained(
...     "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16
... ).to("cuda")

>>> prompt = "A robot made of exotic candies and chocolates of different kinds. Abstract background"
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/watercolor-painting.jpg"
... )
>>> control_image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png"
... )

>>> processor = CannyDetector()
>>> control_image = processor(
...     control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024
... )

>>> image = pipe(
...     prompt=prompt,
...     image=image,
...     control_image=control_image,
...     strength=0.8,
...     height=1024,
...     width=1024,
...     num_inference_steps=50,
...     guidance_scale=30.0,
... ).images[0]
>>> image.save("output.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 (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 层)。

FluxPriorReduxPipeline

class diffusers.FluxPriorReduxPipeline

< >

( image_encoder: SiglipVisionModel feature_extractor: SiglipImageProcessor image_embedder: ReduxImageEncoder text_encoder: CLIPTextModel = None tokenizer: CLIPTokenizer = None text_encoder_2: T5EncoderModel = None tokenizer_2: T5TokenizerFast = None )

参数

  • image_encoder (SiglipVisionModel) — 用于编码输入图像的 SIGLIP 视觉模型。
  • feature_extractor (SiglipImageProcessor) — 用于对 SIGLIP 模型图像进行预处理的图像处理器。
  • image_embedder (ReduxImageEncoder) — 用于处理 SIGLIP 嵌入的 Redux 图像编码器。
  • 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 Redux 管道。

参考:https://blackforestlabs.ai/flux-1-tools/

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None prompt_embeds_scale: typing.Union[float, typing.List[float], NoneType] = 1.0 pooled_prompt_embeds_scale: typing.Union[float, typing.List[float], NoneType] = 1.0 return_dict: bool = True ) ~pipelines.flux.FluxPriorReduxPipelineOutputtuple

参数

  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — 用作起点的图像、numpy 数组或表示图像批次的张量。对于 numpy 数组和 pytorch 张量,预期值范围在 [0, 1] 之间。如果是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果是 numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)
  • prompt (strList[str], 可选) — 用于引导图像生成的提示。实验性功能:要使用此功能,请确保将文本编码器显式加载到管道中。如果未加载文本编码器,则将忽略提示。
  • prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_encoder_2 的提示。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.flux.FluxPriorReduxPipelineOutput 而不是普通元组。

返回

~pipelines.flux.FluxPriorReduxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers import FluxPriorReduxPipeline, FluxPipeline
>>> from diffusers.utils import load_image

>>> device = "cuda"
>>> dtype = torch.bfloat16

>>> repo_redux = "black-forest-labs/FLUX.1-Redux-dev"
>>> repo_base = "black-forest-labs/FLUX.1-dev"
>>> pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(repo_redux, torch_dtype=dtype).to(device)
>>> pipe = FluxPipeline.from_pretrained(
...     repo_base, text_encoder=None, text_encoder_2=None, torch_dtype=torch.bfloat16
... ).to(device)

>>> image = load_image(
...     "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png"
... )
>>> pipe_prior_output = pipe_prior_redux(image)
>>> images = pipe(
...     guidance_scale=2.5,
...     num_inference_steps=50,
...     generator=torch.Generator("cpu").manual_seed(0),
...     **pipe_prior_output,
... ).images
>>> images[0].save("flux-redux.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 (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 缩放因子。

FluxFillPipeline

class diffusers.FluxFillPipeline

< >

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

参数

用于图像修复/扩展的 Flux Fill pipeline。

参考:https://blackforestlabs.ai/flux-1-tools/

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Optional[torch.FloatTensor] = None mask_image: typing.Optional[torch.FloatTensor] = None masked_image_latents: typing.Optional[torch.FloatTensor] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 30.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)
  • 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]) — 表示由 VAE 生成的用于遮罩 image 的图像批处理的 Tensor。如果未提供,遮罩潜变量张量将由 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], 可选) — 用于去噪过程的自定义 sigma,调度器支持在其 set_timesteps 方法中添加 sigmas 参数。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 30.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。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 字典传递给 diffusers.models.attention_processorself.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.FluxPipelineOutputtuple

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

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

示例

>>> import torch
>>> from diffusers import FluxFillPipeline
>>> from diffusers.utils import load_image

>>> image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png")
>>> mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png")

>>> pipe = FluxFillPipeline.from_pretrained("black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()  # save some VRAM by offloading the model to CPU

>>> image = pipe(
...     prompt="a white paper cup",
...     image=image,
...     mask_image=mask,
...     height=1632,
...     width=1232,
...     guidance_scale=30,
...     num_inference_steps=50,
...     max_sequence_length=512,
...     generator=torch.Generator("cpu").manual_seed(0),
... ).images[0]
>>> image.save("flux_fill.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 缩放因子。
< > 在 GitHub 上更新