Diffusers 文档
Flux
并获得增强的文档体验
开始使用
Flux
Flux 是一系列基于扩散 Transformer 的文本到图像生成模型。要了解有关 Flux 的更多信息,请查看 Flux 的创建者 Black Forest Labs 发布的博客文章。
Flux 的原始模型 checkpoints 可以在这里找到。原始推理代码可以在这里找到。
Flux 在消费级硬件设备上运行的成本可能相当高昂。但是,您可以执行一系列优化来使其运行更快且内存更友好。查看此部分了解更多详情。此外,Flux 可以从量化中受益,以提高内存效率,但会牺牲推理延迟。请参阅这篇博客文章以了解更多信息。有关详尽的资源列表,请查看此 gist。
Flux 提供以下变体
模型类型 | 模型 ID |
---|---|
Timestep-distilled | black-forest-labs/FLUX.1-schnell |
Guidance-distilled | black-forest-labs/FLUX.1-dev |
填充/外绘(Guidance-distilled) | black-forest-labs/FLUX.1-Fill-dev |
Canny Control(Guidance-distilled) | black-forest-labs/FLUX.1-Canny-dev |
Depth Control(Guidance-distilled) | black-forest-labs/FLUX.1-Depth-dev |
Canny Control (LoRA) | black-forest-labs/FLUX.1-Canny-dev-lora |
Depth Control (LoRA) | black-forest-labs/FLUX.1-Depth-dev-lora |
Redux (Adapter) | black-forest-labs/FLUX.1-Redux-dev |
所有 checkpoints 都有不同的用途,我们将在下面详细介绍。
Timestep-distilled
max_sequence_length
不能超过 256。guidance_scale
需要为 0。- 由于这是一个 timestep-distilled 模型,它受益于更少的采样步骤。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "A cat holding a sign that says hello world"
out = pipe(
prompt=prompt,
guidance_scale=0.,
height=768,
width=1360,
num_inference_steps=4,
max_sequence_length=256,
).images[0]
out.save("image.png")
Guidance-distilled
- guidance-distilled 变体大约需要 50 个采样步骤才能生成高质量的图像。
- 它对
max_sequence_length
没有任何限制。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "a tiny astronaut hatching from an egg on the moon"
out = pipe(
prompt=prompt,
guidance_scale=3.5,
height=768,
width=1360,
num_inference_steps=50,
).images[0]
out.save("image.png")
Fill 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, torch_dtype=torch.bfloat16).to("cuda")
image = pipe(
prompt="a white paper cup",
image=image,
mask_image=mask,
height=1632,
width=1232,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0)
).images[0]
image.save(f"output.png")
Canny Control
注意: black-forest-labs/Flux.1-Canny-dev
不是 ControlNetModel 模型。 ControlNet 模型是与 UNet/Transformer 分离的组件,其残差被添加到实际的底层模型中。 Canny Control 是一种替代架构,它通过使用与输入控制条件的通道wise连接,并确保 Transformer 通过尽可能紧密地遵循条件来学习结构控制,从而达到与 ControlNet 模型基本相同的效果。
# !pip install -U controlnet-aux
import torch
from controlnet_aux import CannyDetector
from diffusers import FluxControlPipeline
from diffusers.utils import load_image
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16).to("cuda")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=50,
guidance_scale=30.0,
).images[0]
image.save("output.png")
Canny 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", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Canny-dev-lora")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=50,
guidance_scale=30.0,
).images[0]
image.save("output.png")
Depth Control
注意: black-forest-labs/Flux.1-Depth-dev
不是 ControlNet 模型。 ControlNetModel 模型是与 UNet/Transformer 分离的组件,其残差被添加到实际的底层模型中。 Depth Control 是一种替代架构,它通过使用与输入控制条件的通道wise连接,并确保 Transformer 通过尽可能紧密地遵循条件来学习结构控制,从而达到与 ControlNet 模型基本相同的效果。
# !pip install git+https://github.com/huggingface/image_gen_aux
import torch
from diffusers import FluxControlPipeline, FluxTransformer2DModel
from diffusers.utils import load_image
from image_gen_aux import DepthPreprocessor
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Depth-dev", torch_dtype=torch.bfloat16).to("cuda")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=30,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
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", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=30,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
Redux
- Flux Redux 管道是 FLUX.1 基础模型的适配器。 它可以与 flux-dev 和 flux-schnell 一起使用,用于图像到图像的生成。
- 您可以首先使用
FluxPriorReduxPipeline
获取prompt_embeds
和pooled_prompt_embeds
,然后将它们馈送到FluxPipeline
中以进行图像到图像的生成。 - 当将
FluxPriorReduxPipeline
与基础管道一起使用时,您可以在基础管道中设置text_encoder=None
和text_encoder_2=None
,以节省 VRAM。
import torch
from diffusers import FluxPriorReduxPipeline, FluxPipeline
from diffusers.utils import load_image
device = "cuda"
dtype = torch.bfloat16
repo_redux = "black-forest-labs/FLUX.1-Redux-dev"
repo_base = "black-forest-labs/FLUX.1-dev"
pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(repo_redux, torch_dtype=dtype).to(device)
pipe = FluxPipeline.from_pretrained(
repo_base,
text_encoder=None,
text_encoder_2=None,
torch_dtype=torch.bfloat16
).to(device)
image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png")
pipe_prior_output = pipe_prior_redux(image)
images = pipe(
guidance_scale=2.5,
num_inference_steps=50,
generator=torch.Generator("cpu").manual_seed(0),
**pipe_prior_output,
).images
images[0].save("flux-redux.png")
Combining Flux Turbo LoRAs with Flux Control, Fill, and 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", torch_dtype=torch.bfloat16)
control_pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora", adapter_name="depth")
control_pipe.load_lora_weights(
hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"), adapter_name="hyper-sd"
)
control_pipe.set_adapters(["depth", "hyper-sd"], adapter_weights=[0.85, 0.125])
control_pipe.enable_model_cpu_offload()
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = control_pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=8,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
Note about unload_lora_weights() when using Flux LoRAs
当卸载 Control LoRA 权重时,调用 pipe.unload_lora_weights(reset_to_overwritten_params=True)
以将 pipe.transformer
完全重置回其原始形式。 由此产生的管道可以与诸如 DiffusionPipeline.from_pipe() 之类的方法一起使用。 有关此参数的更多详细信息,请参见 此 PR。
Running FP16 inference
Flux 可以使用 FP16 生成高质量的图像(即,加速 Turing/Volta GPU 上的推理),但与 FP32/BF16 相比,会产生不同的输出。 问题是,当在 FP16 中运行时,文本编码器中的某些激活必须被裁剪,这会影响整体图像。 因此,强制文本编码器使用 FP32 推理运行可以消除这种输出差异。 有关详细信息,请参阅 此处。
FP16 推理代码
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) # can replace schnell with dev
# to run on low vram GPUs (i.e. between 4 and 32 GB VRAM)
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()
pipe.to(torch.float16) # casting here instead of in the pipeline constructor because doing so in the constructor loads all models into CPU memory at once
prompt = "A cat holding a sign that says hello world"
out = pipe(
prompt=prompt,
guidance_scale=0.,
height=768,
width=1360,
num_inference_steps=4,
max_sequence_length=256,
).images[0]
out.save("image.png")
Single File Loading for the FluxTransformer2DModel
FluxTransformer2DModel
支持加载 Black Forest Labs 发布的原始格式的检查点。 当尝试加载社区发布的模型的微调或量化版本时,这也很有用。
以下示例演示了如何在少于 16GB VRAM 的情况下运行 Flux。
首先安装 optimum-quanto
pip install optimum-quanto
然后运行以下示例
import torch
from diffusers import FluxTransformer2DModel, FluxPipeline
from transformers import T5EncoderModel, CLIPTextModel
from optimum.quanto import freeze, qfloat8, quantize
bfl_repo = "black-forest-labs/FLUX.1-dev"
dtype = torch.bfloat16
transformer = FluxTransformer2DModel.from_single_file("https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", torch_dtype=dtype)
quantize(transformer, weights=qfloat8)
freeze(transformer)
text_encoder_2 = T5EncoderModel.from_pretrained(bfl_repo, subfolder="text_encoder_2", torch_dtype=dtype)
quantize(text_encoder_2, weights=qfloat8)
freeze(text_encoder_2)
pipe = FluxPipeline.from_pretrained(bfl_repo, transformer=None, text_encoder_2=None, torch_dtype=dtype)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
prompt = "A cat holding a sign that says hello world"
image = pipe(
prompt,
guidance_scale=3.5,
output_type="pil",
num_inference_steps=20,
generator=torch.Generator("cpu").manual_seed(0)
).images[0]
image.save("flux-fp8-dev.png")
FluxPipeline
class diffusers.FluxPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None )
参数
- transformer (FluxTransformer2DModel) — 条件 Transformer (MMDiT) 架构,用于对编码后的图像潜在空间进行去噪。
- scheduler (FlowMatchEulerDiscreteScheduler) — 与
transformer
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。 - vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
- text_encoder (
CLIPTextModel
) — CLIP,特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 类的第二个分词器。
用于文本到图像生成的 Flux 管道。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 3.5 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
or tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示。 如果未定义,则必须传递 `prompt_embeds`。 - prompt_2 (
str
或List[str]
, 可选) — 要发送到 `tokenizer_2` 和 `text_encoder_2` 的提示。 如果未定义,则将使用 `prompt` 代替 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。 默认设置为 1024 以获得最佳效果。 - width (
int
, 可选, 默认值为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。 默认设置为 1024 以获得最佳效果。 - num_inference_steps (
int
, 可选, 默认值为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。 - sigmas (
List[float]
, 可选) — 用于去噪过程的自定义 sigmas,用于调度器,这些调度器在其set_timesteps
方法中支持sigmas
参数。 如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认值为 7.0) — Guidance scale,定义在 Classifier-Free Diffusion Guidance 中。guidance_scale
被定义为 Imagen Paper 的等式 2 中的w
。 通过设置guidance_scale > 1
启用 Guidance scale。 较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认值为 1) — 每个 prompt 生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的单个或列表形式的 torch generator。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声 latents,从高斯分布中采样,用作图像生成的输入。 可用于使用不同的 prompt 调整相同的生成。 如果未提供,将通过使用提供的随机generator
采样来生成 latents 张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 加权。 如果未提供,将从prompt
输入参数生成文本 embeddings。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的 pooled 文本 embeddings。 可用于轻松调整文本输入,例如 prompt 加权。 如果未提供,将从prompt
输入参数生成 pooled 文本 embeddings。 - ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP Adapters 一起使用的可选图像输入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP-Adapter 的预生成图像 embeddings。 它应该是一个列表,长度与 IP-adapters 的数量相同。 每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的张量。 如果未提供,则 embeddings 从ip_adapter_image
输入参数计算得出。 - negative_ip_adapter_image — (
PipelineImageInput
, 可选): 与 IP Adapters 一起使用的可选图像输入。 - negative_ip_adapter_image_embeds (
List[torch.Tensor]
, 可选) — IP-Adapter 的预生成图像 embeddings。 它应该是一个列表,长度与 IP-adapters 的数量相同。 每个元素都应该是一个形状为(batch_size, num_images, emb_dim)
的张量。 如果未提供,则 embeddings 从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 字典,如果指定,则传递给AttentionProcessor
,如 diffusers.models.attention_processor 中self.processor
下定义的那样。 - callback_on_step_end (
Callable
, 可选) — 在推理期间每个去噪步骤结束时调用的函数。 该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含由callback_on_step_end_tensor_inputs
指定的所有张量的列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。 列表中指定的张量将作为callback_kwargs
参数传递。 您将只能包含 pipeline 类的._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
默认值为 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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")
禁用 sliced VAE 解码。 如果之前启用了 enable_vae_slicing
,此方法将恢复为单步计算解码。
禁用 tiled VAE 解码。 如果之前启用了 enable_vae_tiling
,此方法将恢复为单步计算解码。
启用 sliced VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 slices 以分步计算解码。 这对于节省一些内存并允许更大的批量大小很有用。
启用 tiled VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 tiles 以分步计算解码和编码。 这对于节省大量内存并允许处理更大的图像很有用。
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或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: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: 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 类的第二个分词器。
用于图像修复的 Flux pipeline。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 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
,但如果直接传递潜在空间,则不会再次编码。 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素。默认设置为 1024 以获得最佳效果。 - width (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素。默认设置为 1024 以获得最佳效果。 - strength (
float
, 可选, 默认为 1.0) — 指示转换参考image
的程度。必须介于 0 和 1 之间。image
用作起点,strength
越高,添加的噪声就越多。去噪步骤的数量取决于最初添加的噪声量。当strength
为 1 时,添加的噪声最大,并且去噪过程将运行完整数量的迭代次数(在num_inference_steps
中指定)。值为 1 实质上会忽略image
。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多去噪步骤通常会以较慢的推理速度为代价,从而产生更高质量的图像。 - sigmas (
List[float]
, 可选) — 用于去噪过程的自定义 sigmas,与调度器一起使用,这些调度器在其set_timesteps
方法中支持sigmas
参数。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 7.0) — Guidance scale,定义于 Classifier-Free Diffusion Guidance。guidance_scale
定义为 Imagen Paper 中公式 2 的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个 prompt 生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成结果确定性的单个或 torch 生成器列表 torch generator(s)。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声 latents,从高斯分布中采样,用作图像生成的输入。可用于通过不同的 prompt 调整相同的生成。如果未提供,则将通过使用提供的随机generator
采样来生成 latents 张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从prompt
输入参数生成文本 embeddings。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的 pooled 文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从prompt
输入参数生成 pooled 文本 embeddings。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。 在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.flux.FluxPipelineOutput
而不是普通元组。 - joint_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给AttentionProcessor
,定义在 diffusers.models.attention_processor 中的self.processor
下。 - callback_on_step_end (
Callable
, 可选) — 一个函数,在推理期间的每个去噪步骤结束时调用。 该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量的列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。 您将只能包含在管道类的._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
默认为 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的 prompt - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的 prompt 或 prompts。 如果未定义,则prompt
将用于所有文本编码器 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从prompt
输入参数生成文本 embeddings。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的 pooled 文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从prompt
输入参数生成 pooled 文本 embeddings。 - lora_scale (
float
, 可选) — 一个 lora 缩放比例,如果加载了 LoRA 层,它将应用于文本编码器的所有 LoRA 层。
FluxInpaintPipeline
class diffusers.FluxInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel )
参数
- transformer (FluxTransformer2DModel) — 条件 Transformer (MMDiT) 架构,用于对编码的图像 latents 进行去噪。
- scheduler (FlowMatchEulerDiscreteScheduler) — 一个调度器,与
transformer
结合使用,以对编码的图像 latents 进行去噪。 - vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为 latent 表示形式以及从 latent 表示形式解码图像。
- text_encoder (
CLIPTextModel
) — CLIP,特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 类的第二个分词器。
用于图像修复的 Flux pipeline。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< 源代码 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 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
,但如果直接传递潜在表示,则不会再次编码。 - mask_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
,numpy 数组或张量,表示要遮罩image
的图像批次。蒙版中的白色像素会被重新绘制,而黑色像素会被保留。如果mask_image
是 PIL 图像,则在使用前会将其转换为单通道(亮度)。如果是 numpy 数组或 pytorch 张量,则应包含一个颜色通道 (L) 而不是 3 个,因此 pytorch 张量的预期形状为(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。而对于 numpy 数组,则为(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - mask_image_latent (
torch.Tensor
,List[torch.Tensor]
) —Tensor
,表示要遮罩由 VAE 生成的image
的图像批次。如果未提供,则遮罩潜在张量将由mask_image
生成。 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。 默认设置为 1024 以获得最佳效果。 - width (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。 默认设置为 1024 以获得最佳效果。 - padding_mask_crop (
int
, 可选, 默认为None
) — 要应用于图像和蒙版的裁剪边距大小。如果为None
,则不对图像和 mask_image 应用裁剪。 如果padding_mask_crop
不为None
,它将首先找到一个与图像宽高比相同的矩形区域,该区域包含所有蒙版区域,然后根据padding_mask_crop
扩展该区域。 然后将基于扩展区域裁剪图像和 mask_image,然后再调整大小为原始图像大小以进行图像修复。 当蒙版区域较小而图像较大且包含与图像修复无关的信息(例如背景)时,此功能很有用。 - strength (
float
, 可选, 默认为 1.0) — 指示转换参考image
的程度。必须介于 0 和 1 之间。image
用作起点,strength
越高,添加的噪声就越多。 去噪步骤的数量取决于最初添加的噪声量。 当strength
为 1 时,添加的噪声最大,去噪过程将运行num_inference_steps
中指定的完整迭代次数。 值为 1 本质上会忽略image
。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。 - sigmas (
List[float]
, 可选) — 自定义 sigmas,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程。 如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 7.0) — Guidance scale,如 Classifier-Free Diffusion Guidance 中定义。guidance_scale
定义为 Imagen Paper 等式 2 中的w
。 通过设置guidance_scale > 1
启用 Guidance scale。 较高的 guidance scale 鼓励生成与文本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 字典,如果指定,则会传递给AttentionProcessor
,如 diffusers.models.attention_processor 中self.processor
下定义的那样。 - callback_on_step_end (
Callable
, 可选) — 在推理期间的每个去噪步骤结束时调用的函数。 该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含callback_on_step_end_tensor_inputs
指定的所有张量的列表。 - callback_on_step_end_tensor_inputs (
List
, optional) — 用于callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
, 默认为 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或List[str]
, optional) — 要编码的提示词。 - prompt_2 (
str
或List[str]
, optional) — 要发送到tokenizer_2
和text_encoder_2
的提示词。如果未定义,则prompt
将用于所有文本编码器。 - device — (
torch.device
): torch 设备。 - num_images_per_prompt (
int
) — 每个提示词应生成的图像数量。 - prompt_embeds (
torch.FloatTensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - lora_scale (
float
, optional) — Lora 缩放比例,如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层。
FluxControlNetInpaintPipeline
class diffusers.FluxControlNetInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel controlnet: typing.Union[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel, typing.List[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel] )
参数
- transformer (FluxTransformer2DModel) — 条件 Transformer (MMDiT) 架构,用于对编码的图像潜在表示进行去噪。
- scheduler (FlowMatchEulerDiscreteScheduler) — 一个调度器,与
transformer
结合使用,以对编码的图像潜在表示进行去噪。 - vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示和从潜在表示解码。
- text_encoder (
CLIPTextModel
) — CLIP,特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 类的第二个分词器。
用于图像修复的 Flux controlnet 管线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 padding_mask_crop: typing.Optional[int] = None sigmas: typing.Optional[typing.List[float]] = None num_inference_steps: int = 28 guidance_scale: float = 7.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 control_mode: typing.Union[int, typing.List[int], NoneType] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, optional) — 用于引导图像生成的提示词。 - prompt_2 (
str
或List[str]
, optional) — 要发送到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
, optional) — 预生成的掩码图像潜在表示。 - 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]
, 可选) — 用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程的自定义 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) — 每个 prompt 生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch generator(s),用于使生成具有确定性。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompt 调整相同的生成结果。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。 - 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
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的 prompt - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的 prompt 或 prompts。如果未定义,则在所有文本编码器中使用prompt
- device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 lora 比例。
FluxControlNetImg2ImgPipeline
class diffusers.FluxControlNetImg2ImgPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel controlnet: typing.Union[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel, typing.List[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel], diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel] )
参数
- transformer (FluxTransformer2DModel) — 条件 Transformer (MMDiT) 架构,用于对编码后的图像潜在空间进行去噪。
- scheduler (FlowMatchEulerDiscreteScheduler) — 一个调度器,与
transformer
结合使用,以对编码后的图像潜在空间进行去噪。 - vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式。
- text_encoder (
CLIPTextModel
) — CLIP, 特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
) — T5, 特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) —CLIPTokenizer
类的分词器。 - tokenizer_2 (
T5TokenizerFast
) —T5TokenizerFast
类的第二个分词器。
用于图像到图像生成的 Flux controlnet 管线。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 control_mode: typing.Union[int, typing.List[int], NoneType] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 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
) — 要使用管线修改的图像。 - 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]
, 可选) — 用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程的自定义 sigmas。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 7.0) — Guidance scale,定义在 Classifier-Free Diffusion Guidance 中。 - 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
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或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: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: 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 的第二个分词器。
用于可控文本到图像生成的 Flux 管道。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 3.5 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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]]
): ControlNet 输入条件,为unet
的生成提供指导。如果类型指定为torch.Tensor
,则按原样传递给 ControlNet。PIL.Image.Image
也可以作为图像接受。输出图像的尺寸默认为image
的尺寸。如果传递了 height 和/或 width,则会相应地调整image
的大小。如果在init
中指定了多个 ControlNet,则必须将图像作为列表传递,以便列表中的每个元素都可以正确批量处理,以输入到单个 ControlNet。 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素。为了获得最佳效果,默认设置为 1024。 - width (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素。为了获得最佳效果,默认设置为 1024。 - 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。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成具有确定性的一个或多个 torch generator(s)。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将使用提供的随机generator
采样生成潜变量张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从prompt
输入参数生成池化文本嵌入。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.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
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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")
禁用 sliced VAE 解码。 如果之前启用了 enable_vae_slicing
,此方法将恢复为单步计算解码。
禁用 tiled VAE 解码。 如果之前启用了 enable_vae_tiling
,此方法将恢复为单步计算解码。
启用 sliced VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 slices 以分步计算解码。 这对于节省一些内存并允许更大的批量大小很有用。
启用 tiled VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 tiles 以分步计算解码和编码。 这对于节省大量内存并允许处理更大的图像很有用。
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或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
class diffusers.FluxControlImg2ImgPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: 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 的第二个分词器。
用于图像修复的 Flux pipeline。
参考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 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]]
): ControlNet 输入条件,为生成向unet
提供指导。如果类型指定为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]
, 可选) — 自定义 sigma 值,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选,默认为 7.0) — Guidance scale,定义于 Classifier-Free Diffusion Guidance 中。guidance_scale
定义为 Imagen Paper 等式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常会以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选,默认为 1) — 每个 prompt 生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或一组 torch generator(s),用于使生成过程确定。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声 latents,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompts 微调相同的生成。如果未提供,将使用提供的随机generator
采样生成 latents 张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成文本 embeddings。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的 pooled 文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成 pooled 文本 embeddings。 - output_type (
str
, 可选,默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回~pipelines.flux.FluxPipelineOutput
而不是普通元组。 - joint_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则作为AttentionProcessor
传递,定义在 diffusers.models.attention_processor 中的self.processor
下。 - callback_on_step_end (
Callable
, 可选) — 一个函数,在推理期间的每个去噪步骤结束时调用。该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包含由callback_on_step_end_tensor_inputs
指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
默认为 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或List[str]
, 可选) — 要编码的 prompt - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的 prompt 或 prompts。如果未定义,则prompt
用于所有文本编码器 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成文本 embeddings。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的 pooled 文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从prompt
输入参数生成 pooled 文本 embeddings。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 lora 缩放比例。
FluxPriorReduxPipeline
class diffusers.FluxPriorReduxPipeline
< source >( image_encoder: SiglipVisionModel feature_extractor: SiglipImageProcessor image_embedder: ReduxImageEncoder text_encoder: CLIPTextModel = None tokenizer: CLIPTokenizer = None text_encoder_2: T5EncoderModel = None tokenizer_2: T5TokenizerFast = None )
参数
- image_encoder (
SiglipVisionModel
) — SIGLIP 视觉模型,用于编码输入图像。 - feature_extractor (
SiglipImageProcessor
) — 用于预处理 SIGLIP 模型图像的图像处理器。 - image_embedder (
ReduxImageEncoder
) — Redux 图像编码器,用于处理 SIGLIP embeddings。 - text_encoder (
CLIPTextModel
, 可选) — CLIP,特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
, 可选) — T5,特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
, 可选) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
T5TokenizerFast
, 可选) — T5TokenizerFast 类的第二个分词器。
用于图像到图像生成的 Flux Redux 管道。
参考: https://blackforestlabs.ai/flux-1-tools/
__call__
< source >( 图像: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] 提示语: typing.Union[str, typing.List[str]] = None 提示语_2: typing.Union[str, typing.List[str], NoneType] = None 提示语嵌入: typing.Optional[torch.FloatTensor] = None 池化提示语嵌入: typing.Optional[torch.FloatTensor] = None 提示语嵌入缩放: typing.Union[float, typing.List[float], NoneType] = 1.0 池化提示语嵌入缩放: typing.Union[float, typing.List[float], NoneType] = 1.0 返回字典: bool = True ) → ~pipelines.flux.FluxPriorReduxPipelineOutput
或 tuple
参数
- image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
,numpy 数组或 tensor,表示用作起点的图像批次。对于 numpy 数组和 pytorch tensor,期望值范围在[0, 1]
之间。如果它是 tensor 或 tensor 列表,则期望的形状应为(B, C, H, W)
或(C, H, W)
。如果它是 numpy 数组或数组列表,则期望的形状应为(B, H, W, C)
或(H, W, C)
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示语。实验性功能:要使用此功能,请确保显式加载文本编码器到 pipeline 中。如果未加载文本编码器,则提示语将被忽略。 - prompt_2 (
str
或List[str]
, 可选) — 要发送到tokenizer_2
和text_encoder_2
的提示语。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示语权重。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的池化文本嵌入。 - 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: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或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: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: 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 的第二个分词器。
用于图像修复/外绘的 Flux Fill pipeline。
参考: https://blackforestlabs.ai/flux-1-tools/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Optional[torch.FloatTensor] = None mask_image: typing.Optional[torch.FloatTensor] = None masked_image_latents: typing.Optional[torch.FloatTensor] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 30.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
或 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) 而不是 3 个,因此 pytorch 张量的期望形状为(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。而 numpy 数组的期望形状为(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - mask_image_latent (
torch.Tensor
,List[torch.Tensor]
) —Tensor
,表示要遮罩 VAE 生成的image
的图像批次。如果未提供,则遮罩潜在张量将由mask_image
生成。 - height (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度像素。默认设置为 1024 以获得最佳效果。 - width (
int
, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度像素。默认设置为 1024 以获得最佳效果。 - num_inference_steps (
int
, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。 - sigmas (
List[float]
, 可选) — 自定义 sigmas,用于支持在其set_timesteps
方法中使用sigmas
参数的调度器的去噪过程。如果未定义,则将使用传递num_inference_steps
时的默认行为。 - guidance_scale (
float
, 可选, 默认为 7.0) — Guidance scale,定义在 Classifier-Free Diffusion Guidance 中。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以降低图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或一组 torch generator(s) 以使生成具有确定性。 - latents (
torch.FloatTensor
, 可选) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则将通过使用提供的随机generator
进行采样来生成潜在张量。 - prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - pooled_prompt_embeds (
torch.FloatTensor
, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成池化文本嵌入。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回~pipelines.flux.FluxPipelineOutput
而不是普通元组。 - joint_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给AttentionProcessor
,如 diffusers.models.attention_processor 中的self.processor
下所定义。 - callback_on_step_end (
Callable
, 可选) — 在推理期间的每个去噪步骤结束时调用的函数。该函数使用以下参数调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
将包括callback_on_step_end_tensor_inputs
指定的所有张量的列表。 - callback_on_step_end_tensor_inputs (
List
, 可选) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您将只能包含管道类._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
默认为 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 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")
禁用 sliced VAE 解码。 如果之前启用了 enable_vae_slicing
,此方法将恢复为单步计算解码。
禁用 tiled VAE 解码。 如果之前启用了 enable_vae_tiling
,此方法将恢复为单步计算解码。
启用 sliced VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 slices 以分步计算解码。 这对于节省一些内存并允许更大的批量大小很有用。
启用 tiled VAE 解码。 启用此选项后,VAE 会将输入张量拆分为 tiles 以分步计算解码和编码。 这对于节省大量内存并允许处理更大的图像很有用。
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
参数
- prompt (
str
或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
, optional) — 预生成的文本嵌入。 可用于轻松调整文本输入,例如,提示权重。 如果未提供,将从prompt
输入参数生成文本嵌入。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的池化文本嵌入。 可用于轻松调整文本输入,例如,提示权重。 如果未提供,将从prompt
输入参数生成池化文本嵌入。 - lora_scale (
float
, optional) — 一个 lora 缩放比例,如果加载了 LoRA 层,它将应用于文本编码器的所有 LoRA 层。