DiffSynth-Studio Template 模型推理指南:在 FLUX.2 Pipeline 上实现可控生成与多模板组合
【免费下载链接】DiffSynth-StudioEnjoy the magic of Diffusion models!项目地址: https://gitcode.com/GitHub_Trending/dif/DiffSynth-Studio
导读
本文基于 DiffSynth-Studio 官方文档 Template_Model_Inference 编写,系统讲解Diffusion Templates可控生成插件框架的推理全流程:如何以TemplatePipeline将 Template 模型挂载到基础模型 Pipeline 上、如何通过template_inputs/negative_template_inputs实现 CFG 增强、如何借助lazy_loading与 LoRA 热加载在低显存环境下运行,以及如何一次性加载多个 Template 模型完成"超分辨率 + 锐化""结构控制 + 美学对齐 + 锐化""结构控制 + 编辑 + 色调调节""亮度控制 + 编辑 + 局部重绘"等组合任务。读完本文,你将能够直接复现官方示例并基于源码理解其底层机制。
一、Diffusion Templates 与 TemplatePipeline 核心概念
Diffusion Templates 是 DiffSynth-Studio 中的可控生成插件框架,它为扩散模型(Diffusion models)提供额外的可控生成能力,而不需要修改基础模型本身的权重。其架构与模块设计详见 Understanding_Diffusion_Templates,核心包含四个模块:
- Template Input:Template 模型的输入,格式为 Python 字典,字段由各 Template 模型自行定义(例如亮度模型的
{"scale": 0.8}); - Template Model:Template 模型本体,可从 ModelScope 加载(
ModelConfig(model_id="xxx/xxx")),也可从本地路径加载(ModelConfig(path="xxx")); - Template Cache:Template 模型的输出,格式同样是 Python 字典,其字段与基础模型 Pipeline 的输入参数一一对应;
- Template Pipeline:管理多个 Template 模型的调度模块,负责模型加载与 Template Cache 的合并。
当框架启用时,Template Pipeline 输出 Template Cache(即基础 Pipeline 输入参数的子集),基础 Diffusion Pipeline 消费这些参数完成可控生成。当前 FLUX.2 Pipeline 中,Template Cache 支持KV-Cache与LoRA两种媒介。
目前官方围绕 FLUX.2 klein-base-4B 基础模型发布了 11 个 Template 模型,完整清单与对应的推理/训练代码索引见 Introducing_Diffusion_Templates:
| 能力 | 模型 ID(DiffSynth-Studio/前缀) |
|---|---|
| 结构控制 | Template-KleinBase4B-ControlNet |
| 亮度调节 | Template-KleinBase4B-Brightness |
| 色彩调节 | Template-KleinBase4B-SoftRGB |
| 图像编辑 | Template-KleinBase4B-Edit |
| 超分辨率 | Template-KleinBase4B-Upscaler |
| 锐化增强 | Template-KleinBase4B-Sharpness |
| 美学对齐 | Template-KleinBase4B-Aesthetic |
| 局部重绘 | Template-KleinBase4B-Inpaint |
| 内容参考 | Template-KleinBase4B-ContentRef |
| 年龄控制 | Template-KleinBase4B-Age |
| 彩蛋模型 | Template-KleinBase4B-PandaMeme |
二、在基础模型 Pipeline 上启用 Template 模型
2.1 纯基础模型推理(不使用 Template)
以基础模型black-forest-labs/FLUX.2-klein-base-4B为例,仅使用基础模型生成图像时,直接用Flux2ImagePipeline.from_pretrained加载文本编码器、DiT 与 VAE 三部分权重:
from diffsynth.diffusion.template import TemplatePipeline from diffsynth.pipelines.flux2_image import Flux2ImagePipeline, ModelConfig import torch # Load base model pipe = Flux2ImagePipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="text_encoder/*.safetensors"), ModelConfig(model_id="black-forest-labs/FLUX.2-klein-base-4B", origin_file_pattern="transformer/*.safetensors"), ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"), ], tokenizer_config=ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="tokenizer/"), ) # Generate an image image = pipe( prompt="a cat", seed=0, cfg_scale=4, height=1024, width=1024, ) image.save("image.png")这里ModelConfig通过model_id定位 ModelScope 仓库,origin_file_pattern指定从该仓库中下载哪些子文件(如text_encoder/*.safetensors、transformer/*.safetensors、vae/diffusion_pytorch_model.safetensors、tokenizer/)。
2.2 加载 Template 模型并控制生成
亮度控制模型DiffSynth-Studio/Template-KleinBase4B-Brightness可以在生成过程中调节图像亮度。通过TemplatePipeline加载该模型,并在调用时传入template_inputs=[{"scale": 0.8}]即可提高亮度。
关键注意事项:在代码中,原本传给pipe的所有输入参数(prompt、seed、cfg_scale、height、width等)都必须转移到template_pipeline的调用中,并额外添加template_inputs:
# Load Template model template_pipeline = TemplatePipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Brightness") ], ) # Generate an image image = template_pipeline( pipe, prompt="a cat", seed=0, cfg_scale=4, height=1024, width=1024, template_inputs=[{"scale": 0.8}], ) image.save("image_0.8.png")完整可运行版本见示例脚本 Template-KleinBase4B-Brightness.py,其中用同一固定seed=0分别以scale=0.7 / 0.5 / 0.3生成亮、中、暗三张对比图,直观展示亮度控制强度。
2.3 参数传递的源码机制
从 template.py 的TemplatePipeline.__call__(第 188-208 行)可以看出其工作方式:
template_cache = self.call_single_side(pipe=pipe, inputs=template_inputs or []) negative_template_cache = self.call_single_side(pipe=pipe, inputs=negative_template_inputs or []) required_params = list(inspect.signature(pipe.__call__).parameters.keys()) for param in template_cache: if param in required_params: kwargs[param] = template_cache[param] else: print(f"`{param}` is not included in the inputs of `{pipe.__class__.__name__}`. This parameter will be ignored.")也就是说:Template 模型产出的 Template Cache 会被注入pipe(**kwargs)的输入参数中(negative_前缀的缓存则注入对应的负向参数),若某个缓存字段不在基础 Pipeline 的签名中,则会打印告警并忽略。这正是"拦截基础 Pipeline 输入参数"实现可控生成的核心机制。
三、Template 模型的 CFG 增强(Classifier-Free Guidance)
仅使用正向template_inputs时控制效果已经生效;若希望控制效果更明显,可以为 Template 模型启用类似 CFG 的对比机制——在调用参数中增加negative_template_inputs。
例如亮度模型,正向scale=0.8调亮、负向scale=0.5,模型会对比两侧差异,生成亮度变化更明显的图像:
# Generate an image with CFG image = template_pipeline( pipe, prompt="a cat", seed=0, cfg_scale=4, height=1024, width=1024, template_inputs=[{"scale": 0.8}], negative_template_inputs=[{"scale": 0.5}], ) image.save("image_0.8_cfg.png")从源码看,__call__中正向与负向各走一次call_single_side:负向缓存中凡是基础 Pipeline 存在negative_<param>输入(例如negative_text_embedding、negative_kv_cache)的字段都会被注入,从而在去噪过程中拉开正负两侧差距,放大控制强度。后续所有组合示例中,各 Template 模型都同时提供了template_inputs与negative_template_inputs两组配置,正是这一机制的常规用法。
四、低显存支持:惰性加载与 LoRA 热加载
4.1 惰性加载(lazy_loading)
Template 模型暂不支持主框架的 VRAM 显存管理——这一点在 template.py 的check_vram_config(第 141-151 行)中明确体现:只要检测到ModelConfig携带offload_device、offload_dtype、computation_device等 VRAM 配置,就会发出告警"TemplatePipeline doesn't support VRAM management. VRAM config will be ignored."并忽略。
替代方案是惰性加载:仅在推理到某个 Template 模型时才把它的权重加载到显存。这在同时启用多个 Template 模型时能显著降低显存需求——显存占用峰值仅为单个 Template 模型的大小。启用方法是为from_pretrained添加参数lazy_loading=True:
template_pipeline = TemplatePipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Brightness") ], lazy_loading=True, )源码中,lazy_loading=True时TemplatePipeline.__init__不再立即加载模型(self.models = None),仅在fetch_model(第 163-170 行)按model_id触发时下载并加载:
def fetch_model(self, model_id): if self.lazy_loading: model_config = self.model_configs[model_id] model_config.download_if_necessary() model = load_template_model(model_config.path, torch_dtype=self.torch_dtype, device=self.device) else: model = self.models[model_id] return model同时call_single_side中记录了当前已加载的onload_model_id,连续使用同一模型时不会重复加载。
基础模型的 Pipeline 与 Template Pipeline 是完全独立的,因此可以只对基础模型 Pipeline 开启显存管理,而对 Template Pipeline 使用惰性加载,两者互不干扰。
4.2 LoRA 热加载
当 Template 模型的输出 Template Cache 中包含LoRA时(例如美学对齐模型Template-KleinBase4B-Aesthetic的缓存中带有 LoRA 权重),必须对基础模型的 Pipeline开启显存管理,或开启 LoRA 热加载,否则 LoRA 权重会在多次生成中被反复融合叠加,导致结果异常:
pipe.dit = pipe.enable_lora_hot_loading(pipe.dit)enable_lora_hot_loading的实现位于 base_pipeline.py,它会将模型中的torch.nn.Linear等模块替换为支持动态加载 LoRA 权重的包装模块(AutoWrappedLinear),使 LoRA 按需注入而非静态融合。这也是 CLI 训练脚本中--enable_lora_hot_loading参数(见 parsers.py)背后的机制。
五、启用多个 Template 模型
TemplatePipeline支持同时加载多个 Template 模型。推理时,通过template_inputs列表项中的model_id区分每个 Template 模型的输入,model_id即model_configs列表中的索引(从 0 开始)。
对基础模型 Pipeline 开启显存管理、对 Template Pipeline 开启惰性加载后,可以加载任意数量的 Template 模型。以下完整代码一次性加载了全部 11 个 Template 模型:
from diffsynth.diffusion.template import TemplatePipeline from diffsynth.pipelines.flux2_image import Flux2ImagePipeline, ModelConfig from modelscope import dataset_snapshot_download import torch from PIL import Image vram_config = { "offload_dtype": "disk", "offload_device": "disk", "onload_dtype": torch.bfloat16, "onload_device": "cuda", "preparing_dtype": torch.bfloat16, "preparing_device": "cuda", "computation_dtype": torch.bfloat16, "computation_device": "cuda", } pipe = Flux2ImagePipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig(model_id="black-forest-labs/FLUX.2-klein-base-4B", origin_file_pattern="transformer/*.safetensors", **vram_config), ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="text_encoder/*.safetensors", **vram_config), ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"), ], tokenizer_config=ModelConfig(model_id="black-forest-labs/FLUX.2-klein-4B", origin_file_pattern="tokenizer/"), ) pipe.dit = pipe.enable_lora_hot_loading(pipe.dit) template = TemplatePipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", lazy_loading=True, model_configs=[ ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Brightness"), # model_id: 0 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-ControlNet"), # model_id: 1 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Edit"), # model_id: 2 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Upscaler"), # model_id: 3 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-SoftRGB"), # model_id: 4 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Sharpness"), # model_id: 5 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Inpaint"), # model_id: 6 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Aesthetic"), # model_id: 7 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-ContentRef"), # model_id: 8 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-Age"), # model_id: 9 ModelConfig(model_id="DiffSynth-Studio/Template-KleinBase4B-PandaMeme"), # model_id: 10 ], )下面四个官方组合示例均基于上述"多模型"架构,model_id与上表一一对应。
5.1 超分辨率 + 锐化增强
组合Template-KleinBase4B-Upscaler(model_id 3)与Template-KleinBase4B-Sharpness(model_id 5),可将模糊图片高清化,同时提高细节清晰度。upscaler以低分辨率图作为输入(image字段 + 描述性prompt),sharpness通过scale=1施加最大锐化;负向侧分别用空prompt和scale=0作为对照:
image = template( pipe, prompt="A cat is sitting on a stone.", seed=0, cfg_scale=4, num_inference_steps=50, template_inputs = [ { "model_id": 3, "image": Image.open("data/examples/templates/image_lowres_100.jpg"), "prompt": "A cat is sitting on a stone.", }, { "model_id": 5, "scale": 1, }, ], negative_template_inputs = [ { "model_id": 3, "image": Image.open("data/examples/templates/image_lowres_100.jpg"), "prompt": "", }, { "model_id": 5, "scale": 0, }, ], ) image.save("image_Upscaler_Sharpness.png")示例中用到的测试图片位于data/examples/templates/目录,可通过以下代码从 ModelScope 数据集下载(官方所有涉及图片输入的例子均先执行此步骤):
dataset_snapshot_download( "DiffSynth-Studio/examples_in_diffsynth", allow_file_pattern=["templates/*"], local_dir="data/examples", )5.2 结构控制 + 美学对齐 + 锐化增强
三模型组合:ControlNet(model_id 1)负责控制构图,Aesthetic(model_id 7)负责填充细节,Sharpness(model_id 5)负责保证清晰度,融合后可获得精美画面。其中Aesthetic的输入较特殊,直接以lora_ids指定从 Template Cache 的 LoRA 列表(list(range(1, 180, 2)),共 90 个奇数索引 LoRA)中选择融合对象,并用lora_scales=2.0与merge_type="mean"控制融合强度与方式:
image = template( pipe, prompt="A cat is sitting on a stone, bathed in bright sunshine.", seed=0, cfg_scale=4, num_inference_steps=50, template_inputs = [ { "model_id": 1, "image": Image.open("data/examples/templates/image_depth.jpg"), "prompt": "A cat is sitting on a stone, bathed in bright sunshine.", }, { "model_id": 7, "lora_ids": list(range(1, 180, 2)), "lora_scales": 2.0, "merge_type": "mean", }, { "model_id": 5, "scale": 0.8, }, ], negative_template_inputs = [ { "model_id": 1, "image": Image.open("data/examples/templates/image_depth.jpg"), "prompt": "", }, { "model_id": 7, "lora_ids": list(range(1, 180, 2)), "lora_scales": 2.0, "merge_type": "mean", }, { "model_id": 5, "scale": 0, }, ], ) image.save("image_Controlnet_Aesthetic_Sharpness.png")这里的lora_ids/merge_type最终作用于 Template Cache 合并环节——在 template.py 的merge_template_cache(第 122-139 行)中,当缓存键为lora时会调用merge_lora(见 utils/lora/merge.py)完成多份 LoRA 的拼接融合,mean即按均值方式合并。
5.3 结构控制 + 图像编辑 + 色彩调节
ControlNet(model_id 1)控制构图,Edit(model_id 2)保留原图细节(如毛发纹理),SoftRGB(model_id 4)控制画面色调——以R / G / B三个通道系数(取值 0~1)直接指定目标色温。三模型组合即可渲染出极具艺术感的画面:
image = template( pipe, prompt="A cat is sitting on a stone. Colored ink painting.", seed=0, cfg_scale=4, num_inference_steps=50, template_inputs = [ { "model_id": 1, "image": Image.open("data/examples/templates/image_depth.jpg"), "prompt": "A cat is sitting on a stone. Colored ink painting.", }, { "model_id": 2, "image": Image.open("data/examples/templates/image_reference.jpg"), "prompt": "Convert the image style to colored ink painting.", }, { "model_id": 4, "R": 0.9, "G": 0.5, "B": 0.3, }, ], negative_template_inputs = [ { "model_id": 1, "image": Image.open("data/examples/templates/image_depth.jpg"), "prompt": "", }, { "model_id": 2, "image": Image.open("data/examples/templates/image_reference.jpg"), "prompt": "", }, ], ) image.save("image_Controlnet_Edit_SoftRGB.png")SoftRGB的独立用法可参考 Template-KleinBase4B-SoftRGB.py:以(128, 128, 128)得到正常色调,以(208, 185, 138)得到暖色调,以(94, 163, 174)得到冷色调——注意示例中 RGB 值以x/255归一化到 0~1。
5.4 亮度控制 + 图像编辑 + 局部重绘
Brightness(model_id 0)负责生成明亮画面,Edit(model_id 2)参考原图布局,Inpaint(model_id 6)负责保持背景不变——对image施加mask遮罩并设置force_inpaint=True强制重绘遮罩区域,从而生成"跨越次元"的混合内容(如将真实照片中的猫改为平面动漫风格):
image = template( pipe, prompt="A cat is sitting on a stone. Flat anime style.", seed=0, cfg_scale=4, num_inference_steps=50, template_inputs = [ { "model_id": 0, "scale": 0.6, }, { "model_id": 2, "image": Image.open("data/examples/templates/image_reference.jpg"), "prompt": "Convert the image style to flat anime style.", }, { "model_id": 6, "image": Image.open("data/examples/templates/image_reference.jpg"), "mask": Image.open("data/examples/templates/image_mask_1.jpg"), "force_inpaint": True, }, ], negative_template_inputs = [ { "model_id": 0, "scale": 0.5, }, { "model_id": 2, "image": Image.open("data/examples/templates/image_reference.jpg"), "prompt": "", }, { "model_id": 6, "image": Image.open("data/examples/templates/image_reference.jpg"), "mask": Image.open("data/examples/templates/image_mask_1.jpg"), }, ], ) image.save("image_Brightness_Edit_Inpaint.png")Inpaint的独立用法见 Template-KleinBase4B-Inpaint.py:当不指定force_inpaint时模型按 mask 区域重绘,指定后强制执行局部重绘流程。
六、Template 模型格式与加载原理
理解推理的前提是了解 Template 模型的文件组织。一个 Template 模型目录结构如下:
Template_Model ├── model.py # 入口文件 └── model.safetensors # 模型权重template.py 的load_template_model(第 34-63 行)通过importlib动态执行目录下的model.py,读取模块级变量:
TEMPLATE_MODEL:模型类定义;TEMPLATE_MODEL_PATH:权重文件相对路径(若存在则通过load_model加载预训练权重;若不存在则实例化一个随机初始化模型或非模型模块);TEMPLATE_MODEL_CONFIG:可选的模型配置。
加载后通过check_template_model_format校验该模型必须实现带**kwargs的process_inputs与forward两个方法(与基类TemplateModel的接口一致),确保符合插件契约。若模型目录中还有TEMPLATE_DATA_PROCESSOR,则会被load_template_data_processor提取用于训练侧数据预处理。
七、常见问题与注意事项
- 参数必须传给
template_pipeline:启用 Template 后,生成参数(prompt、seed、cfg_scale、num_inference_steps、height、width等)与template_inputs全部传入 TemplatePipeline 的调用,而不是直接调用pipe。 - Template Pipeline 不支持 VRAM 管理:给
ModelConfig附加offload_*/computation_*等显存配置会被忽略并告警,请改用lazy_loading=True。 - 含 LoRA 的 Template Cache 必须配 LoRA 热加载:当缓存输出包含 LoRA(典型如 Aesthetic 模型)时,需对基础 Pipeline 执行
pipe.dit = pipe.enable_lora_hot_loading(pipe.dit),否则 LoRA 权重会反复叠加。 model_id按加载顺序索引:多模型推理时template_inputs中每个字典的model_id必须与from_pretrained的model_configs列表顺序一致。- 缓存字段冲突策略:若多个 Template 模型输出了同名缓存字段(
kv_cache、lora、text_embedding之外的字段),merge_template_cache会打印冲突告警并仅保留第一个结果,设计时应注意各模型输出字段的差异化。
关于 Template 模型的训练方法,请进一步阅读 Template_Model_Training;关于框架架构与 Template Cache 媒介的设计动机,参见 Understanding_Diffusion_Templates。所有可运行示例均位于 examples/flux2/model_inference(低显存版本见examples/flux2/model_inference_low_vram/)。
【免费下载链接】DiffSynth-StudioEnjoy the magic of Diffusion models!项目地址: https://gitcode.com/GitHub_Trending/dif/DiffSynth-Studio
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考