
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 InputTemplate 模型的输入格式为 Python 字典字段由各 Template 模型自行定义例如亮度模型的{scale: 0.8}Template ModelTemplate 模型本体可从 ModelScope 加载ModelConfig(model_idxxx/xxx)也可从本地路径加载ModelConfig(pathxxx)Template CacheTemplate 模型的输出格式同样是 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能力模型 IDDiffSynth-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_dtypetorch.bfloat16, devicecuda, model_configs[ ModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patterntext_encoder/*.safetensors), ModelConfig(model_idblack-forest-labs/FLUX.2-klein-base-4B, origin_file_patterntransformer/*.safetensors), ModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patternvae/diffusion_pytorch_model.safetensors), ], tokenizer_configModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patterntokenizer/), ) # Generate an image image pipe( prompta cat, seed0, cfg_scale4, height1024, width1024, ) 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_dtypetorch.bfloat16, devicecuda, model_configs[ ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Brightness) ], ) # Generate an image image template_pipeline( pipe, prompta cat, seed0, cfg_scale4, height1024, width1024, template_inputs[{scale: 0.8}], ) image.save(image_0.8.png)完整可运行版本见示例脚本 Template-KleinBase4B-Brightness.py其中用同一固定seed0分别以scale0.7 / 0.5 / 0.3生成亮、中、暗三张对比图直观展示亮度控制强度。2.3 参数传递的源码机制从 template.py 的TemplatePipeline.__call__第 188-208 行可以看出其工作方式template_cache self.call_single_side(pipepipe, inputstemplate_inputs or []) negative_template_cache self.call_single_side(pipepipe, inputsnegative_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。例如亮度模型正向scale0.8调亮、负向scale0.5模型会对比两侧差异生成亮度变化更明显的图像# Generate an image with CFG image template_pipeline( pipe, prompta cat, seed0, cfg_scale4, height1024, width1024, 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_loadingTemplate 模型暂不支持主框架的 VRAM 显存管理——这一点在 template.py 的check_vram_config第 141-151 行中明确体现只要检测到ModelConfig携带offload_device、offload_dtype、computation_device等 VRAM 配置就会发出告警TemplatePipeline doesnt support VRAM management. VRAM config will be ignored.并忽略。替代方案是惰性加载仅在推理到某个 Template 模型时才把它的权重加载到显存。这在同时启用多个 Template 模型时能显著降低显存需求——显存占用峰值仅为单个 Template 模型的大小。启用方法是为from_pretrained添加参数lazy_loadingTruetemplate_pipeline TemplatePipeline.from_pretrained( torch_dtypetorch.bfloat16, devicecuda, model_configs[ ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Brightness) ], lazy_loadingTrue, )源码中lazy_loadingTrue时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_dtypeself.torch_dtype, deviceself.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_dtypetorch.bfloat16, devicecuda, model_configs[ ModelConfig(model_idblack-forest-labs/FLUX.2-klein-base-4B, origin_file_patterntransformer/*.safetensors, **vram_config), ModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patterntext_encoder/*.safetensors, **vram_config), ModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patternvae/diffusion_pytorch_model.safetensors), ], tokenizer_configModelConfig(model_idblack-forest-labs/FLUX.2-klein-4B, origin_file_patterntokenizer/), ) pipe.dit pipe.enable_lora_hot_loading(pipe.dit) template TemplatePipeline.from_pretrained( torch_dtypetorch.bfloat16, devicecuda, lazy_loadingTrue, model_configs[ ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Brightness), # model_id: 0 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-ControlNet), # model_id: 1 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Edit), # model_id: 2 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Upscaler), # model_id: 3 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-SoftRGB), # model_id: 4 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Sharpness), # model_id: 5 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Inpaint), # model_id: 6 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Aesthetic), # model_id: 7 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-ContentRef), # model_id: 8 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Age), # model_id: 9 ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-PandaMeme), # model_id: 10 ], )下面四个官方组合示例均基于上述多模型架构model_id与上表一一对应。5.1 超分辨率 锐化增强组合Template-KleinBase4B-Upscalermodel_id 3与Template-KleinBase4B-Sharpnessmodel_id 5可将模糊图片高清化同时提高细节清晰度。upscaler以低分辨率图作为输入image字段 描述性promptsharpness通过scale1施加最大锐化负向侧分别用空prompt和scale0作为对照image template( pipe, promptA cat is sitting on a stone., seed0, cfg_scale4, num_inference_steps50, 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_dirdata/examples, )5.2 结构控制 美学对齐 锐化增强三模型组合ControlNetmodel_id 1负责控制构图Aestheticmodel_id 7负责填充细节Sharpnessmodel_id 5负责保证清晰度融合后可获得精美画面。其中Aesthetic的输入较特殊直接以lora_ids指定从 Template Cache 的 LoRA 列表list(range(1, 180, 2))共 90 个奇数索引 LoRA中选择融合对象并用lora_scales2.0与merge_typemean控制融合强度与方式image template( pipe, promptA cat is sitting on a stone, bathed in bright sunshine., seed0, cfg_scale4, num_inference_steps50, 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 结构控制 图像编辑 色彩调节ControlNetmodel_id 1控制构图Editmodel_id 2保留原图细节如毛发纹理SoftRGBmodel_id 4控制画面色调——以R / G / B三个通道系数取值 0~1直接指定目标色温。三模型组合即可渲染出极具艺术感的画面image template( pipe, promptA cat is sitting on a stone. Colored ink painting., seed0, cfg_scale4, num_inference_steps50, 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 亮度控制 图像编辑 局部重绘Brightnessmodel_id 0负责生成明亮画面Editmodel_id 2参考原图布局Inpaintmodel_id 6负责保持背景不变——对image施加mask遮罩并设置force_inpaintTrue强制重绘遮罩区域从而生成跨越次元的混合内容如将真实照片中的猫改为平面动漫风格image template( pipe, promptA cat is sitting on a stone. Flat anime style., seed0, cfg_scale4, num_inference_steps50, 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_loadingTrue。含 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),仅供参考