Hugging Face 推出 Modular Diffusers,提供可組合的擴散模型流程模組
Introducing Modular Diffusers - Composable Building Blocks for Diffusion Pipelines
Hugging Face 推出 Modular Diffusers,讓使用者以可重用區塊組合擴散模型流程,作為現有 DiffusionPipeline 的更靈活、可組合替代方案。
文章以現成流程、自訂區塊及 Hub 分享示例,展示如何把擴散工作流拆成可檢視、替換並重新組合的元件。
Modular Diffusers 引入建構擴散 pipeline 的新方法:把可重用區塊組合起來。你不必從頭編寫整個 pipeline,而可以混合搭配不同區塊,建立切合需要的工作流程!這是現有 DiffusionPipeline 類別以外,更靈活、可組合的選項。
本文會介紹 Modular Diffusers 的運作方式:從使用熟悉的 API 執行模組化 pipeline,到建立完全自訂的區塊,再把它們組合成自己的工作流程。我們亦會示範它如何與 Mellon 整合;Mellon 是以節點為基礎的視覺化工作流程介面,可用來連接不同 Modular Diffusers 區塊。
目錄
快速開始
以下示範如何使用預先建立的區塊,以 FLUX.2 Klein 4B 執行推論:
import torch
from diffusers import ModularPipeline
# Create a modular pipeline - this only defines the workflow, model weights have not been loaded yet
pipe = ModularPipeline.from_pretrained(
"black-forest-labs/FLUX.2-klein-4B"
)
# Now load the model weights — configure dtype, quantization, etc in this step
pipe.load_components(torch_dtype=torch.bfloat16)
pipe.to("cuda")
# Generate an image - API remains the same as DiffusionPipeline
image = pipe(
prompt="a serene landscape at sunset",
num_inference_steps=4,
).images[0]
image.save("output.png")
結果與使用標準 DiffusionPipeline 相同,但底層 pipeline 完全不同:它由靈活的區塊組成,包括文字編碼、圖像編碼、降噪及解碼,你可以直接檢視各區塊:
print(pipe.blocks)
Flux2KleinAutoBlocks(
...
Sub-Blocks:
[0] text_encoder (Flux2KleinTextEncoderStep)
[1] vae_encoder (Flux2KleinAutoVaeEncoderStep)
[2] denoise (Flux2KleinCoreDenoiseStep)
[3] decode (Flux2DecodeStep)
)
每個區塊都獨立封裝,並有自己的輸入和輸出。你可以把任何區塊當成獨立 pipeline 執行,也可自由新增、移除和替換區塊;系統會動態重新組合,配合仍保留的區塊運作。使用 .init_pipeline() 把區塊轉換成可執行的 pipeline,再用 .load_components() 載入模型權重。
# get a copy of the blocks
blocks = pipe.blocks
# pop out the text_encoder block
text_blocks = blocks.sub_blocks.pop("text_encoder")
# run it as its own pipeline
text_pipe = text_blocks.init_pipeline("black-forest-labs/FLUX.2-klein-4B")
# load the text_encoder, or reuse already loaded components: text_pipe.update_components(text_encoder=pipe.text_encoder)
text_pipe.load_components(torch_dtype=torch.bfloat16)
text_pipe.to("cuda")
prompt_embeds = text_pipe(prompt="a serene landscape at sunset").prompt_embeds
# create a new pipeline from the remaining blocks
# it now accepts prompt_embeds directly instead of prompt
remaining_pipe = blocks.init_pipeline("black-forest-labs/FLUX.2-klein-4B")
remaining_pipe.load_components(torch_dtype=torch.bfloat16)
remaining_pipe.to("cuda")
image = remaining_pipe(prompt_embeds=prompt_embeds, num_inference_steps=4).images[0]
如需瞭解區塊類型、組合模式、延遲載入和使用 ComponentsManager 管理記憶體,請參閲 Modular Diffusers 文件。
自訂區塊
建立自訂區塊時,Modular Diffusers 的優勢便會充分發揮。自訂區塊是 Python 類別,用來定義元件、輸入、輸出及運算邏輯;定義完成後,便可加入任何工作流程。
編寫自訂區塊
以下示範一個區塊,使用 Depth Anything V2 從圖像擷取深度圖。
class DepthProcessorBlock(ModularPipelineBlocks):
@property
def expected_components(self):
return [
ComponentSpec("depth_processor", DepthPreprocessor,
pretrained_model_name_or_path="depth-anything/Depth-Anything-V2-Large-hf")
]
@property
def inputs(self):
return [
InputParam("image", required=True,
description="Image(s) to extract depth maps from"),
]
@property
def intermediate_outputs(self):
return [
OutputParam("control_image", type_hint=torch.Tensor,
description="Depth map(s) of input image(s)"),
]
@torch.no_grad()
def __call__(self, components, state):
block_state = self.get_block_state(state)
depth_map = components.depth_processor(block_state.image)
block_state.control_image = depth_map.to(block_state.device)
self.set_block_state(state, block_state)
return components, state
expected_components定義區塊所需的模型;此處需要深度估算模型。pretrained_model_name_or_path參數會設定預設 Hub 儲存庫,供系統載入,令load_components自動擷取深度模型;你亦可在modular_model_index.json中覆寫設定。inputs和intermediate_outputs會定義輸入和輸出。- 運算邏輯寫在
__call__中。
把區塊組合成工作流程
我們以 Qwen 的 ControlNet 工作流程使用這個區塊。先擷取 ControlNet 工作流程,再把深度區塊放到最前面:
# Create Qwen Image pipeline
pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image")
print(pipe.blocks.available_workflows)
# Supported workflows:
# - `text2image`: requires `prompt`
# - `image2image`: requires `prompt`, `image`
# - `inpainting`: requires `prompt`, `mask_image`, `image`
# - `controlnet_text2image`: requires `prompt`, `control_image`
# - `controlnet_image2image`: requires `prompt`, `image`, `control_image`
# Extract the ControlNet workflow — it expects a control_image input
blocks = pipe.blocks.get_workflow("controlnet_text2image")
# Show the blocks this workflow uses
print(blocks)
# Insert depth block at the beginning — its output (control_image)
# automatically flows to the ControlNet block that needs it
blocks.sub_blocks.insert("depth", DepthProcessorBlock(), 0)
# You can inspect any block's inputs and outputs with print(blocks.doc)
blocks.sub_blocks['depth'].doc
序列中的區塊會自動共用數據:深度區塊輸出的 control_image 會傳至需要它的下游區塊;由於沒有較早的區塊提供 image 輸入,因此它會成為 pipeline 輸入。
from diffusers import ComponentsManager, AutoModel
from diffusers.utils import load_image
# ComponentsManager handles memory across multiple pipelines —
# it automatically offloads models to CPU when not in use
manager = ComponentsManager()
pipeline = blocks.init_pipeline("Qwen/Qwen-Image", components_manager=manager)
pipeline.load_components(torch_dtype=torch.bfloat16)
# The depth model loads automatically from the default path we set in expected_components —
# no need to load it manually even though it's not part of the Qwen repo.
# But controlnet is not included by default, so we do need to load it from a different repo
controlnet = AutoModel.from_pretrained("InstantX/Qwen-Image-ControlNet-Union", torch_dtype=torch.bfloat16)
pipeline.update_components(controlnet=controlnet)
# pipeline now takes image as input
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg")
output = pipeline(
prompt="an astronaut hatching from an egg, detailed, fantasy, Pixar, Disney",
image=image,
).images[0]
在 Hub 分享自訂區塊
你可以把自訂區塊發布至 Hub,讓任何人都可使用 trust_remote_code=True 載入。我們建立了範本供你開始使用;完整流程請參閲建立自訂區塊指南。
pipeline.save_pretrained(local_dir, repo_id="your-username/your-block-name", push_to_hub=True)
本文使用的 DepthProcessorBlock 已發布在 diffusers/depth-processor-custom-block;你可以直接載入和使用:
from diffusers import ModularPipelineBlocks
depth_block = ModularPipelineBlocks.from_pretrained(
"diffusers/depth-processor-custom-block", trust_remote_code=True
)
我們已發布一系列可直接使用的自訂區塊,請按此查看。
模組化儲存庫
ModularPipeline.from_pretrained 開箱即用,適用於任何現有 Diffusers 儲存庫;除此之外,Modular Diffusers 亦引入一種新型儲存庫:模組化儲存庫。
模組化儲存庫可以參照原始模型儲存庫中的元件。例如,diffusers/flux2-bnb-4bit-modular 內含量化 transformer,並從原始儲存庫載入其餘元件。
// diffusers/flux2-bnb-4bit-modular/modular_model_index.json
{
"transformer": [
"diffusers",
"Flux2Transformer2DModel",
{
"pretrained_model_name_or_path": "diffusers/flux2-bnb-4bit-modular",
"subfolder": "transformer",
"type_hint": ["diffusers", "Flux2Transformer2DModel"]
}
],
"vae": [
"diffusers",
"AutoencoderKLFlux2",
{
"pretrained_model_name_or_path": "black-forest-labs/FLUX.2-dev",
"subfolder": "vae",
"type_hint": ["diffusers", "AutoencoderKLFlux2"]
}
],
...
}
模組化儲存庫亦可託管以 Python 程式碼編寫的自訂 pipeline 區塊,以及供 Mellon 等工具使用的視覺化介面設定,全部集中在同一處。
社羣 pipeline
社羣已開始使用 Modular Diffusers 建立完整 pipeline,並在 Hub 發布模型權重和可直接執行的程式碼。
- Krea Realtime Video — 一款由 Wan 2.1 蒸餾而成的 14B 即時影片生成模型,在單張 B200 GPU 上可達 11fps。它支援文字生成影片、影片轉影片及串流影片轉影片,全部以模組化區塊建構。用戶可在生成期間修改提示、即時改變影片風格,並在 1 秒內看到首幀。
import torch
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("krea/krea-realtime-video", trust_remote_code=True)
pipe.load_components(
trust_remote_code=True,
device_map="cuda",
torch_dtype={"default": torch.bfloat16, "vae": torch.float16}
)
- Waypoint-1 — 由 Overworld 推出的 2.3B 即時擴散世界模型。它會根據控制輸入和文字提示自回歸生成互動世界;你可以在消費級硬件上即時探索並與生成的環境互動。
團隊可以建立新穎架構,將它們封裝成區塊,再把完整 pipeline 發布至 Hub,讓任何人都能使用 ModularPipeline.from_pretrained 載入。
如需更多內容,請查看完整的社羣 pipeline 合集。
整合 Mellon
💡 Mellon 仍在早期開發階段,尚未準備好用於正式環境。以下只是讓你預先了解整合方式!
Mellon 是與 Modular Diffusers 整合的節點圖介面。如果你熟悉 ComfyUI 等節點式工具,便會很快上手;不過兩者有幾項重要分別:
- 動態節點 — 不再需要數十個按模型區分的節點;我們只提供少量節點,並會按你選擇的模型自動調整介面。學會一次,便可配合任何模型使用。
- 單節點工作流程 — 受惠於 Modular Diffusers 可組合的區塊系統,你可以把整個 pipeline 收納成單一節點。在同一畫布上執行多個工作流程,也不會變得雜亂。
- 開箱即用的 Hub 整合 — 發布到 Hugging Face Hub 的自訂區塊可即時在 Mellon 使用。我們提供實用函式,按區塊定義自動生成節點介面,無須編寫 UI 程式碼。
之所以能夠整合,是因為每個區塊都提供相同屬性(inputs、intermediate_outputs、expected_components)。這個一致的 API 讓 Mellon 可按任何區塊定義自動生成節點介面,並把區塊組合成更高層級的節點。
例如,diffusers/FLUX.2-klein-4B-modular 在同一個儲存庫內包含 pipeline 定義、元件參照及 mellon_pipeline_config.json。你可以在 Python 中使用 ModularPipeline.from_pretrained("diffusers/FLUX.2-klein-4B-modular") 載入,亦可在 Mellon 中載入,建立單節點或多節點工作流程。
以下是一個簡單範例:我們把 Gemini 提示擴展節點加入現有的文字生成圖像工作流程。該節點以模組化儲存庫形式託管於 diffusers/gemini-prompt-expander-mellon:
- 拖入 Dynamic Block 節點,然後輸入
repo_id(即diffusers/gemini-prompt-expander-mellon) - 按一下 LOAD CUSTOM BLOCK;節點會自動增加提示文字方塊和名為「prompt」的輸出插槽,所有設定均取自該儲存庫
- 輸入簡短提示,把輸出連接至 Encode Prompt 節點,然後執行
Gemini 會在生成圖像前,把你的簡短提示擴展成詳細描述。不用程式碼,不用設定,只需輸入 Hub 儲存庫 ID。
你的瀏覽器不支援影片標籤。
這只是其中一個例子。如需詳細教學,請參閲 Mellon x Modular Diffusers 指南,亦可觀看這段影片!
總結
Modular Diffusers 帶來社羣一直期待的可組合性和靈活度,同時保留 Diffusers 的強大功能。這項技術仍處於早期階段;我們希望聽取你的意見,決定下一步發展。歡迎試用,並告訴我們哪些地方好用、哪些不好用,以及還欠缺甚麼。
資源
- Modular Diffusers概覽
- Mellon
- Mellon x Modular Diffusers
- 合集:自訂區塊
- 合集:使用 Modular Diffusers 建立的社羣 pipeline
感謝 Chun Te Lee 製作縮圖,亦感謝 Poli、Pedro、Lysandre、Linoy、Aritra 和 Steven 提供寶貴審閲意見。
來源:Hugging Face Blog · huggingface.co