Diffusers 文件
FluxControlInpaint
並獲得增強的文件體驗
開始使用
FluxControlInpaint
FluxControlInpaintPipeline 是 Flux.1 深度/邊緣檢測模型的影像修復實現。它是一個允許您使用 Flux.1 深度/邊緣檢測模型修復影像的流水線。該流水線接收影像和遮罩作為輸入,並返回修復後的影像。
FLUX.1 深度和邊緣檢測 [開發中] 是一個 120 億引數的修正流轉換器,能夠根據文字描述生成影像,同時遵循給定輸入影像的結構。**這不是一個 ControlNet 模型**。
控制型別 | 開發者 | 連結 |
---|---|---|
深度 | Black Forest Labs | 連結 |
邊緣檢測 | Black Forest Labs | 連結 |
在消費級硬體裝置上執行 Flux 可能相當昂貴。但是,您可以執行一系列最佳化,使其執行更快、更節省記憶體。有關更多詳細資訊,請檢視此部分。此外,Flux 可以受益於量化,以提高記憶體效率,但會犧牲推理延遲。要了解更多資訊,請參閱此部落格文章。有關資源的詳盡列表,請檢視此 gist。
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np
pipe = FluxControlInpaintPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Depth-dev",
torch_dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
"sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
"sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")
prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
head_mask = np.zeros_like(image)
head_mask[65:580,300:642] = 255
mask_image = Image.fromarray(head_mask)
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")
output = pipe(
prompt=prompt,
image=image,
control_image=control_image,
mask_image=mask_image,
num_inference_steps=30,
strength=0.9,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save("output.png")
FluxControlInpaintPipeline
class diffusers.FluxControlInpaintPipeline
< 源 >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel )
引數
- 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-dev-Depth/Canny 進行影像修復的 Flux 流水線。
參考:https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< 源 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.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
的尺寸。如果傳遞了 height 和/或 width,則image
會相應地調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素都可以正確批處理以輸入到單個 ControlNet。 - mask_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) —Image
、numpy 陣列或張量,表示用於遮罩image
的影像批處理。遮罩中的白色畫素將被重新繪製,而黑色畫素將被保留。如果mask_image
是 PIL 影像,則在使用前將其轉換為單通道(亮度)。如果是 numpy 陣列或 pytorch 張量,則應包含一個顏色通道 (L) 而不是 3 個,因此 pytorch 張量的預期形狀為(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。numpy 陣列的預期形狀為(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - mask_image_latent (
torch.Tensor
,List[torch.Tensor]
) —Tensor
表示由 VAE 生成的用於遮罩image
的影像批處理。如果未提供,則將由mask_image
生成遮罩潛在空間張量。 - height (
int
,可選,預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素高度。為獲得最佳結果,預設為 1024。 - width (
int
,可選,預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影像的畫素寬度。為獲得最佳結果,預設為 1024。 - strength (
float
,可選,預設為 1.0) — 指示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的完整迭代次數。值為 1 基本上會忽略image
。 - num_inference_steps (
int
,可選,預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但會以較慢的推理速度為代價。 - sigmas (
List[float]
,可選) — 用於去噪過程的自定義 sigmas,排程器支援在其set_timesteps
方法中接受sigmas
引數。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - guidance_scale (
float
,可選,預設為 7.0) — 無分類器擴散引導中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
來啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - num_images_per_prompt (
int
,可選,預設為 1) — 每個提示生成的影像數量。 - generator (
torch.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
。返回元組時,第一個元素是生成的影像列表。
呼叫管道進行生成時呼叫的函式。
示例
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np
pipe = FluxControlInpaintPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Depth-dev",
torch_dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
"sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
"sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")
prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
head_mask = np.zeros_like(image)
head_mask[65:580, 300:642] = 255
mask_image = Image.fromarray(head_mask)
processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")
output = pipe(
prompt=prompt,
image=image,
control_image=control_image,
mask_image=mask_image,
num_inference_steps=30,
strength=0.9,
guidance_scale=10.0,
generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save(
"output.png"
)
停用切片 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 縮放因子。
FluxPipelineOutput
類 diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput
< 來源 >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )
Stable Diffusion 管道的輸出類。