Diffusers 文件
Flux
並獲得增強的文件體驗
開始使用
Flux
Flux 是一系列基於擴散變換器的文字到影像生成模型。要了解更多關於 Flux 的資訊,請檢視 Flux 的建立者 Black Forest Labs 釋出的原始部落格文章。
Flux 的原始模型檢查點可以在這裡找到。原始推理程式碼可以在這裡找到。
Flux 在消費級硬體裝置上執行可能會非常昂貴。但是,您可以執行一系列最佳化,使其執行更快,並以更節省記憶體的方式執行。有關更多詳細資訊,請檢視此部分。此外,Flux 可以受益於量化以提高記憶體效率,但會犧牲推理延遲。請參閱此部落格文章瞭解更多資訊。有關資源的詳盡列表,請檢視此要點。
Flux 提供以下變體:
模型型別 | 模型 ID |
---|---|
時間步長蒸餾 | black-forest-labs/FLUX.1-schnell |
引導蒸餾 | black-forest-labs/FLUX.1-dev |
填充修復/外畫(引導蒸餾) | black-forest-labs/FLUX.1-Fill-dev |
Canny 控制(引導蒸餾) | black-forest-labs/FLUX.1-Canny-dev |
深度控制(引導蒸餾) | black-forest-labs/FLUX.1-Depth-dev |
Canny 控制 (LoRA) | black-forest-labs/FLUX.1-Canny-dev-lora |
深度控制 (LoRA) | black-forest-labs/FLUX.1-Depth-dev-lora |
Redux(介面卡) | black-forest-labs/FLUX.1-Redux-dev |
所有檢查點都有不同的用法,我們將在下面詳細介紹。
時間步長蒸餾
max_sequence_length
不能超過 256。guidance_scale
需設定為 0。- 由於這是一個時間步長蒸餾模型,因此它受益於更少的取樣步長。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "A cat holding a sign that says hello world"
out = pipe(
prompt=prompt,
guidance_scale=0.,
height=768,
width=1360,
num_inference_steps=4,
max_sequence_length=256,
).images[0]
out.save("image.png")
引導蒸餾
- 引導蒸餾變體需要大約 50 個取樣步驟才能生成高質量影像。
- 它對
max_sequence_length
沒有任何限制。
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "a tiny astronaut hatching from an egg on the moon"
out = pipe(
prompt=prompt,
guidance_scale=3.5,
height=768,
width=1360,
num_inference_steps=50,
).images[0]
out.save("image.png")
填充修復/外畫
- Flux Fill 管道不需要像常規影像修復管道那樣將
strength
作為輸入。 - 它同時支援影像修復和外畫。
import torch
from diffusers import FluxFillPipeline
from diffusers.utils import load_image
image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png")
mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png")
repo_id = "black-forest-labs/FLUX.1-Fill-dev"
pipe = FluxFillPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to("cuda")
image = pipe(
prompt="a white paper cup",
image=image,
mask_image=mask,
height=1632,
width=1232,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0)
).images[0]
image.save(f"output.png")
Canny 控制
注意:black-forest-labs/Flux.1-Canny-dev
不是 ControlNetModel 模型。ControlNet 模型是 UNet/Transformer 的獨立元件,其殘差被新增到實際的基礎模型中。Canny Control 是一種替代架構,透過使用通道級串聯和輸入控制條件,並確保 Transformer 儘可能緊密地遵循條件來學習結構控制,從而達到與 ControlNet 模型相同的效果。
# !pip install -U controlnet-aux
import torch
from controlnet_aux import CannyDetector
from diffusers import FluxControlPipeline
from diffusers.utils import load_image
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16).to("cuda")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=50,
guidance_scale=30.0,
).images[0]
image.save("output.png")
Canny 控制也可以透過此條件的 LoRA 變體實現。用法如下:
# !pip install -U controlnet-aux
import torch
from controlnet_aux import CannyDetector
from diffusers import FluxControlPipeline
from diffusers.utils import load_image
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Canny-dev-lora")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = CannyDetector()
control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024)
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=50,
guidance_scale=30.0,
).images[0]
image.save("output.png")
深度控制
注意:black-forest-labs/Flux.1-Depth-dev
不是一個 ControlNet 模型。ControlNetModel 模型是 UNet/Transformer 的獨立元件,其殘差被新增到實際的基礎模型中。深度控制是一種替代架構,透過使用通道級串聯和輸入控制條件,並確保 Transformer 儘可能緊密地遵循條件來學習結構控制,從而達到與 ControlNet 模型相同的效果。
# !pip install git+https://github.com/huggingface/image_gen_aux
import torch
from diffusers import FluxControlPipeline, FluxTransformer2DModel
from diffusers.utils import load_image
from image_gen_aux import DepthPreprocessor
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Depth-dev", torch_dtype=torch.bfloat16).to("cuda")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=30,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
深度控制也可以透過此條件的 LoRA 變體實現。用法如下:
# !pip install git+https://github.com/huggingface/image_gen_aux
import torch
from diffusers import FluxControlPipeline, FluxTransformer2DModel
from diffusers.utils import load_image
from image_gen_aux import DepthPreprocessor
pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora")
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=30,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
Redux
- Flux Redux 管道是 FLUX.1 基礎模型的介面卡。它可以與 flux-dev 和 flux-schnell 一起用於影像到影像生成。
- 您可以先使用
FluxPriorReduxPipeline
獲取prompt_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")
將 Flux Turbo LoRA 與 Flux Control、Fill 和 Redux 結合使用
我們可以將 Flux Turbo LoRA 與 Flux Control 和其他管道(如 Fill 和 Redux)結合使用,以實現少量步驟的推理。下面的示例展示瞭如何對深度和來自 ByteDance/Hyper-SD
的 Turbo LoRA 的 Flux Control LoRA 執行此操作。
from diffusers import FluxControlPipeline
from image_gen_aux import DepthPreprocessor
from diffusers.utils import load_image
from huggingface_hub import hf_hub_download
import torch
control_pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
control_pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora", adapter_name="depth")
control_pipe.load_lora_weights(
hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"), adapter_name="hyper-sd"
)
control_pipe.set_adapters(["depth", "hyper-sd"], adapter_weights=[0.85, 0.125])
control_pipe.enable_model_cpu_offload()
prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(control_image)[0].convert("RGB")
image = control_pipe(
prompt=prompt,
control_image=control_image,
height=1024,
width=1024,
num_inference_steps=8,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
image.save("output.png")
使用 Flux LoRA 時關於 unload_lora_weights() 的注意事項
解除安裝 Control LoRA 權重時,請呼叫 pipe.unload_lora_weights(reset_to_overwritten_params=True)
以將 pipe.transformer
完全重置回其原始形式。然後可以將生成的管道與 DiffusionPipeline.from_pipe() 等方法一起使用。有關此引數的更多詳細資訊,請參閱 此 PR。
IP-Adapter
請檢視IP-Adapter以瞭解 IP-Adapter 的工作原理。
IP-Adapter 允許您除了文字提示外,還使用影像來提示 Flux。當描述僅透過文字難以表達的複雜概念,並且您有參考影像時,這尤其有用。
import torch
from diffusers import FluxPipeline
from diffusers.utils import load_image
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
).to("cuda")
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux_ip_adapter_input.jpg").resize((1024, 1024))
pipe.load_ip_adapter(
"XLabs-AI/flux-ip-adapter",
weight_name="ip_adapter.safetensors",
image_encoder_pretrained_model_name_or_path="openai/clip-vit-large-patch14"
)
pipe.set_ip_adapter_scale(1.0)
image = pipe(
width=1024,
height=1024,
prompt="wearing sunglasses",
negative_prompt="",
true_cfg_scale=4.0,
generator=torch.Generator().manual_seed(4444),
ip_adapter_image=image,
).images[0]
image.save('flux_ip_adapter_output.jpg')

