Diffusers documentation
Flux
Flux
Flux 是一系列基于扩散 Transformer 的文本生成图像模型。如需了解更多关于 Flux 的信息,请参阅 Flux 的创建者 Black Forest Labs 撰写的原始博客文章。
Flux 的原始模型检查点可在此处找到。原始推理代码可在此处找到。
Flux 在消费级硬件设备上运行可能成本较高。不过,你可以执行一系列优化,使其运行得更快,并且对内存更加友好。有关更多详细信息,请参阅 本节。此外,Flux 可以通过量化来提升内存效率,但代价是推理延迟会增加。要了解更多信息,请参考 这篇博客文章。如需获取详尽的资源列表,请查看 此 gist。
缓存还可以通过存储和复用中间输出来加速推理。
Flux 提供以下变体:
| 模型类型 | 模型 ID |
|---|---|
| 时间步蒸馏 | black-forest-labs/FLUX.1-schnell |
| Guidance-distilled | black-forest-labs/FLUX.1-dev |
| 填充 Inpainting/Outpainting(引导蒸馏) | black-forest-labs/FLUX.1-Fill-dev |
| Canny Control(引导蒸馏) | black-forest-labs/FLUX.1-Canny-dev |
| 深度控制(引导蒸馏) | black-forest-labs/FLUX.1-Depth-dev |
| Canny Control (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 |
| Kontext | black-forest-labs/FLUX.1-kontext |
所有检查点都有不同的用途,我们将在下文详细说明。
时间步蒸馏
max_sequence_length不能超过 256。guidance_scale必须为 0。- 由于这是一个时间步蒸馏模型,因此它受益于更少的采样步数。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", 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")Guidance-distilled
- 经过指导蒸馏的变体大约需要 50 个采样步骤即可生成高质量的内容。
- 它没有
max_sequence_length方面的任何限制。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", 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")填充 Inpainting/Outpainting
- Flux Fill 流水线与常规修复流水线不同,不需要将
strength作为输入。 - 它同时支持图像修复(inpainting)和图像外扩(outpainting)。
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, dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
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 Control
注意: 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", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
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 Control 也可以通过该条件的 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", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
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 的组件,其残差会被添加到实际的基础模型中。Depth Control 是一种替代架构,它通过将与输入控制条件的通道级拼接,并确保 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", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
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")Depth Control 也可以通过该条件的 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", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
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_embeds和pooled_prompt_embeds,然后将它们输入到FluxPipeline中进行图生图生成。 - 在使用
FluxPriorReduxPipeline与基础 pipeline 时,您可以在基础 pipeline 中设置text_encoder=None和text_encoder_2=None,以节省 VRAM。
import torch
from diffusers import FluxPriorReduxPipeline, FluxPipeline
from diffusers.utils import load_image
device = "cuda" # or "mps", "xpu", "cpu"
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, dtype=dtype).to(device)
pipe = FluxPipeline.from_pretrained(
repo_base,
text_encoder=None,
text_encoder_2=None,
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")Kontext
Flux Kontext 是一个支持在图像生成过程中进行上下文控制的模型,可实现编辑、优化、重新打光、风格迁移、角色定制等功能。
import torch
from diffusers import FluxKontextPipeline
from diffusers.utils import load_image
pipe = FluxKontextPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png").convert("RGB")
prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors"
image = pipe(
image=image,
prompt=prompt,
guidance_scale=2.5,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("flux-kontext.png")Flux Kontext 附带一个完整性安全检查器,应在图像生成步骤之后运行。要运行安全检查器,请从 black-forest-labs/flux 安装官方仓库,并添加以下代码:
from flux.content_filters import PixtralContentFilter
# ... pipeline invocation to generate images
integrity_checker = PixtralContentFilter(torch.device("cuda"))
image_ = np.array(image) / 255.0
image_ = 2 * image_ - 1
image_ = torch.from_numpy(image_).to("cuda", dtype=torch.float32).unsqueeze(0).permute(0, 3, 1, 2)
if integrity_checker.test_image(image_):
raise ValueError("Your image has been flagged. Choose another prompt/image or try again.")Kontext 图像修复
FluxKontextInpaintPipeline 支持在固定掩码区域内修改图像。它目前同时支持基于文本的条件控制和基于图像参考的条件控制。
import torch
from diffusers import FluxKontextInpaintPipeline
from diffusers.utils import load_image
prompt = "Change the yellow dinosaur to green one"
img_url = (
"https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_input.jpeg?raw=true"
)
mask_url = (
"https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_mask.png?raw=true"
)
source = load_image(img_url)
mask = load_image(mask_url)
pipe = FluxKontextInpaintPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(prompt=prompt, image=source, mask_image=mask, strength=1.0).images[0]
image.save("kontext_inpainting_normal.png")import torch
from diffusers import FluxKontextInpaintPipeline
from diffusers.utils import load_image
pipe = FluxKontextInpaintPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
prompt = "Replace this ball"
img_url = "https://images.pexels.com/photos/39362/the-ball-stadion-football-the-pitch-39362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
mask_url = "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/ball_mask.png?raw=true"
image_reference_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTah3x6OL_ECMBaZ5ZlJJhNsyC-OSMLWAI-xw&s"
source = load_image(img_url)
mask = load_image(mask_url)
image_reference = load_image(image_reference_url)
mask = pipe.mask_processor.blur(mask, blur_factor=12)
image = pipe(
prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0
).images[0]
image.save("kontext_inpainting_ref.png")将 Flux Turbo LoRA 与 Flux Control、Fill 和 Redux 结合使用
我们可以将 Flux Turbo LoRA 与 Flux Control 以及其他流水线(如 Fill 和 Redux)结合使用,以实现少步推理。下面的示例展示了如何针对深度 Flux Control LoRA 以及来自 ByteDance/Hyper-SD 的 turbo 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", 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 完全重置为其原始状态。随后,生成的 pipeline 即可与 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", dtype=torch.bfloat16
).to("cuda") # or "mps", "xpu", "cpu"
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')
优化
Flux 是一个非常大的模型,加载所有建模组件大约需要 50GB 的 RAM/VRAM。启用以下部分优化以降低内存需求。
组卸载
Group offloading 通过卸载内部层的分组(而非整个模型或权重)来降低 VRAM 使用量。你需要在 pipeline 的所有模型组件上调用 apply_group_offloading()。offload_type 参数允许你在 block 级别和 leaf 级别的卸载之间切换。将其设置为 leaf_level 会将最低层级的 leaf 级参数卸载到 CPU,而不是在 module 级别进行卸载。
在支持异步数据流传输的 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,
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", 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,
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,
dtype=torch.float16,
)
pipeline = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
text_encoder_2=text_encoder_8bit,
transformer=transformer_8bit,
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 提供的原始格式检查点。当尝试加载社区发布的模型微调版本或量化版本时,这一功能同样非常有用。
FP8推理的稳定性可能因您使用的 GPU 类型、CUDA 版本以及torch版本而异。建议您在机器上使用optimum-quanto库来运行 FP8 推理。
以下示例演示了如何在显存低于 16GB 的情况下运行 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", dtype=dtype)
quantize(transformer, weights=qfloat8)
freeze(transformer)
text_encoder_2 = T5EncoderModel.from_pretrained(bfl_repo, subfolder="text_encoder_2", dtype=dtype)
quantize(text_encoder_2, weights=qfloat8)
freeze(text_encoder_2)
pipe = FluxPipeline.from_pretrained(bfl_repo, transformer=None, text_encoder_2=None, 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
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于文本到图像生成的 Flux 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 3.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,则使用prompt。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时会被忽略(即当true_cfg_scale不大于1时会被忽略)。 - negative_prompt_2 (
str或list[str],可选) — 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则所有文本编码器都会使用negative_prompt。 - true_cfg_scale(
float,可选,默认值为 1.0)— 当true_cfg_scale> 1 且提供了negative_prompt时,将启用真正的无分类器引导(guidance scale)。 - height (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - width (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float, 可选, ,默认值为 3.5)—— 通过设置guidance_scale> 1. 更高的guidance_scale值,可以促使模型生成与prompt更加一致的图片,但代价是图像质量会降低。Guidance-distilled 模型近似了
guidance_scale> 1 时的真实 classifier-free guidance。有关详细信息,请参阅 论文。 - 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输入参数生成池化文本嵌入。 - ip_adapter_image — (
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - ip_adapter_image_embeds (
list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_ip_adapter_image —
(
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - negative_ip_adapter_image_embeds (
list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_prompt_embeds (
torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - 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 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")encode_prompt
< source >( 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 缩放系数。
FluxImg2ImgPipeline
class diffusers.FluxImg2ImgPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像修复的 Flux 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0image: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,将使用prompt。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时会被忽略(即当true_cfg_scale不大于1时会被忽略)。 - negative_prompt_2 (
str或list[str],可选) — 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则所有文本编码器都会使用negative_prompt。 - true_cfg_scale(
float,可选,默认值为 1.0)— 当true_cfg_scale> 1 且提供了negative_prompt时,将启用真正的无分类器引导(guidance scale)。 - 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,但如果直接传入潜变量,则不会再次进行编码。 - 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输入参数生成池化文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - ip_adapter_image_embeds (
list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_ip_adapter_image —
(
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - negative_ip_adapter_image_embeds (
list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.flux.FluxPipelineOutput而不是普通元组。 - joint_attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中self.processor下定义的AttentionProcessor。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
list,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为 512)— 与prompt配合使用的最大序列长度。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers 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]encode_prompt
< source >( 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 缩放系数。
FluxInpaintPipeline
class diffusers.FluxInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像修复的 Flux 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0image: 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 = Nonepadding_mask_crop: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,将使用prompt。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时会被忽略(即当true_cfg_scale不大于1时会被忽略)。 - negative_prompt_2 (
str或list[str],可选) — 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则所有文本编码器都会使用negative_prompt。 - true_cfg_scale(
float,可选,默认值为 1.0)— 当true_cfg_scale> 1 且提供了negative_prompt时,将启用真正的无分类器引导(guidance scale)。 - 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,但如果直接传入潜变量,则不会再次进行编码。 - 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,以获得最佳效果。 - padding_mask_crop (
int, 可选,默认为None) — 应用于图像和掩码的裁剪边距大小。如果为None,则不对 image 和 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.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从prompt输入参数生成池化文本嵌入。 - negative_prompt_embeds (
torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - ip_adapter_image_embeds (
list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_ip_adapter_image —
(
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - negative_ip_adapter_image_embeds (
list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.flux.FluxPipelineOutput而不是普通元组。 - joint_attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中self.processor下定义的AttentionProcessor。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
list,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传递。您只能包含流水线类._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为 512)— 与prompt配合使用的最大序列长度。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers 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
< source >( 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 缩放系数。
FluxControlNetInpaintPipeline
类 diffusers.FluxControlNetInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelcontrolnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像修复的 Flux controlnet 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( 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]] = 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]] = Nonecontrol_image: 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.6padding_mask_crop: int | None = Nonesigmas: list[float] | None = Nonenum_inference_steps: int = 28guidance_scale: float = 7.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0control_mode: int | list[int] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。 - prompt_2(
str或list[str],可选)— 要发送给tokenizer_2和text_encoder_2的提示词或提示词列表。 - image (
PIL.Image.Image或list[PIL.Image.Image]或torch.FloatTensor) — 要执行图像修复的图像。 - mask_image (
PIL.Image.Image或list[PIL.Image.Image]或torch.FloatTensor) — 用于图像修复的掩码图像。掩码中的白色像素将被重绘,而黑色像素将保持不变。 - masked_image_latents(
torch.FloatTensor,可选)— 预生成的带掩码图像潜变量。 - control_image (
PIL.Image.Image或list[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参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。 - control_guidance_start(
float或list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。 - control_guidance_end (
float或list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。 - control_mode (
int或list[int],可选) — ControlNet 的模式。如果使用了多个 ControlNet,则此参数应为列表。 - controlnet_conditioning_scale(
float或list[float],可选,默认值为 1.0)— ControlNet 的输出在加到原始 transformer 的残差之前,会先乘以controlnet_conditioning_scale。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或多个 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。 - prompt_embeds (
torch.FloatTensor,可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。 - pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的池化文本嵌入。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。在PIL.Image和np.array之间选择。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.flux.FluxPipelineOutput而不是普通元组。 - joint_attention_kwargs (
dict, 可选) — 传递给联合注意力机制的额外关键字参数。 - callback_on_step_end (
Callable, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。 - callback_on_step_end_tensor_inputs(
list[str],可选)—callback_on_step_end函数的张量输入列表。 - max_sequence_length (
int,可选,默认值为 512) — 要生成的序列的最大长度。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> 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
< source >( 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 缩放系数。
FluxControlNetImg2ImgPipeline
class diffusers.FluxControlNetImg2ImgPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelcontrolnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像到图像生成的 Flux controlnet 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( 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]] = Noneheight: int | None = Nonewidth: int | None = Nonestrength: float = 0.6num_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 7.0control_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0control_mode: int | list[int] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。 - prompt_2(
str或list[str],可选)— 要发送给tokenizer_2和text_encoder_2的提示词或提示词列表。 - image (
PIL.Image.Image或list[PIL.Image.Image]或torch.FloatTensor) — 要通过 pipeline 修改的图像。 - control_image (
PIL.Image.Image或list[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) — 从概念上讲,表示对参考image进行多大程度的变换。取值必须在 0 到 1 之间。 - num_inference_steps (
int,可选,默认为 28) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但推理速度会更慢。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。 - control_mode (
int或list[int],可选) — ControlNet 的模式。如果使用了多个 ControlNet,则此参数应为列表。 - controlnet_conditioning_scale(
float或list[float],可选,默认值为 1.0)— ControlNet 的输出在加到原始 transformer 的残差之前,会先乘以controlnet_conditioning_scale。 - control_guidance_start(
float或list[float],可选,默认值为 0.0)—— ControlNet 开始施加影响的总步数百分比。 - control_guidance_end (
float或list[float],可选,默认值为 1.0) — ControlNet 停止应用时占总步数的百分比。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或多个 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。 - prompt_embeds (
torch.FloatTensor,可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。 - pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的池化文本嵌入。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。在PIL.Image和np.array之间选择。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.flux.FluxPipelineOutput而不是普通元组。 - joint_attention_kwargs (
dict, 可选) — 传递给联合注意力机制的额外关键字参数。 - callback_on_step_end (
Callable, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。 - callback_on_step_end_tensor_inputs(
list[str],可选)—callback_on_step_end函数的张量输入列表。 - max_sequence_length (
int,可选,默认值为 512) — 要生成的序列的最大长度。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> 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
< source >( 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 缩放系数。
FluxControlPipeline
class diffusers.FluxControlPipeline
< source >( 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 流水线。
参考:https://bfl.ai/flux-1-tools
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonecontrol_image: 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 = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 3.5num_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[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,将使用prompt。 - 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 的输入。 - 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)— 通过设置guidance_scale> 1. 更高的guidance_scale值,可以促使模型生成与提示词更一致的图片,但代价是图像质量会降低。Guidance-distilled 模型在
guidance_scale> 1 时近似真实的 classifier-free guidance。有关详细信息,请参阅论文。 - 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 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")encode_prompt
< source >( 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 缩放系数。
FluxControlImg2ImgPipeline
类 diffusers.FluxControlImg2ImgPipeline
< source >( 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 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( 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]] = 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[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,将使用prompt。 - 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 的输入。 - 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 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
< source >( 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 缩放系数。
FluxPriorReduxPipeline
class diffusers.FluxPriorReduxPipeline
< source >( image_encoder: SiglipVisionModelfeature_extractor: SiglipImageProcessorPilimage_embedder: ReduxImageEncodertext_encoder: CLIPTextModel = Nonetokenizer: CLIPTokenizer = Nonetext_encoder_2: T5EncoderModel = Nonetokenizer_2: T5Tokenizer = 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 类的 Tokenizer。
用于图像到图像生成的 Flux Redux 流水线。
参考:https://blackforestlabs.ai/flux-1-tools/
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneprompt_embeds_scale: float | list[float] | None = 1.0pooled_prompt_embeds_scale: float | list[float] | None = 1.0return_dict: bool = True ) → ~pipelines.flux.FluxPriorReduxPipelineOutput or tuple
参数
- 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) - prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。实验性功能:若要使用此功能,请确保显式将文本编码器加载到流水线中。如果未加载文本编码器,提示词将被忽略。 - prompt_2(
str或list[str],可选)— 要发送给tokenizer_2和text_encoder_2的提示词或提示词列表。 - prompt_embeds (
torch.FloatTensor,可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。 - pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的池化文本嵌入。 - prompt_embeds_scale(
float或list[float],可选,默认值为 1.0)— 在返回之前应用于 redux 提示嵌入的缩放因子(或针对每张图像的缩放因子列表)。 - pooled_prompt_embeds_scale(
float或list[float],可选,默认为 1.0) — 在返回之前,应用于 redux 池化提示嵌入的缩放因子(或每张图像的缩放因子列表)。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.flux.FluxPriorReduxPipelineOutput而不是普通元组。
返回值
~pipelines.flux.FluxPriorReduxPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.flux.FluxPriorReduxPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是一个包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> 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
< source >( 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 缩放系数。
FluxFillPipeline
class diffusers.FluxFillPipeline
< source >( 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 Fill 流水线。
参考:https://blackforestlabs.ai/flux-1-tools/
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Optional[torch.FloatTensor] = Nonemask_image: typing.Optional[torch.FloatTensor] = Nonemasked_image_latents: typing.Optional[torch.FloatTensor] = Noneheight: int | None = Nonewidth: int | None = Nonestrength: float = 1.0num_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 30.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[str] = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,将使用prompt。 - 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)而不是三个,因此 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,可选,默认为 30.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 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")encode_prompt
< source >( 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 缩放系数。
FluxKontextPipeline
class diffusers.FluxKontextPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于图像到图像和文本到图像生成的 Flux Kontext 流水线。
参考:https://bfl.ai/announcements/flux-1-kontext-dev
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneprompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 3.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512max_area: int = 1048576_auto_resize: bool = True ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- 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,但如果直接传入潜变量,则不会再次进行编码。 - prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,则使用prompt。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时会被忽略(即当true_cfg_scale不大于1时会被忽略)。 - negative_prompt_2 (
str或list[str],可选) — 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则所有文本编码器都会使用negative_prompt。 - true_cfg_scale (
float,可选,默认值为 1.0) — 当值大于 1.0 且提供了negative_prompt时,启用真正的无分类器引导(true classifier-free guidance)。 - 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)— 通过设置guidance_scale> 1. 更高的guidance_scale值,可以促使模型生成与提示词更一致的图片,但代价是图像质量会降低。Guidance-distilled 模型在
guidance_scale> 1 时近似真实的 classifier-free guidance。有关详细信息,请参阅论文。 - 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输入参数生成池化文本嵌入。 - ip_adapter_image — (
PipelineImageInput,可选): 用于配合 IP Adapter 使用的可选图像输入。 - ip_adapter_image_embeds (
list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_ip_adapter_image —
(
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - negative_ip_adapter_image_embeds (
list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_prompt_embeds (
torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - 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配合使用的最大序列长度。 - max_area (
int,默认为1024 ** 2) — 生成图像的最大面积(以像素为单位)。高度和宽度将在此面积范围内进行调整,同时保持宽高比。 - _auto_resize (
bool,可选,默认为True) — 是否自动将输入图像调整到首选分辨率。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import FluxKontextPipeline
>>> from diffusers.utils import load_image
>>> pipe = FluxKontextPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
... ).convert("RGB")
>>> prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors"
>>> image = pipe(
... image=image,
... prompt=prompt,
... guidance_scale=2.5,
... generator=torch.Generator().manual_seed(42),
... ).images[0]
>>> image.save("output.png")encode_prompt
< source >( 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 缩放系数。
FluxKontextInpaintPipeline
class diffusers.FluxKontextInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = None )
参数
- transformer (FluxTransformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — CLIP,具体为 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel) — T5,具体为 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - tokenizer_2(
T5TokenizerFast)—— 第二个 T5TokenizerFast 类的 Tokenizer。
用于文本到图像生成的 Flux Kontext 流水线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneimage_reference: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneprompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] | None = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonestrength: float = 1.0padding_mask_crop: int | None = Nonenum_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 3.5num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_ip_adapter_image_embeds: list[torch.Tensor] | None = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512max_area: int = 1048576_auto_resize: bool = True ) → ~pipelines.flux.FluxPipelineOutput or tuple
参数
- image (
torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]或list[np.ndarray]) —Image、numpy 数组或张量,表示要执行图像修复(inpainting)的图像批次(即根据prompt和image_reference,将mask_image指定的图像区域进行遮罩并重绘)。对于 numpy 数组和 PyTorch 张量,预期的取值范围为[0, 1]。如果输入是张量或张量列表,预期的形状应为(B, C, H, W)或(C, H, W)。如果输入是 numpy 数组或数组列表,预期的形状应为(B, H, W, C)或(H, W, C)。也可以将图像潜变量(image latents)作为image传入,但直接传入潜变量时不会再次进行编码。 - image_reference (
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,但如果直接传入潜变量,则不会再次进行编码。 - 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)。 - prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2 (
str或list[str],可选) — 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,则使用prompt。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。当不使用引导时会被忽略(即当true_cfg_scale不大于1时会被忽略)。 - negative_prompt_2 (
str或list[str],可选) — 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则所有文本编码器都会使用negative_prompt。 - true_cfg_scale(
float,可选,默认值为 1.0)— 当true_cfg_scale> 1 且提供了negative_prompt时,将启用真正的无分类器引导(guidance scale)。 - height (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - width (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - strength (
float, 可选,默认为 1.0) — 指示对参考image进行变换的程度。取值必须在 0 到 1 之间。image用作起始点,strength越高,添加的噪声越多。去噪步数取决于初始添加的噪声量。当strength为 1 时,添加的噪声达到最大值,去噪过程将运行num_inference_steps中指定的完整迭代次数。值为 1 时,基本上会忽略image。 - padding_mask_crop (
int, 可选,默认为None) — 应用于图像和掩码的裁剪边距大小。如果为None,则不对 image 和 mask_image 进行裁剪。如果padding_mask_crop不为None,则会先找到一个与图像具有相同宽高比且包含所有掩码区域的矩形区域,然后基于padding_mask_crop扩展该区域。随后,在调整大小以匹配原始图像尺寸用于修复之前,会根据扩展后的区域对图像和 mask_image 进行裁剪。当掩码区域较小而图像较大,且包含与修复无关的信息(例如背景)时,此功能非常有用。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float, 可选, ,默认值为 3.5)—— 通过设置guidance_scale> 1. 更高的guidance_scale值,可以促使模型生成与prompt更一致的图像,但图像质量可能会降低。Guidance-distilled 模型在
guidance_scale> 1 时近似真实的 classifier-free guidance。有关详细信息,请参阅论文。 - 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输入参数生成池化文本嵌入。 - ip_adapter_image — (
PipelineImageInput,可选): 用于配合 IP Adapter 使用的可选图像输入。 - ip_adapter_image_embeds (
list[torch.Tensor], 可选) — 为 IP-Adapter 预生成的图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_ip_adapter_image —
(
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - negative_ip_adapter_image_embeds (
list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,其长度与 IP-Adapter 的数量相同。每个元素应该是一个形状为(batch_size, num_images, emb_dim)的张量。如果未提供,则从ip_adapter_image输入参数计算嵌入。 - negative_prompt_embeds (
torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据negative_prompt输入参数生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - 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配合使用的最大序列长度。 - max_area (
int,默认为1024 ** 2) — 生成图像的最大面积(以像素为单位)。高度和宽度将在此面积范围内进行调整,同时保持宽高比。 - _auto_resize (
bool,可选,默认为True) — 是否自动将输入图像调整到首选分辨率。
返回值
~pipelines.flux.FluxPipelineOutput 或 tuple
~pipelines.flux.FluxPipelineOutput(当 return_dict 为 True 时),否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
仅使用文本进行图像修复
>>> import torch
>>> from diffusers import FluxKontextInpaintPipeline
>>> from diffusers.utils import load_image
>>> prompt = "Change the yellow dinosaur to green one"
>>> img_url = (
... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_input.jpeg?raw=true"
... )
>>> mask_url = (
... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_mask.png?raw=true"
... )
>>> source = load_image(img_url)
>>> mask = load_image(mask_url)
>>> pipe = FluxKontextInpaintPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = pipe(prompt=prompt, image=source, mask_image=mask, strength=1.0).images[0]
>>> image.save("kontext_inpainting_normal.png")使用图像条件进行图像修复
>>> import torch
>>> from diffusers import FluxKontextInpaintPipeline
>>> from diffusers.utils import load_image
>>> pipe = FluxKontextInpaintPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> prompt = "Replace this ball"
>>> img_url = "https://images.pexels.com/photos/39362/the-ball-stadion-football-the-pitch-39362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
>>> mask_url = (
... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/ball_mask.png?raw=true"
... )
>>> image_reference_url = (
... "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTah3x6OL_ECMBaZ5ZlJJhNsyC-OSMLWAI-xw&s"
... )
>>> source = load_image(img_url)
>>> mask = load_image(mask_url)
>>> image_reference = load_image(image_reference_url)
>>> mask = pipe.mask_processor.blur(mask, blur_factor=12)
>>> image = pipe(
... prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0
... ).images[0]
>>> image.save("kontext_inpainting_ref.png")encode_prompt
< source >( 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 缩放系数。