资讯动态

Diffusers 中 SANA-Sprint 流水线实战:一步生成、量化加速与图像编辑

发布时间:2026/9/12 5:17:37 来源:尧图企业网站定制
Diffusers 中 SANA-Sprint 流水线实战一步生成、量化加速与图像编辑【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers本篇技术指南围绕 Hugging Face Diffusers 仓库中 SANA-Sprint 官方文档 展开深入讲解如何在当前项目中以 1~4 步完成超快速文生图T2I推理、通过 bitsandbytes 进行 8-bit 量化以降低显存占用、调节max_timesteps平衡画质与速度并使用SanaSprintImg2ImgPipeline完成基于输入图片与提示词的图像编辑。读者读完后可以独立复现完整的文本到图像、图像到图像推理流程并理解其背后的 sCMcontinuous-time consistency distillation连续时间一致性蒸馏原理与源码级实现细节。SANA-Sprint 是什么SANA-Sprint 是由 NVIDIA、MIT HAN Lab 与 Hugging Face 合作提出的一步式高效扩散模型论文标题为SANA-Sprint: One-Step Diffusion with Continuous-Time Consistency Distillation论文编号 2503.09641。它构建在预训练的 Sana 基础模型之上通过混合蒸馏hybrid distillation将推理步数从 20 步大幅压缩到 1~4 步实现超快速文本到图像生成。其核心创新点可概括为三点训练免费的连续时间一致性蒸馏sCM无需从头训练即可将预训练的 flow-matching 模型转换为 sCM 模型显著提升训练效率。混合蒸馏策略将 sCM 与潜在对抗蒸馏LADD结合——sCM 保证与教师模型对齐LADD 增强单步生成的保真度。统一的自适应步数模型同一个模型在 1~4 步内都能产出高质量结果无需针对特定步数单独训练。与 ControlNet 集成支持实时交互式图像生成为用户交互提供即时视觉反馈。根据论文公开的结果SANA-Sprint 在单步推理时达到 7.59 FID 与 0.74 GenEval优于 FLUX-schnell7.94 FID / 0.71 GenEval且推理速度约为其 10 倍在 H100 上生成 1024×1024 图像仅需约 0.1 秒T2I与 0.25 秒ControlNet在 RTX 4090 上 T2I 约 0.31 秒。说明上述性能数据均引自论文摘要见 sana_sprint.md属于研究论文公开结果实际表现会因硬件、依赖版本与推理配置而异请以本地实测为准。本流水线由 lawrence-cj、shuchen Xue 与 Enze Xie 贡献原始代码库位于 NVlabs/Sana原始权重托管于Efficient-Large-Model组织。可用模型与推荐精度SANA-Sprint 在 Diffusers 中提供两个官方模型均以diffusers格式发布模型推荐精度Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffuserstorch.bfloat16Efficient-Large-Model/Sana_Sprint_0.6B_1024px_diffuserstorch.bfloat16精度约束非常重要上文推荐的 dtype 仅针对 Transformer 权重。文档明确要求——文本编码器Gemma2必须保持torch.bfloat16VAE 权重必须保持torch.bfloat16或torch.float32否则模型无法正常工作。在实际代码中这体现在推理时对 latents 使用torch.float32计算见 pipeline_sana_sprint.py而 Transformer 输入则在去噪循环内转换为其自身的transformer_dtypepipeline_sana_sprint.py最终解码时 latents 会再转到self.vae.dtypepipeline_sana_sprint.py。因此加载时请严格遵循推荐 dtype。更多模型信息可查阅Efficient-Large-Model组织下名为sana-sprint的官方模型集合。快速开始文生图推理import torch from diffusers import SanaSprintPipeline pipe SanaSprintPipeline.from_pretrained( Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers, torch_dtypetorch.bfloat16, ) pipe.to(cuda) image pipe(prompta tiny astronaut hatching from an egg on the moon)[0] image[0].save(output.png)这是仓库源码中SanaSprintPipeline官方示例pipeline_sana_sprint.py的完整形态。pipe(...)返回的SanaPipelineOutput中images字段为生成图片列表也可直接按下标索引取第一张。源码视角SanaSprintPipeline 的结构与调用链SanaSprintPipeline定义于 src/diffusers/pipelines/sana/pipeline_sana_sprint.py它继承自DiffusionPipeline与SanaLoraLoaderMixin后者使其天然支持 Sana 系 LoRA 加载。其模块组合为tokenizerGemma tokenizerGemmaTokenizer/GemmaTokenizerFasttext_encoderGemma2 预训练模型vaeAutoencoderDCDC-AE 自编码器transformerSanaTransformer2DModelschedulerDPMSolverMultistepSchedulerPipeline 内部通过register_modules注册以上组件并设置了model_cpu_offload_seq text_encoder-transformer-vae这意味着调用enable_model_cpu_offload()时模型会按该顺序依次卸载到 CPU可显著降低显存占用。_callback_tensor_inputs [latents, prompt_embeds]则声明了步进回调可以访问的张量。__call__方法pipeline_sana_sprint.py的完整执行流程为输入检查check_inputs校验分辨率需能被 32 整除、prompt与prompt_embeds二选一、自定义timesteps长度必须为num_inference_steps 1等。分辨率分箱resolution binning若use_resolution_binningTrue高度与宽度会被映射到ASPECT_RATIO_1024_BIN中最接近的标准分辨率该常量来自 PixArt-Alpha 流水线pipeline_sana_sprint.py解码后再裁剪/缩回原始请求尺寸方便生成非方形图。提示词编码encode_prompt内部调用_get_gemma_prompt_embeds支持clean_caption需安装beautifulsoup4与ftfy与complex_human_instruction复杂人类指令用于提示词增强。时间步准备通过retrieve_timesteps调用调度器的set_timesteps并传入max_timesteps与intermediate_timesteps。latents 准备prepare_latents采样高斯噪声并乘以self.scheduler.config.sigma_data。去噪循环这是 sCM 推理的核心详见下文。解码与后处理VAE 解码后经PixArtImageProcessor后处理输出 PIL 或 numpy 数组若出现显存不足代码会提示使用pipe.vae.enable_tiling(...)开启 VAE 平铺。sCM 时间步与去噪公式SANA-Sprint 使用三角流trigflow形式的一致性模型时间参数化。在去噪循环中源码先计算 sCM 时间步scm_timestep torch.sin(timestep) / (torch.cos(timestep) torch.sin(timestep))随后对模型输入进行缩放并将模型输出通过解析式换算为噪声预测pipeline_sana_sprint.pylatent_model_input latents_model_input * torch.sqrt( scm_timestep_expanded**2 (1 - scm_timestep_expanded) ** 2 ) noise_pred ( (1 - 2 * scm_timestep_expanded) * latent_model_input (1 - 2 * scm_timestep_expanded 2 * scm_timestep_expanded**2) * noise_pred ) / torch.sqrt(scm_timestep_expanded**2 (1 - scm_timestep_expanded) ** 2) noise_pred noise_pred.float() * self.scheduler.config.sigma_data最终由self.scheduler.step(...)完成x_t - x_{t-1}的单步更新。这里sigma_data是调度器配置中噪声的标准差默认 0.5多个环节都围绕它做缩放与还原。设置 max_timesteps画质与速度的平衡旋钮max_timesteps是 SANA-Sprint 推理中最重要的超参数之一它表示 sCM 调度器使用的最大时间步值默认值为1.57080即 π/2 的近似值。该默认值是通过推理时的搜索过程inference-time search得到的论文中有详细说明。用户可以自行调节它以权衡生成结果的视觉质量image pipe(promptyour prompt, max_timesteps1.4)[0]从实现上看max_timesteps会传入调度器的set_timestepsscheduling_scm.py当intermediate_timesteps非空且步数为 2 时时间步序列被设置为[max_timesteps, intermediate_timesteps, 0]否则使用torch.linspace(max_timesteps, 0, num_inference_steps 1)生成等距时间步。代码注释还透露了一个细节sCM 原论文的默认max_timestepsarctan(80/0.5)≈1.56454而本实现选择了不同的取值1.57080这也是为什么文档建议按论文所述进行推理时搜索来确定取值。另外注意两条约束scheduling_scm.pytimesteps与max_timesteps不能同时提供intermediate_timesteps仅在num_inference_steps2时生效。对应的check_inputs校验逻辑同样位于流水线中pipeline_sana_sprint.py。量化用 bitsandbytes 8-bit 加载降低显存SANA-Sprint 1.6B 模型整体参数量较大量化是降低显存占用的有效手段。文档给出的思路是对text encoder 与 transformer 分别进行 8-bit 量化然后以这两个量化组件组装流水线import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaTransformer2DModel, SanaSprintPipeline from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel quant_config BitsAndBytesConfig(load_in_8bitTrue) text_encoder_8bit AutoModel.from_pretrained( Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers, subfoldertext_encoder, quantization_configquant_config, dtypetorch.bfloat16, ) quant_config DiffusersBitsAndBytesConfig(load_in_8bitTrue) transformer_8bit SanaTransformer2DModel.from_pretrained( Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers, subfoldertransformer, quantization_configquant_config, dtypetorch.bfloat16, ) pipeline SanaSprintPipeline.from_pretrained( Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers, text_encodertext_encoder_8bit, transformertransformer_8bit, dtypetorch.bfloat16, device_mapbalanced, ) prompt a tiny astronaut hatching from an egg on the moon image pipeline(prompt).images[0] image.save(sana.png)要点解析文本编码器使用transformers的BitsAndBytesConfig(load_in_8bitTrue)加载因为 Gemma2 文本编码器属于 transformers 模型Transformer 使用 Diffusers 自带的BitsAndBytesConfig注意这里做了命名别名以避免与 transformers 的同名类冲突加载因为SanaTransformer2DModel是 Diffusers 原生模型两者均通过subfoldertext_encoder/subfoldertransformer从同一个仓库中按子目录加载对应权重量化不影响精度要求——加载时依然传入dtypetorch.bfloat16device_mapbalanced让模型在多设备间均衡分布。不同量化后端bitsandbytes、GGUF、torchao 等对模型质量和速度的影响各不相同完整的后端对比与选型指南可参考 量化总览文档。VAE 组件未被量化按前文精度约束保持torch.bfloat16或torch.float32即可。图像到图像SanaSprintImg2ImgPipelineSanaSprintImg2ImgPipeline用于图像到图像生成输入一张参考图与一个提示词输出基于该图与提示词生成的新图像。官方示例pipeline_sana_sprint_img2img.pyimport torch from diffusers import SanaSprintImg2ImgPipeline from diffusers.utils.loading_utils import load_image image load_image( https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png ) pipe SanaSprintImg2ImgPipeline.from_pretrained( Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers, torch_dtypetorch.bfloat16, ) pipe.to(cuda) # 也支持 mps、xpu、cpu image pipe( prompta cute pink bear, imageimage, strength0.5, height832, width480, ).images[0] image.save(output.png)img2img 的关键参数与实现原理strength默认 0.6控制对参考图改造的程度取值必须在[0.0, 1.0]。值越大注入的噪声越多、对原图的保留越少为 1 时几乎完全忽略输入图。源码中get_timestepspipeline_sana_sprint_img2img.py先计算init_timestep min(num_inference_steps * strength, num_inference_steps)再从调度器时间步中截取从t_start开始的子序列从而把实际去噪步数压缩到num_inference_steps - t_start。latents 构造prepare_latentspipeline_sana_sprint_img2img.py将输入图先经 VAE 编码得到image_latents再按三角流公式混合噪声noise randn_tensor(shape, generatorgenerator, devicedevice, dtypedtype) * self.scheduler.config.sigma_data latents torch.cos(timestep) * image_latents torch.sin(timestep) * noise这正是 sCM 三角流参数化在 img2img 场景下的应用用cos(timestep)保留原图信息、sin(timestep)注入噪声timestep由strength决定。输入检查check_inputs额外校验strength范围以及height/width能被 32 整除pipeline_sana_sprint_img2img.py。若按strength调整后的步数小于 1会直接抛出异常提示参数不合理。其余流程提示词编码、去噪循环、VAE 解码与SanaSprintPipeline完全一致SanaSprintImg2ImgPipeline甚至直接复用了SanaSprintPipeline.encode_prompt的实现。核心 API 速查SanaSprintPipeline文生图流水线源码。__call__主要参数与默认值参数默认值说明promptNone提示词str或list[str]与prompt_embeds二选一num_inference_steps2去噪步数SANA-Sprint 支持 1~4 步timestepsNone自定义时间步列表长度必须为num_inference_steps 1需降序max_timesteps1.57080sCM 调度器最大时间步intermediate_timesteps1.3仅num_inference_steps2时生效的中间时间步guidance_scale4.5嵌入式引导强度1 时启用num_images_per_prompt1每个提示词生成的图片数height/width1024/1024输出尺寸必须能被 32 整除generatorNonetorch.Generator或列表用于确定性生成latentsNone预生成的噪声 latentsprompt_embeds/prompt_attention_maskNone预生成的文本嵌入与其注意力掩码output_typepil输出格式pil、np或latentreturn_dictTrue是否返回SanaPipelineOutputclean_captionFalse是否清洗提示词依赖beautifulsoup4、ftfyuse_resolution_binningTrue是否将尺寸映射到ASPECT_RATIO_1024_BIN标准分箱attention_kwargsNone透传给注意力处理器的 kwargs如 LoRA scalecallback_on_step_endNone每步结束回调max_sequence_length300提示词最大序列长度complex_human_instruction内置复杂人类指令用于提示词增强置None可关闭注意guidance_scale在源码中最终会乘以self.transformer.config.guidance_embeds_scalepipeline_sana_sprint.py且 SANA-Sprint 属于 guidance-distilled 模型guidance_scale 1时近似真实的无分类器引导CFG。SanaSprintImg2ImgPipeline图像到图像流水线源码。除上述文生图参数外还支持参数默认值说明imageNone输入图支持PIL.Image.Image、np.ndarray、torch.Tensor及对应列表也可直接传入 latents此时不再编码strength0.6对参考图的改造程度取值[0.0, 1.0]SanaPipelineOutput两个流水线的输出类pipeline_output.py继承自BaseOutput包含字段imageslist[PIL.Image.Image]或np.ndarray即去噪后的图像列表长度等于 batch size或形状为(batch_size, height, width, num_channels)的 numpy 数组。工程化建议与测试佐证显存与内存优化显存紧张时使用pipe.enable_model_cpu_offload()按text_encoder-transformer-vae顺序卸载或pipe.enable_sequential_cpu_offload()大尺寸图像解码遇 OOM 时启用 VAE 平铺pipe.vae.enable_tiling(tile_sample_min_width512, tile_sample_min_height512)——该提示就来自源码中的 OOM 捕获分支pipeline_sana_sprint.py参考 量化总览 选择适合自身场景的量化后端。测试用例佐证仓库的 test_sana_sprint.py 与 test_sana_sprint_img2img.py 覆盖了关键行为可作为复现与验证的参考test_inference用 dummy 组件跑通完整推理断言输出形状正确test_vae_tiling对比开启/关闭 VAE 平铺tile_sample_min_height96等参数时的输出差异test_callback_inputs、test_inference_batch_consistent验证回调输入与批量一致性测试默认使用num_inference_steps2、guidance_scale6.0、max_sequence_length16并将complex_human_instruction置为None——说明该参数可关闭以加快编码。组件注册与导入SanaSprintPipeline与SanaSprintImg2ImgPipeline已通过 src/diffusers/pipelines/sana/init.py 及顶层 src/diffusers/init.py 导出安装本仓库的 diffusers 后可直接from diffusers import SanaSprintPipeline使用无需额外注册。小结SANA-Sprint 通过连续时间一致性蒸馏sCM与潜在对抗蒸馏LADD的混合策略将 Sana 基础模型的推理步数压缩至 1~4 步使其适合实时交互式生成场景。在 Diffusers 中SanaSprintPipeline与SanaSprintImg2ImgPipeline完整实现了该模型的推理链路并提供了max_timesteps、strength、量化加载、VAE 平铺与 LoRA 支持等丰富的调优手段。建议按本文流程先跑通默认配置再结合max_timesteps搜索与量化策略在画质、速度与显存之间找到适合自己硬件与应用场景的平衡点。【免费下载链接】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 小时内与您沟通定制方案

免费获取报价