资讯动态

diffusers 中 Stable Diffusion 3 的 ControlNet 管线:StableDiffusion3ControlNetPipeline 深度解析与实战指南

发布时间:2026/9/10 15:52:56 来源:尧图企业网站定制
diffusers 中 Stable Diffusion 3 的 ControlNet 管线StableDiffusion3ControlNetPipeline 深度解析与实战指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers本文围绕 diffusers 仓库中 docs/source/en/api/pipelines/controlnet_sd3.md 所定义的 ControlNet for Stable Diffusion 3 实现展开系统讲解StableDiffusion3ControlNetPipeline与StableDiffusion3ControlNetInpaintingPipeline两条管线的架构、可用官方权重、完整调用方式与核心参数语义。读完本文你将掌握如何在 SD3 的 MMDiT 架构上叠加 Canny、Depth、Pose、Tile 与 Inpainting 等空间条件控制理解 ControlNet 条件如何经过 VAE 编码进入去噪循环并能够结合仓库源码定位关键实现。ControlNet 与 Stable Diffusion 3为什么需要空间条件控制ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在论文 Adding Conditional Control to Text-to-Image Diffusion ModelsarXiv 2302.05543中提出。其核心思想是将生产就绪的大型扩散模型冻结作为主干在保留其海量图像预训练编码能力的同时通过额外可学习的控制分支学习多样化的条件控制边缘、深度、分割、人体姿态等。论文摘要原文We present ControlNet, a neural network architecture to add spatial conditioning controls to large, pretrained text-to-image diffusion models. ControlNet locks the production-ready large diffusion models, and reuses their deep and robust encoding layers pretrained with billions of images as a strong backbone to learn a diverse set of conditional controls. The neural architecture is connected with zero convolutions (zero-initialized convolution layers) that progressively grow the parameters from zero and ensure that no harmful noise could affect the finetuning. We test various conditioning controls, eg, edges, depth, segmentation, human pose, etc, with Stable Diffusion, using single or multiple conditions, with or without prompts. We show that the training of ControlNets is robust with small (50k) and large (1m) datasets. Extensive results show that ControlNet may facilitate wider applications to control image diffusion models.在 diffusers 中StableDiffusion3ControlNetPipeline就是 ControlNet 架构在 Stable Diffusion 3 上的实现。与 SD1.x/SDXL 的 UNet 不同SD3 使用基于 MMDiTMultimodal Diffusion Transformer的SD3Transformer2DModel作为去噪主干因此 ControlNet 分支也改为与 MMDiT 对应的 Joint Transformer Block 结构详见下文源码解析。有了 ControlNet你可以额外提供一张控制图例如深度图来约束生成——模型会尽量保留深度图中的空间信息从而以更灵活、更准确的方式控制图像生成过程。官方预训练权重一览本文档对应的 ControlNet 代码主要由 The InstantX Team 实现其中 Inpainting 相关代码由 The Alimama Creative Team 开发。社区可直接使用的 SD3-ControlNet 预训练检查点如下ControlNet 类型开发者模型链接CannyThe InstantX TeamInstantX/SD3-Controlnet-CannyDepthThe InstantX TeamInstantX/SD3-Controlnet-DepthPoseThe InstantX TeamInstantX/SD3-Controlnet-PoseTileThe InstantX TeamInstantX/SD3-Controlnet-TileInpaintingThe AlimamaCreative Teamalimama-creative/SD3-Controlnet-Inpainting[!TIP] 在使用调度器前建议先阅读 diffusers 的 Schedulers 指南了解调度器速度与质量的权衡方法同时在 跨管线复用组件 一节中学习如何高效地在多条管线间共享同一批模型组件例如复用已加载的 VAE 与文本编码器。管线架构与关键源码位置与 SD3 家族其他管线一致ControlNet 管线同样由三文本编码器 MMDiT VAE Flow Matching 调度器构成。从 pipeline_stable_diffusion_3_controlnet.py 的类构造签名可见其完整组件清单transformerSD3Transformer2DModelMMDiT负责对编码后的图像潜变量去噪schedulerFlowMatchEulerDiscreteScheduler配合transformer完成去噪vaeAutoencoderKL在图像与潜空间之间编解码text_encoder/text_encoder_2两个CLIPTextModelWithProjection分别为 clip-vit-large-patch14 与 laion/CLIP-ViT-bigG-14 变体text_encoder_3T5EncoderModelt5-v1_1-xxl 变体tokenizer/tokenizer_2/tokenizer_3对应三个文本编码器的分词器controlnetSD3ControlNetModel也支持以list[SD3ControlNetModel]或SD3MultiControlNetModel形式传入多个 ControlNet此时各 ControlNet 的输出相加组成联合条件image_encoder/feature_extractor可选IP-Adapter 使用的SiglipVisionModel与SiglipImageProcessor。管线还声明了model_cpu_offload_seq text_encoder-text_encoder_2-text_encoder_3-image_encoder-transformer-vae即 CPU offload 时按此顺序逐个搬运模块帮助在显存受限环境下运行。此外类混入了SD3LoraLoaderMixin、FromSingleFileMixin与SD3IPAdapterMixin意味着可以叠加 LoRA、从单文件权重加载并配合 IP-Adapter 使用。值得注意的构造细节当传入的 ControlNet 配置中use_pos_embedFalse例如 SD3.5 8B 的官方 ControlNet时管线会在__init__中直接从transformer上提取共享的pos_embed并注入 ControlNet 模型实现位置编码复用见 pipeline_stable_diffusion_3_controlnet.py。SD3ControlNetModel 的模型结构ControlNet 分支本身定义在 src/diffusers/models/controlnets/controlnet_sd3.py 的SD3ControlNetModel中另有SD3MultiControlNetModel用于多 ControlNet 组合。其核心配置参数包括sample_size默认 128潜变量的宽/高训练时固定用于学习位置编码patch_size默认 2Patch Embedding 的切块大小in_channels默认 16输入潜变量通道数num_layers默认 18Transformer Block 层数attention_head_dim默认 64与num_attention_heads默认 18多头注意力配置joint_attention_dim默认 4096图文联合注意力的嵌入维度caption_projection_dim默认 1152与pooled_projection_dim默认 2048文本条件投影维度extra_conditioning_channels默认 0Patch Embedding 的额外条件通道数——Inpainting 模型正是通过将其设为 1 来接收拼接的 mask 通道qk_norm可选注意力 Q/K 归一化方式如rms_normforce_zeros_for_pooled_projection默认 True是否强制 pooled 投影为零——InstantX 的 SD3 ControlNet 即采用零 pooled 投影管线会读取该配置决定是否用torch.zeros_like(pooled_prompt_embeds)替代文本投影见管线源码中force_zeros_for_pooled_projection分支。结构上SD3ControlNetModel由PatchEmbed位置编码、CombinedTimestepTextProjEmbeddings时间步与文本投影融合、context_embedder以及一串JointTransformerBlock/SD3SingleTransformerBlock组成输出SD3ControlNetOutput.controlnet_block_samples供主干 Transformer 的block_controlnet_hidden_states使用。基础用法Canny 边缘引导文生图文档源码中给出了完整可运行示例见 pipeline_stable_diffusion_3_controlnet.pyimport torch from diffusers import StableDiffusion3ControlNetPipeline from diffusers.models import SD3ControlNetModel, SD3MultiControlNetModel from diffusers.utils import load_image controlnet SD3ControlNetModel.from_pretrained(InstantX/SD3-Controlnet-Canny, torch_dtypetorch.float16) pipe StableDiffusion3ControlNetPipeline.from_pretrained( stabilityai/stable-diffusion-3-medium-diffusers, controlnetcontrolnet, torch_dtypetorch.float16 ) pipe.to(cuda) control_image load_image( https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png ) prompt A bird in space image pipe( prompt, control_imagecontrol_image, height1024, width768, controlnet_conditioning_scale0.7 ).images[0] image.save(sd3.png)要点说明SD3ControlNetModel.from_pretrained仅加载 ControlNet 分支随后通过StableDiffusion3ControlNetPipeline.from_pretrained(..., controlnetcontrolnet)将其注入 SD3 主干管线实现组件复用式组装显存有限时可把pipe.to(cuda)换成pipe.enable_model_cpu_offload()管线会按照model_cpu_offload_seq顺序做 CPU offloadcontrol_image会被VaeImageProcessor.preprocess预处理到与height/width一致的分辨率再送入 VAE 编码为潜变量官方示例对 Canny 控制使用controlnet_conditioning_scale0.7即控制强度低于默认值 1.0避免结构约束过强导致画面呆板。核心参数与语义详解StableDiffusion3ControlNetPipeline.__call__源码见 pipeline_stable_diffusion_3_controlnet.py在 SD3 标准参数之上增加了 ControlNet 专属参数下表整理了关键项及其默认值参数默认值说明prompt/prompt_2/prompt_3None分别送入两个 CLIP 编码器与 T5 编码器的提示词缺省时全部复用promptheight/width由default_sample_size * vae_scale_factor决定生成图像分辨率check_inputs强制要求能被 8 整除num_inference_steps28去噪步数更多步数通常质量更高但推理更慢sigmasNone自定义 sigma 调度仅支持在set_timesteps中接收sigmas参数的调度器guidance_scale7.0CFG 引导强度 1时启用无分类器引导数值越高越贴近提示词但可能牺牲图像质量control_imageNone控制条件图支持torch.Tensor、PIL.Image.Image、np.ndarray及其列表传入 Tensor 时按原样交给 ControlNetcontrol_mask仅 InpaintingNone修复蒙版图白色像素被重绘黑色像素被保留controlnet_conditioning_scale1.0ControlNet 输出在加入主干残差前乘上的权重多 ControlNet 时传列表control_guidance_start/control_guidance_end0.0/1.0ControlNet 生效的时间步百分比区间多 ControlNet 时传列表controlnet_pooled_projectionsNone条件输入投影后的嵌入形状(batch_size, projection_dim)num_images_per_prompt1每个提示词生成的图像数量generatorNone一个或多个torch.Generator用于可复现生成latentsNone预先生成的噪声潜变量可用于固定构图、跨提示词复用prompt_embeds/negative_prompt_embeds/pooled_prompt_embeds/negative_pooled_prompt_embedsNone预计算文本嵌入传入prompt_embeds时必须同时传pooled_prompt_embeds源码check_inputs强制校验ip_adapter_image/ip_adapter_image_embedsNoneIP-Adapter 参考图或预计算图像嵌入需配合 IP-Adapter 权重使用output_typepil输出格式可选pil、np或latentreturn_dictTrue为True时返回StableDiffusion3PipelineOutput否则返回裸 tuplejoint_attention_kwargsNone透传给 AttentionProcessor 的额外关键字参数例如 IP-Adapter 图像嵌入clip_skipNone从 CLIP 末尾跳过的层数1表示使用倒数第二层输出callback_on_step_end/callback_on_step_end_tensor_inputsNone/[latents]每步去噪结束后的回调可用张量集合由_callback_tensor_inputslatents、prompt_embeds、negative_prompt_embeds、negative_pooled_prompt_embeds限定max_sequence_length256T5 编码的最大序列长度上限 512几个来自源码的约束值得留意见check_inputsheight/width必须能被 8 整除否则抛出ValueErrorprompt与prompt_embeds不能同时传入二者必须二选一negative_prompt的 batch 大小必须与prompt一致max_sequence_length不能大于 512多 ControlNet 场景下control_guidance_start/control_guidance_end长度必须与 ControlNet 数量一致且每个区间的start end、start 0、end 1。多 ControlNet 组合控制如果你希望同时使用多种空间条件例如 Canny 边缘 Depth 深度可以直接传入 ControlNet 列表。管线在__init__中会自动将list/tuple包装为SD3MultiControlNetModel并将各分支输出相加作为联合条件controlnet_canny SD3ControlNetModel.from_pretrained(InstantX/SD3-Controlnet-Canny, torch_dtypetorch.float16) controlnet_depth SD3ControlNetModel.from_pretrained(InstantX/SD3-Controlnet-Depth, torch_dtypetorch.float16) pipe StableDiffusion3ControlNetPipeline.from_pretrained( stabilityai/stable-diffusion-3-medium-diffusers, controlnet[controlnet_canny, controlnet_depth], torch_dtypetorch.float16, )多 ControlNet 时需注意control_image必须传列表列表长度与 ControlNet 数量一致每个元素对应一个控制图controlnet_conditioning_scale与control_guidance_start/control_guidance_end同样可传列表实现每个控制分支各自不同的强度与生效区间在去噪循环中管线会按步计算controlnet_keep张量基于control_guidance_start/end的步进比例再与controlnet_conditioning_scale逐元素相乘得到当步实际cond_scale见 pipeline_stable_diffusion_3_controlnet.py。Inpainting 管线掩码引导的局部重绘StableDiffusion3ControlNetInpaintingPipeline源码见 pipeline_stable_diffusion_3_controlnet_inpainting.py在基础管线之上增加了control_mask参数用于局部重绘。与通用 ControlNet 将整张控制图编码进潜空间不同Inpainting 版通过prepare_image_with_mask完成以下处理见源码 L822-L879图像与 mask 分别经image_processorRGB、归一化与mask_processor灰度、二值化预处理到目标尺寸将 mask 中大于 0.5 的区域在原图上置为-1得到被遮罩图像用 VAE 将遮罩图像编码为潜变量再按(latents - shift_factor) * scaling_factor缩放mask 被双线性插值到潜空间分辨率并取反mask 1 - mask将图像潜变量与 mask 通道沿通道维拼接control_image torch.cat([image_latents, mask], dim1)—— 这正是加载 Inpainting 权重时需要设置extra_conditioning_channels1的原因。官方示例见源码 docstring L59-L102import torch from diffusers.utils import load_image, check_min_version from diffusers.pipelines import StableDiffusion3ControlNetInpaintingPipeline from diffusers.models.controlnet_sd3 import SD3ControlNetModel controlnet SD3ControlNetModel.from_pretrained( alimama-creative/SD3-Controlnet-Inpainting, use_safetensorsTrue, extra_conditioning_channels1 ) pipe StableDiffusion3ControlNetInpaintingPipeline.from_pretrained( stabilityai/stable-diffusion-3-medium-diffusers, controlnetcontrolnet, torch_dtypetorch.float16, ) pipe.text_encoder.to(torch.float16) pipe.controlnet.to(torch.float16) pipe.to(cuda) image load_image( https://huggingface.co/alimama-creative/SD3-Controlnet-Inpainting/resolve/main/images/dog.png ) mask load_image( https://huggingface.co/alimama-creative/SD3-Controlnet-Inpainting/resolve/main/images/dog_mask.png ) width 1024 height 1024 prompt A cat is sitting next to a puppy. generator torch.Generator(devicecuda).manual_seed(24) res_image pipe( negative_promptdeformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, mutated hands and fingers, disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, NSFW, promptprompt, heightheight, widthwidth, control_imageimage, control_maskmask, num_inference_steps28, generatorgenerator, controlnet_conditioning_scale0.95, guidance_scale7, ).images[0] res_image.save(sd3.png)实操提示Inpainting 场景下官方示例将controlnet_conditioning_scale设为 0.95、guidance_scale设为 7并配合较长的手部/解剖学负向提示词以抑制常见伪影。管线在check_inputs中还校验了多 ControlNet 时 mask 与图像数量的一致性。去噪循环的底层原理从源码可以还原__call__的完整执行流程编号注释与源码一致检查输入check_inputs校验尺寸、提示词/嵌入二选一、CFG 批次一致性、max_sequence_length ≤ 512等编码提示词encode_prompt分别经两个 CLIP 编码器与 T5 编码器得到prompt_embeds与pooled_prompt_embedsCLIP 输出与 T5 输出按序列维拼接CFG 开启时再拼接负向嵌入准备控制图prepare_image预处理控制图后用 VAE 编码为潜变量并做shift_factor/scaling_factor缩放InstantX 权重因force_zeros_for_pooled_projectionTrue而令vae_shift_factor0Inpainting 版则走prepare_image_with_mask拼接 mask 通道准备时间步retrieve_timesteps调用调度器set_timesteps获取去噪时间步支持自定义sigmas/timesteps准备潜变量prepare_latents按batch × channels × height/vae_scale_factor × width/vae_scale_factor采样高斯噪声构建 controlnet_keep按control_guidance_start/end计算每一步各 ControlNet 的生效系数可选IP-Adapter 图像嵌入若激活 IP-Adapter则把图像嵌入放入joint_attention_kwargs去噪循环每个时间步先让 ControlNet 产出control_block_samples再将其以block_controlnet_hidden_states传入SD3Transformer2DModel计算noise_pred随后执行 CFG 插值noise_pred_uncond guidance_scale * (noise_pred_text - noise_pred_uncond)最后交给FlowMatchEulerDiscreteScheduler.step得到下一步潜变量解码输出潜变量经(latents / scaling_factor) shift_factor逆缩放后由 VAE 解码再经image_processor.postprocess输出 PIL 图像最终包装为StableDiffusion3PipelineOutput定义于 src/diffusers/pipelines/stable_diffusion_3/pipeline_output.py。关于 ControlNet 与主干的交互还有一个实现细节当 ControlNet 配置的joint_attention_dim非空时文本嵌入prompt_embeds会作为controlnet_encoder_hidden_states传入 ControlNet 的联合注意力而 SD3.5 官方 8B ControlNet 不接收encoder_hidden_states此时传None见 pipeline_stable_diffusion_3_controlnet.py。测试用例与工程验证仓库为这两条管线提供了完整的单元测试可用于验证上述行为tests/pipelines/controlnet_sd3/test_controlnet_sd3.py覆盖StableDiffusion3ControlNetPipeline通过get_dummy_components构造迷你 Transformersample_size32、patch_size1、qk_normrms_norm与迷你 ControlNet验证输出的张量形状、批次参数支持prompt、negative_prompt以及多 ControlNetSD3MultiControlNetModel路径tests/pipelines/controlnet_sd3/test_controlnet_inpaint_sd3.py覆盖 Inpainting 管线的 mask 预处理、extra_conditioning_channels1拼接逻辑与输出正确性。这些测试同时印证了管线对外暴露的required_input_params_in_call_signatureprompt、height、width、guidance_scale、negative_prompt、prompt_embeds、negative_prompt_embeds——它们共同构成了管线可复现运行的最小契约。总结StableDiffusion3ControlNetPipeline与StableDiffusion3ControlNetInpaintingPipeline将 ControlNet 的空间条件控制能力完整地带到了 Stable Diffusion 3 的 MMDiT 架构上既保留了 SD3 三文本编码器与 Flow Matching 调度器的生成质量又通过SD3ControlNetModel分支实现了 Canny、Depth、Pose、Tile 与 Inpainting 五种开箱即用的官方权重。配合多 ControlNet 组合、controlnet_conditioning_scale/control_guidance_start/end的细粒度调节以及 IP-Adapter、LoRA 等既有生态能力的叠加它适合作为图像编辑、局部重绘、结构可控生成等生产场景的落地方案。深入阅读 controlnet_sd3 管线目录 与 SD3 ControlNet 模型 源码可以进一步理解每一步条件注入的底层机制。【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价