ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

DiffSynth-Studio Template 模型推理完全指南:在 FLUX.2 Pipeline 上实现可控生成与多模型组合

DiffSynth-Studio Template 模型推理完全指南:在 FLUX.2 Pipeline 上实现可控生成与多模型组合 DiffSynth-Studio Template 模型推理完全指南在 FLUX.2 Pipeline 上实现可控生成与多模型组合【免费下载链接】DiffSynth-StudioEnjoy the magic of Diffusion models!项目地址: https://gitcode.com/GitHub_Trending/dif/DiffSynth-Studio本篇技术指南聚焦 DiffSynth-Studio 的 Diffusion Templates 可控生成插件框架讲解如何通过TemplatePipeline在 FLUX.2 基础模型 Pipeline 之上加载 Template 模型亮度调节、结构控制、超分辨率、图像编辑等实现单模型控制、CFG 增强、低显存推理与多 Template 模型组合。读完本文你将掌握template_inputs/negative_template_inputs的完整用法、lazy_loading低显存方案、model_id多模型调度机制以及超分锐化结构美学锐化等实战组合的代码写法并理解 Template Cache 合并的底层原理。前置准备安装与模型获取Template 模型推理依赖 DiffSynth-Studio 主框架与 FLUX.2 基础模型。推理脚本可参考仓库中的现成示例例如 examples/flux2/model_inference/Template-KleinBase4B-Brightness.py标准显存版与examples/flux2/model_inference_low_vram/目录下的同名低显存版本。运行前需要准备基础模型组件以black-forest-labs/FLUX.2-klein-base-4B为例需要分别下载 transformer、text_encoder、tokenizer 与 vae 四个部分各部分的model_id与origin_file_pattern见下文代码。Template 模型由 DiffSynth-Studio 官方提供目前围绕 FLUX.2 KleinBase4B 基础模型发布了 11 个 Template 模型涵盖结构控制ControlNet、亮度调节Brightness、色彩调节SoftRGB、图像编辑Edit、超分辨率Upscaler、锐利激发Sharpness、美学对齐Aesthetic、局部重绘Inpaint、内容参考ContentRef、年龄控制Age以及彩蛋模型魔性熊猫PandaMeme。完整的模型清单与对应的推理/训练/验证代码索引见 Introducing_Diffusion_Templates.md。模型下载默认走魔搭ModelScope如需切换下载源可通过环境变量DIFFSYNTH_DOWNLOAD_SOURCEHuggingFace切换到 HuggingFace或设置DIFFSYNTH_SKIP_DOWNLOADTrue跳过下载直接使用本地已下载文件对应实现见 diffsynth/core/loader/config.py 中的parse_download_source与parse_skip_download。在基础模型 Pipeline 上启用 Template 模型第一步仅用基础模型生成图像先加载 FLUX.2 基础模型并直接生成一张图像作为后续对比的基线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是统一的模型描述数据结构定义见 diffsynth/core/loader/config.py核心字段包括字段作用说明model_id远程模型仓库 ID形如owner/repo配合origin_file_pattern使用path本地模型目录与model_id二选一传入本地目录时直接从本地加载origin_file_pattern文件过滤模式支持通配符如transformer/*.safetensors、tokenizer/以/结尾会自动展开为tokenizer/*未指定时默认*download_source下载源覆盖环境变量可选modelscope或huggingfaceoffload_*/onload_*/preparing_*/computation_*显存管理配置分别为 offload 设备/精度、onload 设备/精度、准备阶段设备/精度、计算阶段设备/精度第二步叠加 Template 模型控制亮度以亮度调节模型DiffSynth-Studio/Template-KleinBase4B-Brightness为例它可以通过scale参数控制生成图像的亮度输入scale0.8即可提高图像亮度。关键在于将原来传给pipe的输入参数转移到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)从源码看TemplatePipeline.__call__的执行逻辑见 diffsynth/diffusion/template.py是依次调用call_single_side处理template_inputs与negative_template_inputs可为空将每个 Template 模型产出的 Template Cache 合并检查合并结果的每个字段是否存在于pipe.__call__的签名参数中存在则注入kwargs负侧则注入negative_前缀参数否则打印忽略提示最后调用pipe(**kwargs)完成生图。因此 Template Cache 中的字段必须与基础模型 Pipeline 的输入参数对齐才能生效这也解释了为什么template_inputs中出现的scale等字段能够被下游 Pipeline 识别。Template 模型的 CFG 增强Template 模型同样支持 CFGClassifier-Free Guidance无分类器引导。以 Brightness 模型为例在TemplatePipeline的输入参数中增加negative_template_inputs并把scale设为 0.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_single_side的实现diffsynth/diffusion/template.py逐条遍历输入列表对每个输入字典取出model_id默认 0并fetch_model获取模型先执行model.process_inputs(pipepipe, **i)做输入预处理再执行model.forward(pipepipe, **cache)得到 Template Cache最后统一合并。正负两侧各自合并后在__call__中按negative_前缀注入负侧参数从而在基础模型内部形成两侧对照、拉大控制强度的效果。低显存支持惰性加载按需加载 Template 模型Template 模型暂不支持主框架的显存管理VRAM management这一点在源码中有明确约束TemplatePipeline.check_vram_config会对ModelConfig中的 offload/onload/preparing/computation 配置逐一检查只要任一字段非空就会警告 TemplatePipeline doesnt support VRAM management. VRAM config will be ignored.见 diffsynth/diffusion/template.py。不过 Template 模型支持惰性加载lazy_loadingTrue仅在推理轮到某个 Template 模型时才把它加载进显存推理完即可释放。启用多个 Template 模型时显存占用峰值约为单个 Template 模型的显存占用量可以显著降低显存需求。template_pipeline TemplatePipeline.from_pretrained( torch_dtypetorch.bfloat16, devicecuda, model_configs[ ModelConfig(model_idDiffSynth-Studio/Template-KleinBase4B-Brightness) ], lazy_loadingTrue, )惰性加载的代码路径在 diffsynth/diffusion/template.py构造时只执行download_if_necessary()下载权重、不加载模型self.models Nonefetch_model在推理时才按model_id索引model_configs并调用load_template_model加载见 diffsynth/diffusion/template.py#L163-L170。基础模型 Pipeline 的显存管理基础模型的 Pipeline 与 Template Pipeline 完全独立Template Pipeline 不使用显存管理但基础模型 Pipeline 可以按需开启显存管理。例如在ModelConfig中通过**vram_config传入 offload/onload/preparing/computation 的设备与精度配置让 transformer、text_encoder 等大组件在推理时按阶段在 disk/cuda 之间流转完整配置见下节示例。含 LoRA 的 Template Cache必须开启 LoRA 热加载当 Template 模型输出的 Template Cache 中包含 LoRA 时必须对基础模型的 Pipeline 开启显存管理或开启 LoRA 热加载否则会导致 LoRA 权重叠加例如多步推理时权重被反复叠加。开启 LoRA 热加载只需一行pipe.dit pipe.enable_lora_hot_loading(pipe.dit)enable_lora_hot_loading的实现位于 diffsynth/diffusion/base_pipeline.py如果模型已开启显存管理则直接返回否则用AutoWrappedLinear包装所有torch.nn.Linear层并按当前 Pipeline 的 dtype/device 构造一份 vram_config 后调用enable_vram_management使 LoRA 权重可以按需热加载/卸载而不驻留叠加。启用多个 Template 模型TemplatePipeline可以同时加载多个 Template 模型推理时通过template_inputs中的model_id区分每个模型的输入。model_id是model_configs列表的索引从 0 开始这一点可以从fetch_model的self.model_configs[model_id]直接印证。对基础模型 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 ], )多模型输入的调度与合并在call_single_side中template_inputs是一个字典列表每个字典对应一个 Template 模型的一次调用model_id缺省时为 0。同一model_id连续出现时会复用已加载的模型通过onload_model_id缓存避免重复加载。所有 Template Cache 最终由merge_template_cache合并diffsynth/diffusion/template.py合并规则如下kv_cache按 KV 名称逐项在序列维度dim1拼接实现多个 Template 的注意力缓存叠加lora调用merge_lora进行 LoRA 权重合并text_embedding在序列维度dim-2顺序拼接其余字段若只有一个模型产出则直接保留若多个模型产出同一字段则打印冲突提示并保留第一个。下面给出四个官方推荐的组合案例代码可直接运行对应的低显存版本见examples/flux2/model_inference_low_vram/。超分辨率 锐利激发组合 Upscalermodel_id 3与 Sharpnessmodel_id 5可将模糊图片高清化同时提升细节清晰度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)结构控制 美学对齐 锐利激发ControlNetmodel_id 1负责控制构图Aestheticmodel_id 7负责填充细节通过lora_ids与lora_scales指定参与合并的 LoRA 编号与权重merge_typemean表示均值合并Sharpnessmodel_id 5负责保证清晰度三者融合可获得精美画面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)结构控制 图像编辑 色彩调节ControlNetmodel_id 1控制构图Editmodel_id 2保留原图的毛发纹理等细节SoftRGBmodel_id 4通过R/G/B三个通道分量控制画面色调可以渲染出极具艺术感的画面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)亮度控制 图像编辑 局部重绘Brightnessmodel_id 0负责生成明亮的画面Editmodel_id 2参考原图布局Inpaintmodel_id 6通过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)Template 模型的格式与加载机制了解 Template 模型的内部格式有助于排查加载问题。一个完整的 Template 模型目录结构为Template_Model ├── model.py └── model.safetensors其中model.py是模型入口model.safetensors是权重文件。加载流程diffsynth/diffusion/template.py会动态执行model.py读取其中的约定属性TEMPLATE_MODEL模型类若定义了TEMPLATE_MODEL_PATH则通过load_model加载预训练权重否则实例化一个随机初始化模型或非模型模块TEMPLATE_MODEL_CONFIG可选模型配置TEMPLATE_DATA_PROCESSOR可选数据处理器训练流程中会用到。加载完成后还会调用check_template_model_formatdiffsynth/diffusion/template.py#L23-L31做格式校验要求模型类必须实现process_inputs和forward且两者签名都必须包含**kwargs。对应地基类TemplateModeldiffsynth/diffusion/template.py#L11-L20中process_inputs默认返回空字典forward则抛出NotImplementedError由各 Template 模型自行实现。关于如何从零构建与训练 Template 模型可参考文档 Template_Model_Training.md。底层原理Template Cache 如何驱动可控生成Diffusion Templates 的核心设计是Template Cache 是基础模型 Pipeline 输入参数的子集。框架的整体结构详见 Understanding_Diffusion_Templates.md可概括为Template Input → Template Model → Template Cache ↓ Model Input → Diffusion Pipeline → Model OutputTemplate InputTemplate 模型的输入Python 字典字段由每个 Template 模型自行定义如{scale: 0.8}Template Model可插拔的能力模块可从魔搭加载或本地加载Template CacheTemplate 模型的输出字典字段必须对应基础模型 Pipeline 的输入参数Template Pipeline负责加载多个 Template 模型、合并它们的 Template Cache并把合并结果注入基础模型 Pipeline。框架为此为基础模型 Pipeline 设计了额外的输入参数作为能力媒介其中最核心的是KV-Cache注意力缓存在序列层面可直接拼接让多个 Template 模型同时生效且对生图结果具备高权限的直接影响能力能力上限高、适配新基础模型的开发成本低。此外还支持Residual残差适合点对点控制但多残差融合可能冲突且不支持任意分辨率与LoRA本质是一系列张量作为输入参数注入而非模型权重。目前框架仅在 FLUX.2 的 Pipeline 上提供了 KV-Cache 与 LoRA 两种媒介支持。理解这一机制后组合推理时的两个实用结论便清晰了model_id即索引在template_inputs中用model_id指定使用model_configs列表中的第几个 Template 模型列表顺序决定编号因此调整模型加载顺序时需同步修改所有model_id正负侧成对出现需要 CFG 增强的 Template 输入应同时在negative_template_inputs中提供弱化版本如亮度scale0.5、锐化scale0、ControlNet/Edit 的prompt让基础模型通过两侧差异放大控制效果。至此从单模型亮度控制、CFG 增强、低显存惰性加载到多模型任意组合DiffSynth-Studio 的 Template 模型推理全流程已可以完整落地。更多官方示例脚本可直接参考 examples/flux2/model_inference/ 与examples/flux2/model_inference_low_vram/目录动手替换 prompt、图像与参数即可验证不同组合的控制效果。【免费下载链接】DiffSynth-StudioEnjoy the magic of Diffusion models!项目地址: https://gitcode.com/GitHub_Trending/dif/DiffSynth-Studio创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表