Hugging Face推出Modular Diffusers 实现扩散管道可组合化

关键创新
Modular Diffusers 是 Hugging Face 在 Diffusers 框架基础上推出的全新组合式构建方式。传统的 DiffusionPipeline 需要一次性定义完整的模型结构,而 Modular Diffusers 将整个流程拆解为若干独立块(text encoder、vae encoder、denoise、decode 等),每个块拥有明确的输入、输出和组件依赖。开发者可以像搭积木一样自由增删、替换或单独运行任意块,大幅提升实验灵活性和资源复用率。
可组合块的工作原理
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("black-forest-labs/FLUX.2-klein-4B")
pipe.load_components(torch_dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt="a serene landscape at sunset", num_inference_steps=4).images[0]
上述代码与标准 DiffusionPipeline 的调用方式保持一致,但内部的 pipe.blocks 实际上是一个块集合。通过 print(pipe.blocks) 可以看到每个子块的名称与实现类,开发者可以使用 pipe.blocks.sub_blocks.pop("text_encoder") 将文本编码块抽离出来,单独构建文本嵌入流水线,然后将得到的 prompt_embeds 直接喂给剩余块,实现 Prompt‑to‑Embedding 的解耦。
自定义块实战
Modular Diffusers 允许用户用 Python 定义自己的块,只需声明 expected_components、inputs、intermediate_outputs 与核心计算逻辑。例如下面的 DepthProcessorBlock 使用了开源的 Depth Anything V2 模型,将输入图像转化为深度图并输出 control_image,随后可以无缝接入任何需要控制图的工作流(如 ControlNet):
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
将该块插入 Qwen‑Image 的 controlnet_text2image 工作流,只需一次 blocks.sub_blocks.insert("depth", DepthProcessorBlock(), 0),后续的数据流会自动把 control_image 传递给下游的 ControlNet 节点,无需手动编写桥接代码。
社区管线与生态
自发布以来,社区已经基于 Modular Diffusers 构建了多条完整管线。例如:
- Krea Realtime Video:14B 参数实时视频生成模型,支持文本到视频、视频到视频以及流式交互,能够在单张 B200 GPU 上实现 11fps。
- Waypoint‑1:2.3B 参数的交互式世界模型,能够根据控制信号和文本提示实时生成可探索的 3D 环境。
这些管线均以模块化仓库(Modular Repository)的形式托管在 Hugging Face Hub,仓库中不仅包含模型权重的引用,还包含自定义块的 Python 实现和可视化配置文件,用户只需 ModularPipeline.from_pretrained(repo_id) 即可一键启动。
与 Mellon 的深度集成
Mellon 是 Hugging Face 正在研发的节点式可视化工作流编辑器,旨在为非程序员提供拖拽式的模型组装体验。得益于 Modular Diffusers 统一的块接口,Mellon 能够自动读取任意块的 inputs 与 outputs,在节点面板中动态生成对应的输入框和连线,实现 “一次定义,万种组合” 的使用体验。用户只需在 Mellon 画布上加载仓库 ID(如 diffusers/gemini-prompt-expander-mellon),系统即会生成一个带有 Prompt 输入和扩展后 Prompt 输出的节点,随后将其连接到标准的文本编码节点,即可完成 Prompt 扩展 → 图像生成的全链路。
未来展望
Modular Diffusers 将继续扩展块库,加入更多跨模态控制(如深度、姿态、语义分割)以及更高效的懒加载与显存管理机制。随着 Mellon 的逐步成熟,预计会有更多非技术背景的创作者直接在浏览器中搭建复杂的生成式 AI 工作流,进一步降低大模型的使用门槛。
“Modular Diffusers 把扩散模型的可组合性提升到了前所未有的水平,让研发者可以像搭乐高一样快速迭代。” — Hugging Face 官方博客