使用 Diffusers 运行 HunyuanImage-2.1:APG 引导、蒸馏加速与 Refiner 精修的完整指南
发布时间:2026/9/11 21:59:12 作者:尧图编辑部 阅读量:1,286

使用 Diffusers 运行 HunyuanImage-2.1APG 引导、蒸馏加速与 Refiner 精修的完整指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusersHunyuanImage-2.1 是腾讯 Hunyuan 团队推出的 17B 参数文生图扩散模型原生支持 2048 × 20482K分辨率图像生成在 diffusers 中通过HunyuanImagePipeline与HunyuanImageRefinerPipeline两套管线对外提供推理能力。本文以 docs/source/en/api/pipelines/hunyuanimage21.md 为主线结合 src/diffusers/pipelines/hunyuan_image/ 下的源码实现与 tests/pipelines/hunyuan_image_21/test_hunyuanimage.py 测试用例完整讲解三个官方变体的加载方式、Guider 引导机制、蒸馏版参数用法与精修流程。读完本文你将掌握在 diffusers 中端到端运行 HunyuanImage-2.1 全家族模型、动态调整引导强度、生成带精准文字的图像以及用 Refiner 对结果做二次精修的全部方法。模型概览与三个官方变体HunyuanImage-2.1 是一个 17B 参数的文生图模型核心能力是在 2K 分辨率2048 × 2048下生成高质量图像并且针对文字渲染OCR/字形生成做了专门设计。官方共提供三个 diffusers 格式的变体对应不同的使用场景模型类型模型 IDHugging Face Hub定位HunyuanImage-2.1hunyuanvideo-community/HunyuanImage-2.1-Diffusers完整版基础模型配合 APG CFG 引导HunyuanImage-2.1-Distilledhunyuanvideo-community/HunyuanImage-2.1-Distilled-Diffusers引导蒸馏版只需 8 步采样速度更快HunyuanImage-2.1-Refinerhunyuanvideo-community/HunyuanImage-2.1-Refiner-Diffusers精修器对已生成图像做细节增强三个变体共享同一套双文本编码器架构但调用参数不同基础版通过guider对象控制引导蒸馏版通过distilled_guidance_scale参数直接传入引导强度Refiner 则额外接受输入图像。下文分别展开。加载与推理三分钟跑通基础版基础版HunyuanImagePipeline的使用与 diffusers 其他管线一致通过from_pretrained加载并建议使用torch.bfloat16精度以降低显存占用import torch from diffusers import HunyuanImagePipeline pipe HunyuanImagePipeline.from_pretrained( hunyuanvideo-community/HunyuanImage-2.1-Diffusers, dtypetorch.bfloat16 ) pipe pipe.to(cuda) # 或 mps、xpu、cpu从源码结构看该管线由六个核心组件构成其注册关系见 pipeline_hunyuanimage.py 的__init__方法组件类型职责transformerHunyuanImageTransformer2DModel条件 TransformerMMDiT主干负责去噪schedulerFlowMatchEulerDiscreteSchedulerFlow Matching Euler 离散采样器vaeAutoencoderKLHunyuanImage图像与潜空间的双向编解码text_encoder/tokenizerQwen2.5-VL-7B-Instruct/Qwen2Tokenizer主文本编码器语义理解text_encoder_2/tokenizer_2T5EncoderModel/ByT5Tokenizer字形Glyph文本编码器文字渲染guider/ocr_guiderAdaptiveProjectedMixGuidanceAPG CFG 引导器可选组件其中guider与ocr_guider被声明为可选组件见源码中的_optional_components这是因为蒸馏版模型不使用传统引导方式。管线默认的 CPU offload 顺序为text_encoder-text_encoder_2-transformer-vae显存紧张时可直接调用pipe.enable_model_cpu_offload()自动按序卸载。核心机制为什么没有 guidance_scale 参数与 Stable Diffusion 等传统管线不同调用HunyuanImagePipeline时不能传guidance_scale。原因在于HunyuanImage-2.1 在去噪循环中采用的是Adaptive Projected GuidanceAPG与 Classifier-Free GuidanceCFG的组合引导该引导逻辑被封装为独立的guider组件在管线运行时动态管理。这一点在官方文档中有明确说明并且可以从源码中得到印证在 pipeline_hunyuanimage.py 的去噪循环中每个采样步都依次执行收集模型输入 → 更新 guider 内部状态guider.set_state→ 按引导方式切分条件/无条件批次guider.prepare_inputs→ 逐批次运行 transformer → 按引导公式合并预测guider(guider_state)最终才交给scheduler.step推进去噪。CFG 的合并公式即经典的noise_pred pred_uncond guidance_scale * (pred_cond - pred_uncond)而 APG 部分则在此基础上叠加动量缓冲与投影重缩放。加载管线后可以直接打印guider对象查看其完整配置与内部状态 pipe.guider AdaptiveProjectedMixGuidance { _class_name: AdaptiveProjectedMixGuidance, _diffusers_version: 0.36.0.dev0, adaptive_projected_guidance_momentum: -0.5, adaptive_projected_guidance_rescale: 10.0, adaptive_projected_guidance_scale: 10.0, adaptive_projected_guidance_start_step: 5, enabled: true, eta: 0.0, guidance_rescale: 0.0, guidance_scale: 3.5, start: 0.0, stop: 1.0, use_original_formulation: false } State: step: None num_inference_steps: None timestep: None count_prepared: 0 enabled: True num_conditions: 2 momentum_buffer: None is_apg_enabled: False is_cfg_enabled: True这些字段的语义与默认值在 adaptive_projected_guidance_mix.py 的类文档中有详细定义关键参数如下参数默认值作用guidance_scale3.5CFG 引导强度越大对提示词的遵从越强过大会导致过饱和与画质劣化guidance_rescale0.0CFG 噪声预测的重缩放因子用于修正过曝问题adaptive_projected_guidance_scale10.0APG 投影引导强度adaptive_projected_guidance_momentum-0.5APG 动量参数设为None可禁用adaptive_projected_guidance_rescale10.0APG 噪声预测重缩放因子adaptive_projected_guidance_start_step5APG 生效的起始步此前仅使用 CFG 并更新动量缓冲start/stop0.0 / 1.0CFG 生效的去噪步比例区间use_original_formulationFalse是否使用论文原始 CFG 公式默认使用 diffusers 原生实现enabledTrue是否启用引导动态调整引导强度guider.new() 的用法由于引导参数不再通过管线调用参数暴露调整guidance_scale等数值的正确方式是使用 guider 的new()方法生成新配置并重新赋值给pipe.guider。new()是 guider_utils.py 中BaseGuidance提供的配置克隆方法只更新传入的字段其余保持默认。例如要以guidance_scale5.0生成一张 2048 × 2048 的 2K 图像同时保持其他引导参数不变import torch from diffusers import HunyuanImagePipeline pipe HunyuanImagePipeline.from_pretrained( hunyuanvideo-community/HunyuanImage-2.1-Diffusers, dtypetorch.bfloat16 ) pipe pipe.to(cuda) # 或 mps、xpu、cpu # 更新 guider 配置只修改 guidance_scale其余参数沿用默认值 pipe.guider pipe.guider.new(guidance_scale5.0) prompt ( A cute, cartoon-style anthropomorphic penguin plush toy with fluffy fur, standing in a painting studio, wearing a red knitted scarf and a red beret with the word Tencent on it, holding a paintbrush with a focused expression as it paints an oil painting of the Mona Lisa, rendered in a photorealistic photographic style. ) image pipe( promptprompt, num_inference_steps50, height2048, width2048, ).images[0] image.save(image.png)这种设计使引导策略与推理参数解耦你可以预先构造多套guider配置不同guidance_scale、不同adaptive_projected_guidance_start_step在批量生成时灵活切换。测试用例 test_hunyuanimage.py 中的test_inference_guider正是通过pipe.guider pipe.guider.new(guidance_scale1000)和pipe.ocr_guider pipe.ocr_guider.new(guidance_scale1000)验证了该 API 的可用性与数值可复现性。文字渲染OCR Guider 与字形提取机制HunyuanImage-2.1 对图像中的文字渲染做了专门优化。管线的encode_prompt流程pipeline_hunyuanimage.py会从提示词中提取引号包裹的文本交给 ByT5 T5EncoderModel 生成字形Glyph嵌入与 Qwen2.5-VL 生成的语义嵌入一起送入 transformerextract_glyph_textpipeline_hunyuanimage.py通过正则匹配单引号、双引号、中文单引号 与中文双引号 内的文本将其格式化为Text xxx序列若提示词中没有引号文本则字形嵌入与掩码全部置零管线退化为纯语义引导若提示词中存在字形文本且管线带有ocr_guider去噪时会自动切换到ocr_guider执行引导见 pipeline_hunyuanimage.py 的 guider 选择逻辑。这意味着要实现精准的文字渲染只需在提示词中把目标文字用引号括起来即可例如把上面的示例提示词中the word Tencent部分换成任意希望出现在画面中的文字。ocr_guider与guider均为AdaptiveProjectedMixGuidance类型可以分别用new()独立调整各自的引导参数。蒸馏版8 步采样的 distilled_guidance_scale对于追求速度的场景官方提供了引导蒸馏版本HunyuanImage-2.1-Distilled-Diffusers。蒸馏版不再使用 APG CFG 引导器而是将引导强度直接作为模型前向输入。因此调用方式有两点关键差异不需要也不应调整pipe.guider从源码看当管线没有guider时会回退到AdaptiveProjectedMixGuidance(enabledFalse)引导被禁用必须传distilled_guidance_scale若 transformer 配置了guidance_embeds而未提供该参数管线会直接抛出ValueError: distilled_guidance_scale is required for guidance-distilled model见 pipeline_hunyuanimage.py。该值会在前向时乘以 1000 作为引导嵌入输入模型。官方示例仅需 8 步即可出图import torch from diffusers import HunyuanImagePipeline pipe HunyuanImagePipeline.from_pretrained( hunyuanvideo-community/HunyuanImage-2.1-Distilled-Diffusers, dtypetorch.bfloat16 ) pipe pipe.to(cuda) # 或 mps、xpu、cpu prompt ( A cute, cartoon-style anthropomorphic penguin plush toy with fluffy fur, standing in a painting studio, wearing a red knitted scarf and a red beret with the word Tencent on it, holding a paintbrush with a focused expression as it paints an oil painting of the Mona Lisa, rendered in a photorealistic photographic style. ) out pipe( prompt, num_inference_steps8, distilled_guidance_scale3.25, height2048, width2048, generatorgenerator, ).images[0]关于distilled_guidance_scale的取值规律源码 docstring 的说明是distilled_guidance_scale 1时启用引导数值越大图像与提示词越贴合但通常以牺牲画质为代价对于非蒸馏模型该参数会被忽略。测试 test_hunyuanimage.py 中的test_inference_with_distilled_guidance即为该路径的回归验证。注意官方示例中generator需自行定义如torch.Generator().manual_seed(0)以保证可复现性。Refiner 精修对已生成图像做细节增强HunyuanImageRefinerPipelinepipeline_hunyuanimage_refiner.py用于对已有图像进行精修可显著提升细节与质感。与主管线相比它有以下几个实现上的特点接受输入图像__call__提供image参数PipelineImageInput图像经 VAE 编码为潜变量局部加噪强度控制prepare_latents中通过strength默认 0.25按cond_latents strength * noise (1 - strength) * image_latents混合初始潜变量控制精修幅度潜变量重排精修器在送入 transformer 前对图像 token 做_reorder_image_tokens重排解码前用_restore_image_tokens_order恢复顺序仅支持蒸馏式引导该管线强制要求distilled_guidance_scale缺失时直接报错默认num_inference_steps4组件更精简只有text_encoderQwen2.5-VLtransformervaescheduler无需 ByT5 字形编码器CPU offload 顺序为text_encoder-transformer-vae。官方 docstring 中的最小调用示例图片加载函数load_image来自 diffusers 工具模块import torch from diffusers import HunyuanImageRefinerPipeline pipe HunyuanImageRefinerPipeline.from_pretrained( hunyuanvideo-community/HunyuanImage-2.1-Refiner-Diffusers, torch_dtypetorch.bfloat16 ) pipe.to(cuda) prompt A cat holding a sign that says hello world image load_image(path/to/image.png) image pipe(prompt, imageimage, num_inference_steps4).images[0] image.save(hunyuanimage.png)一个完整的实战流程通常是先用基础版50 步 APG/CFG或蒸馏版8 步生成初稿再把初稿交给 Refiner 做 4 步精修兼顾速度与画质。完整调用参数速查HunyuanImagePipeline.__call__的核心参数完整签名见 pipeline_hunyuanimage.py参数默认值说明promptNone提示词str或list[str]与prompt_embeds二选一negative_promptNone负面提示词不传时使用空串height/width2048输出尺寸默认64 * vae_scale_factorvae_scale_factor 为 32需能被 64 整除num_inference_steps50去噪步数越多画质越高、速度越慢distilled_guidance_scale3.25蒸馏版引导强度仅对guidance_embeds模型生效sigmasNone自定义 sigma 调度覆盖默认线性 1.0→0.0 调度num_images_per_prompt1每个提示词生成的图像数generatorNonetorch.Generator或列表用于复现latentsNone预生成噪声潜变量可用于固定构图跨提示词复用prompt_embeds/prompt_embeds_2None预生成的语义/字形嵌入支持提示词加权等高级玩法output_typepil输出格式pil、np、latentreturn_dictTrue为 False 时返回普通 tupleattention_kwargsNone透传给AttentionProcessor的参数字典callback_on_step_endNone每步结束回调可配合latents/prompt_embeds张量做中间状态干预输出为HunyuanImagePipelineOutput见 pipeline_output.py其中images是batch_size张去噪后的 PIL 图像列表或 numpy 数组。管线还暴露了num_timesteps与current_timestep两个属性供回调函数读取当前采样进度。性能与显存优化提示官方文档特别提示缓存Caching优化可以显著加速推理其原理是存储并复用中间输出避免重复计算。具体配置方法见 缓存优化指南。此外结合本仓库的通用优化手段可按需组合显存紧张时使用pipe.enable_model_cpu_offload()管线会按text_encoder-text_encoder_2-transformer-vae的顺序自动调度低精度推理时保持torch.bfloat16Apple Silicon 上使用mps设备时源码中对潜变量做了 dtype 回迁处理以规避 PyTorch 平台 bug追求吞吐量时优先选择蒸馏版 Refiner 的两段式流程把最重的 50 步采样替换为 8 步 4 步若开启 torch_xlaXPU 环境管线会在每个采样步调用xm.mark_step()同步计算图见 pipeline_hunyuanimage.py。进一步阅读管线 API 参考HunyuanImagePipeline、HunyuanImageRefinerPipeline与HunyuanImagePipelineOutput的完整文档位于 docs/source/en/api/pipelines/hunyuanimage21.md源码实现pipeline_hunyuanimage.py、pipeline_hunyuanimage_refiner.py引导器实现adaptive_projected_guidance_mix.py更全面的 Guider 体系介绍见 Guider 指南回归测试tests/pipelines/hunyuan_image_21/test_hunyuanimage.py包含基础推理、guider 参数热更新、蒸馏引导三条关键路径的数值断言【免费下载链接】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),仅供参考