最佳化
Flux 是一個非常大的模型,載入所有模型元件需要大約 50GB 的 RAM/VRAM。啟用以下一些最佳化以降低記憶體要求。
組解除安裝
組解除安裝 透過解除安裝內部層組而不是整個模型或權重來降低 VRAM 使用。您需要在管道的所有模型元件上使用 apply_group_offloading()。offload_type
引數允許您在塊級和葉級解除安裝之間切換。將其設定為 leaf_level
會將最低葉級引數解除安裝到 CPU,而不是在模組級別解除安裝。
在支援非同步資料流的 CUDA 裝置上,設定 use_stream=True
可重疊資料傳輸和計算以加速推理。
可以在管道的不同元件中混合使用塊級和葉級解除安裝。
import torch
from diffusers import FluxPipeline
from diffusers.hooks import apply_group_offloading
model_id = "black-forest-labs/FLUX.1-dev"
dtype = torch.bfloat16
pipe = FluxPipeline.from_pretrained(
model_id,
torch_dtype=dtype,
)
apply_group_offloading(
pipe.transformer,
offload_type="leaf_level",
offload_device=torch.device("cpu"),
onload_device=torch.device("cuda"),
use_stream=True,
)
apply_group_offloading(
pipe.text_encoder,
offload_device=torch.device("cpu"),
onload_device=torch.device("cuda"),
offload_type="leaf_level",
use_stream=True,
)
apply_group_offloading(
pipe.text_encoder_2,
offload_device=torch.device("cpu"),
onload_device=torch.device("cuda"),
offload_type="leaf_level",
use_stream=True,
)
apply_group_offloading(
pipe.vae,
offload_device=torch.device("cpu"),
onload_device=torch.device("cuda"),
offload_type="leaf_level",
use_stream=True,
)
prompt="A cat wearing sunglasses and working as a lifeguard at pool."
generator = torch.Generator().manual_seed(181201)
image = pipe(
prompt,
width=576,
height=1024,
num_inference_steps=30,
generator=generator
).images[0]
image
執行 FP16 推理
Flux 可以使用 FP16(即加速 Turing/Volta GPU 上的推理)生成高質量影像,但與 FP32/BF16 相比,會產生不同的輸出。問題在於文字編碼器中的某些啟用在 FP16 中執行時必須被剪裁,這會影響整體影像。因此,強制文字編碼器使用 FP32 推理可以消除這種輸出差異。有關詳細資訊,請參閱此處。
FP16 推理程式碼
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) # can replace schnell with dev
# to run on low vram GPUs (i.e. between 4 and 32 GB VRAM)
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()
pipe.to(torch.float16) # casting here instead of in the pipeline constructor because doing so in the constructor loads all models into CPU memory at once
prompt = "A cat holding a sign that says hello world"
out = pipe(
prompt=prompt,
guidance_scale=0.,
height=768,
width=1360,
num_inference_steps=4,
max_sequence_length=256,
).images[0]
out.save("image.png")
量化
量化有助於透過以較低精度資料型別儲存模型權重來減少大型模型的記憶體需求。但是,量化對影片質量的影響可能因影片模型而異。
請參閱量化概述,瞭解有關支援的量化後端以及選擇適合您用例的量化後端的更多資訊。以下示例演示瞭如何使用 bitsandbytes 載入量化的 FluxPipeline 進行推理。
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel
quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="text_encoder_2",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev",
subfolder="transformer",
quantization_config=quant_config,
torch_dtype=torch.float16,
)
pipeline = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
text_encoder_2=text_encoder_8bit,
transformer=transformer_8bit,
torch_dtype=torch.float16,
device_map="balanced",
)
prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt, guidance_scale=3.5, height=768, width=1360, num_inference_steps=50).images[0]
image.save("flux.png")
FluxTransformer2DModel 的單一檔案載入
FluxTransformer2DModel
支援載入 Black Forest Labs 提供的原始格式的檢查點。當嘗試載入社群釋出的模型的微調或量化版本時,這也很有用。
以下示例演示瞭如何使用小於 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) — 用於對編碼影像潛在進行去噪的條件變換器(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
或 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) — 當 > 1.0 且提供了negative_prompt
時,啟用真正的無分類器引導。 - height (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。為了獲得最佳效果,預設設定為 1024。 - width (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。為了獲得最佳效果,預設設定為 1024。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。 - sigmas (
List[float]
, 可選) — 在去噪過程中使用排程器(支援set_timesteps
方法中的sigmas
引數)的自定義 sigma 值。如果未定義,將使用傳入num_inference_steps
時的預設行為。 - guidance_scale (
float
, 可選, 預設為 3.5) — 無分類器擴散引導 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例會促使生成與文字prompt
緊密相關的影像,但通常會犧牲影像質量。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch generator(s),用於使生成具有確定性。 - latents (
torch.FloatTensor
, 可選) — 預先生成的噪聲潛在變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,將使用提供的隨機generator
進行取樣以生成潛在張量。 - prompt_embeds (
torch.FloatTensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.FloatTensor
, 可選) — 預先生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP Adapter 的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預先生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - negative_ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP Adapters 的可選影像輸入。 - negative_ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預先生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - negative_prompt_embeds (
torch.FloatTensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.FloatTensor
, 可選) — 預先生成的負面池化文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,池化negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.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
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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")
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
encode_prompt
< 源 >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
引數
- prompt (
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
< 源 >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None )
引數
- transformer (FluxTransformer2DModel) — 用於去噪編碼影像潛在變數的條件 Transformer (MMDiT) 架構。
- scheduler (FlowMatchEulerDiscreteScheduler) — 與
transformer
結合使用的排程器,用於去噪編碼影像潛在變數。 - vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (
CLIPTextModel
) — CLIP,特別是 clip-vit-large-patch14 變體。 - text_encoder_2 (
T5EncoderModel
) — T5,特別是 google/t5-v1_1-xxl 變體。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 類的分詞器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 類的第二個分詞器。
用於影像修復的 Flux 管道。
參考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< 源 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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]
) — 用作起點的影像、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
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預先生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-adapter 數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,則從ip_adapter_image
輸入引數計算嵌入。 - negative_ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - negative_ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預先生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-adapter 數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,則從ip_adapter_image
輸入引數計算嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在 PIL:PIL.Image.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
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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]
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
encode_prompt
< 來源 >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
引數
- prompt (
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
< 來源 >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None )
引數
- transformer (FluxTransformer2DModel) — 用於對編碼影像潛在表示進行去噪的條件 Transformer (MMDiT) 架構。
- scheduler (FlowMatchEulerDiscreteScheduler) — 與
transformer
結合使用的排程器,用於對編碼影像潛在表示進行去噪。 - vae (AutoencoderKL) — 變分自動編碼器 (VAE) 模型,用於編碼和解碼影像到潛在表示和從潛在表示中解碼影像。
- text_encoder (
CLIPTextModel
) — CLIP,特別是 clip-vit-large-patch14 變體。 - text_encoder_2 (
T5EncoderModel
) — T5,特別是 google/t5-v1_1-xxl 變體。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 類的分詞器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 類的第二個分詞器。
用於影像修復的 Flux 管道。
參考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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]
) — 用作起點的影像、Numpy 陣列或表示影像批次的張量。對於 Numpy 陣列和 PyTorch 張量,預期值範圍在[0, 1]
之間。如果它是張量或張量列表,則預期形狀應為(B, C, H, W)
或(C, H, W)
。如果它是 Numpy 陣列或陣列列表,則預期形狀應為(B, H, W, C)
或(H, W, C)
。它也可以接受影像潛在表示作為image
,但如果直接傳遞潛在表示,則不會再次編碼。 - mask_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) — 用於遮蓋image
的影像、Numpy 陣列或表示影像批次的張量。遮罩中白色畫素的部分將被重新繪製,而黑色畫素的部分將被保留。如果mask_image
是 PIL 影像,則在使用前會轉換為單通道(亮度)。如果它是 Numpy 陣列或 PyTorch 張量,則應包含一個顏色通道(L)而不是 3 個,因此 PyTorch 張量的預期形狀為(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。而 Numpy 陣列的預期形狀為(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - mask_image_latent (
torch.Tensor
,List[torch.Tensor]
) — 表示由 VAE 生成的用於遮蓋image
的影像批次的Tensor
。如果未提供,遮罩潛在張量將由mask_image
生成。 - height (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳結果,預設為 1024。 - width (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳結果,預設為 1024。 - padding_mask_crop (
int
, 可選, 預設為None
) — 應用於影像和遮罩的裁剪邊距大小。如果為None
,則不對影像和mask_image
應用裁剪。如果padding_mask_crop
不為None
,它將首先找到與影像寬高比相同且包含所有遮罩區域的矩形區域,然後根據padding_mask_crop
擴充套件該區域。然後將根據擴充套件區域裁剪影像和mask_image
,再調整大小到原始影像大小以進行修復。當遮罩區域較小而影像較大且包含與修復無關的資訊(例如背景)時,這很有用。 - strength (
float
, 可選, 預設為 1.0) — 表示轉換參考image
的程度。必須在 0 到 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步數取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的完整迭代次數。值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於其set_timesteps
方法支援sigmas
引數的排程器。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - guidance_scale (
float
, 可選, 預設為 7.0) — 如 Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
來啟用引導比例。更高的引導比例會促使生成與文字prompt
更緊密相關的影像,通常以犧牲影像質量為代價。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示要生成的影像數量。 - generator (
torch.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 介面卡配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — IP-Adapter 預生成的影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - negative_ip_adapter_image — (
PipelineImageInput
, 可選):用於與 IP 介面卡配合使用的可選影像輸入。 - negative_ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — IP-Adapter 預生成的影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在 PIL:PIL.Image.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
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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]
, 可選) — 要編碼的提示 - 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: 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.Optional[torch.FloatTensor] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 padding_mask_crop: typing.Optional[int] = None sigmas: typing.Optional[typing.List[float]] = None num_inference_steps: int = 28 guidance_scale: float = 7.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 control_mode: typing.Union[int, typing.List[int], NoneType] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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
) — 要進行影像修復的影像。 - 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
引數的排程器一起用於去噪過程的自定義 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 的輸出乘以controlnet_conditioning_scale
,然後新增到原始 Transformer 的殘差中。 - 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
, optional, defaults toTrue
) — 是否返回~pipelines.flux.FluxPipelineOutput
物件,而不是普通元組。 - joint_attention_kwargs (
dict
, optional) — 要傳遞給聯合注意力機制的附加關鍵字引數。 - callback_on_step_end (
Callable
, optional) — 推理過程中在每個去噪步驟結束時呼叫的函式。 - callback_on_step_end_tensor_inputs (
List[str]
, optional) —callback_on_step_end
函式的張量輸入列表。 - max_sequence_length (
int
, optional, defaults to 512) — 要生成的序列的最大長度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.flux.FluxPipelineOutput
,否則返回 tuple
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> import torch
>>> from diffusers import FluxControlNetInpaintPipeline
>>> from diffusers.models import FluxControlNetModel
>>> from diffusers.utils import load_image
>>> controlnet = FluxControlNetModel.from_pretrained(
... "InstantX/FLUX.1-dev-controlnet-canny", torch_dtype=torch.float16
... )
>>> pipe = FluxControlNetInpaintPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> control_image = load_image(
... "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
... )
>>> init_image = load_image(
... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
... )
>>> mask_image = load_image(
... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
... )
>>> prompt = "A girl holding a sign that says InstantX"
>>> image = pipe(
... prompt,
... image=init_image,
... mask_image=mask_image,
... control_image=control_image,
... control_guidance_start=0.2,
... control_guidance_end=0.8,
... controlnet_conditioning_scale=0.7,
... strength=0.7,
... num_inference_steps=28,
... guidance_scale=3.5,
... ).images[0]
>>> image.save("flux_controlnet_inpaint.png")
encode_prompt
< 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
orList[str]
, optional) — 要編碼的提示。 - prompt_2 (
str
orList[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 比例。
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
or tuple
引數
- prompt (
str
orList[str]
, optional) — 用於指導影像生成的提示。 - prompt_2 (
str
orList[str]
, optional) — 要傳送給tokenizer_2
和text_encoder_2
的提示。 - image (
PIL.Image.Image
orList[PIL.Image.Image]
ortorch.FloatTensor
) — 要透過管線修改的影像。 - control_image (
PIL.Image.Image
orList[PIL.Image.Image]
ortorch.FloatTensor
) — ControlNet 輸入條件。用於控制生成的影像。 - height (
int
, optional, defaults to self.default_sample_size * self.vae_scale_factor) — 生成影像的畫素高度。 - width (
int
, optional, defaults to self.default_sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。 - strength (
float
, optional, defaults to 0.6) — 概念上表示對參考image
進行轉換的程度。必須介於 0 和 1 之間。 - num_inference_steps (
int
, optional, defaults to 28) — 去噪步驟的數量。更多的去噪步驟通常會生成更高質量的影像,但推理速度會變慢。 - sigmas (
List[float]
, optional) — 自定義 sigma,用於支援sigmas
引數的排程器進行去噪。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - guidance_scale (
float
, optional, defaults to 7.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。 - control_mode (
int
orList[int]
, optional) — ControlNet 的模式。如果使用多個 ControlNet,則應為一個列表。 - controlnet_conditioning_scale (
float
orList[float]
, optional, defaults to 1.0) — ControlNet 的輸出乘以controlnet_conditioning_scale
後新增到原始 transformer 中的殘差。 - num_images_per_prompt (
int
, optional, defaults to 1) — 每個提示要生成的影像數量。 - generator (
torch.Generator
orList[torch.Generator]
, optional) — 一個或多個 torch 生成器,用於使生成確定性。 - latents (
torch.FloatTensor
, optional) — 預生成的噪聲潛在,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示調整相同生成。 - prompt_embeds (
torch.FloatTensor
, optional) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 預生成的池化文字嵌入。 - output_type (
str
, optional, defaults to"pil"
) — 生成影像的輸出格式。在PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回~pipelines.flux.FluxPipelineOutput
物件,而不是普通元組。 - joint_attention_kwargs (
dict
, optional) — 要傳遞給聯合注意力機制的附加關鍵字引數。 - callback_on_step_end (
Callable
, optional) — 推理過程中在每個去噪步驟結束時呼叫的函式。 - callback_on_step_end_tensor_inputs (
List[str]
, optional) —callback_on_step_end
函式的張量輸入列表。 - max_sequence_length (
int
, optional, defaults to 512) — 要生成的序列的最大長度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.flux.FluxPipelineOutput
,否則返回 tuple
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> import torch
>>> from diffusers import FluxControlNetImg2ImgPipeline, FluxControlNetModel
>>> from diffusers.utils import load_image
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> controlnet = FluxControlNetModel.from_pretrained(
... "InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16
... )
>>> pipe = FluxControlNetImg2ImgPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.text_encoder.to(torch.float16)
>>> pipe.controlnet.to(torch.float16)
>>> pipe.to("cuda")
>>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
>>> init_image = load_image(
... "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
... )
>>> prompt = "A girl in city, 25 years old, cool, futuristic"
>>> image = pipe(
... prompt,
... image=init_image,
... control_image=control_image,
... control_guidance_start=0.2,
... control_guidance_end=0.8,
... controlnet_conditioning_scale=1.0,
... strength=0.7,
... num_inference_steps=2,
... guidance_scale=3.5,
... ).images[0]
>>> image.save("flux_controlnet_img2img.png")
encode_prompt
< 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
orList[str]
, optional) — 要編碼的提示。 - prompt_2 (
str
orList[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 比例。
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__
< 來源 >( 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
或 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
的尺寸。如果傳遞了 height 和/或 width,則image
會相應地調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確批處理以輸入到單個 ControlNet。 - height (
int
,可選,預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳效果,預設設定為 1024。 - width (
int
,可選,預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳效果,預設設定為 1024。 - num_inference_steps (
int
,可選,預設為 50) — 去噪步數。通常,去噪步數越多,影像質量越高,但推理速度越慢。 - sigmas (
List[float]
,可選) — 用於去噪過程的自定義 sigmas,與排程器結合使用,排程器在其set_timesteps
方法中支援sigmas
引數。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - guidance_scale (
float
,可選,預設為 3.5) — 如 Classifier-Free Diffusion Guidance 中定義的指導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用指導比例。更高的指導比例會促使生成與文字prompt
緊密相關的影像,但通常會犧牲影像質量。 - num_images_per_prompt (
int
,可選,預設為 1) — 每個提示詞生成的影像數量。 - generator (
torch.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
如果 return_dict
為 True,則返回 ~pipelines.flux.FluxPipelineOutput
,否則返回 tuple
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> import torch
>>> from controlnet_aux import CannyDetector
>>> from diffusers import FluxControlPipeline
>>> from diffusers.utils import load_image
>>> pipe = FluxControlPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16
... ).to("cuda")
>>> prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
>>> control_image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png"
... )
>>> processor = CannyDetector()
>>> control_image = processor(
... control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024
... )
>>> image = pipe(
... prompt=prompt,
... control_image=control_image,
... height=1024,
... width=1024,
... num_inference_steps=50,
... guidance_scale=30.0,
... ).images[0]
>>> image.save("output.png")
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
encode_prompt
< 來源 >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
引數
- prompt (
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
< 來源 >( 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__
< 源 >( 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]
) — 用作起點的影像、numpy 陣列或表示影像批次的張量。對於 numpy 陣列和 pytorch 張量,預期值範圍在[0, 1]
之間。如果是張量或張量列表,則預期形狀應為(B, C, H, W)
或(C, H, W)
。如果是 numpy 陣列或陣列列表,則預期形狀應為(B, H, W, C)
或(H, W, C)
。它也可以接受影像潛在表示作為image
,但如果直接傳遞潛在表示,則不會再次編碼。 - control_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): ControlNet 輸入條件,用於為unet
提供生成指導。如果型別指定為torch.Tensor
,則按原樣傳遞給 ControlNet。PIL.Image.Image
也可以作為影像接受。輸出影像的尺寸預設為image
的尺寸。如果傳遞了 height 和/或 width,則image
會相應地調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確批處理以輸入到單個 ControlNet。 - height (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的高度(畫素)。預設設定為 1024 以獲得最佳效果。 - width (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的寬度(畫素)。預設設定為 1024 以獲得最佳效果。 - strength (
float
, 可選, 預設為 1.0) — 表示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的全部迭代次數。值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於其set_timesteps
方法支援sigmas
引數的排程器。如果未定義,則將使用傳遞num_inference_steps
時的預設行為。 - guidance_scale (
float
, 可選, 預設為 7.0) — 如 Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 方程 2 中的w
。透過設定guidance_scale > 1
來啟用引導比例。更高的引導比例會鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示生成的影像數量。 - generator (
torch.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
如果 return_dict
為 True,則返回 ~pipelines.flux.FluxPipelineOutput
,否則返回 tuple
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> import torch
>>> from controlnet_aux import CannyDetector
>>> from diffusers import FluxControlImg2ImgPipeline
>>> from diffusers.utils import load_image
>>> pipe = FluxControlImg2ImgPipeline.from_pretrained(
... "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16
... ).to("cuda")
>>> prompt = "A robot made of exotic candies and chocolates of different kinds. Abstract background"
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/watercolor-painting.jpg"
... )
>>> control_image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png"
... )
>>> processor = CannyDetector()
>>> control_image = processor(
... control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024
... )
>>> image = pipe(
... prompt=prompt,
... image=image,
... control_image=control_image,
... strength=0.8,
... height=1024,
... width=1024,
... num_inference_steps=50,
... guidance_scale=30.0,
... ).images[0]
>>> image.save("output.png")
encode_prompt
< 源 >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None max_sequence_length: int = 512 lora_scale: typing.Optional[float] = None )
引數
- prompt (
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
< 源 >( image_encoder: SiglipVisionModel feature_extractor: SiglipImageProcessor image_embedder: ReduxImageEncoder text_encoder: CLIPTextModel = None tokenizer: CLIPTokenizer = None text_encoder_2: T5EncoderModel = None tokenizer_2: T5TokenizerFast = None )
引數
- image_encoder (
SiglipVisionModel
) — 用於編碼輸入影像的 SIGLIP 視覺模型。 - feature_extractor (
SiglipImageProcessor
) — 用於對 SIGLIP 模型影像進行預處理的影像處理器。 - image_embedder (
ReduxImageEncoder
) — 用於處理 SIGLIP 嵌入的 Redux 影像編碼器。 - text_encoder (
CLIPTextModel
, 可選) — CLIP,特別是 clip-vit-large-patch14 變體。 - text_encoder_2 (
T5EncoderModel
, 可選) — T5,特別是 google/t5-v1_1-xxl 變體。 - tokenizer (
CLIPTokenizer
, 可選) — CLIPTokenizer 類的分詞器。 - tokenizer_2 (
T5TokenizerFast
, 可選) — T5TokenizerFast 類的第二個分詞器。
用於影像到影像生成的 Flux Redux 管道。
參考:https://blackforestlabs.ai/flux-1-tools/
__call__
< 源 >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None prompt_embeds_scale: typing.Union[float, typing.List[float], NoneType] = 1.0 pooled_prompt_embeds_scale: typing.Union[float, typing.List[float], NoneType] = 1.0 return_dict: bool = True ) → ~pipelines.flux.FluxPriorReduxPipelineOutput
或 tuple
引數
- image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) — 用作起點的影像、numpy 陣列或表示影像批次的張量。對於 numpy 陣列和 pytorch 張量,預期值範圍在[0, 1]
之間。如果是張量或張量列表,則預期形狀應為(B, C, H, W)
或(C, H, W)
。如果是 numpy 陣列或陣列列表,則預期形狀應為(B, H, W, C)
或(H, W, C)
。 - prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示。實驗性功能:要使用此功能,請確保將文字編碼器顯式載入到管道中。如果未載入文字編碼器,則將忽略提示。 - 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
。返回元組時,第一個元素是包含生成影像的列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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 strength: float = 1.0 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 30.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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]
) — 表示由 VAE 生成的用於遮罩image
的影像批處理的Tensor
。如果未提供,遮罩潛變數張量將由mask_image
生成。 - height (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳效果,預設設定為 1024。 - width (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳效果,預設設定為 1024。 - strength (
float
, 可選, 預設為 1.0) — 指示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的全部迭代次數。值為 1 基本上忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會生成更高質量的影像,但推理速度會變慢。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigma,排程器支援在其set_timesteps
方法中新增sigmas
引數。如果未定義,將使用傳入num_inference_steps
時的預設行為。 - guidance_scale (
float
, 可選, 預設為 30.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 方程 2 中的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞要生成的影像數量。 - generator (
torch.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
。當返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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")
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
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 縮放因子。