
Diffusers DEISMultistepScheduler 详解基于指数积分器的高阶 ODE 快速采样器【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers导读DEISMultistepSchedulerDiffusion Exponential Integrator Sampler是 Diffusers 中实现的一类快速高阶扩散常微分方程ODE求解器它利用扩散过程学习到的半线性结构来显著降低离散化误差从而在仅 10 步左右即可生成高质量样本。本文以 docs/source/en/api/schedulers/deis.md 为骨架深入结合 调度器源码 与 单元测试系统讲解 DEIS 的数学动机、全部构造参数、采样流程、动态阈值化以及如何在实际 pipeline 中替换使用。读完本文你将掌握如何在 Stable Diffusion 等 pipeline 中配置并调优DEISMultistepScheduler在减少采样步数的同时保住生成质量。一、背景扩散模型为什么需要快速采样器扩散模型Diffusion Models, DMs能生成高保真样本但一个主要痛点是采样过程极其缓慢通常需要成百上千个时间离散化步骤才能达到期望精度。DEIS 论文《Fast Sampling of Diffusion Models with Exponential Integrator》系统地分析了 DM 的采样过程指出影响样本质量的关键因素中离散化方法最为关键。DEIS 的核心思路是基于**指数积分器Exponential Integrator**来离散化扩散过程的常微分方程ODE利用扩散过程学习到的半线性semilinear结构降低离散化误差可以应用到任意扩散模型在10 步内即可生成高保真样本在有限的 score function evaluationNFE下达到当时的 SOTA 采样性能。原文摘要给出的参考数据论文中报告CIFAR10 上 10 个 NFE 时 FID 4.1715 个 NFE 时 FID 3.37、IS 9.74单张 A6000 GPU 约 3 分钟生成 50k 张 CIFAR10 图像。这些数据来自论文本身可作为理解其加速效果的背景参考。本仓库实现的两个关键改动DEISMultistepScheduler的实现见 调度器源码相比原论文做了两点重要修改多项式拟合从原始线性t空间改到 log-rho 空间。原论文在时间t上做多项式拟合本实现改为在rho sigma / alpha的对数空间中进行从而获得指数多步更新的闭式系数closed-form coefficients不再依赖数值求解器支持多种预测类型与噪声调度包括epsilon、sample、v_prediction、flow_prediction以及 Karras、exponential、beta、flow 四种 sigma 调度使其能适配从经典 Stable Diffusion 到 flow-matching 类模型的不同场景。从源码注释看该实现基于DPMSolverMultistepScheduler修改而来见 调度器源码第 16 行因此其 API 风格、step流程与 DPM-Solver 系列高度一致。二、快速上手在 Stable Diffusion pipeline 中替换调度器DEISMultistepScheduler与 Stable Diffusion 系列 pipeline 完全兼容。以经典的StableDiffusionPipeline为例import torch from diffusers import StableDiffusionPipeline, DEISMultistepScheduler pipe StableDiffusionPipeline.from_pretrained( runwayml/stable-diffusion-v1-5, torch_dtypetorch.float16 ) pipe pipe.to(cuda) # 用 DEIS 替换默认调度器 pipe.scheduler DEISMultistepScheduler.from_config(pipe.scheduler.config) # 仅用 10~25 步即可获得良好结果 image pipe( a photo of an astronaut riding a horse on mars, num_inference_steps10, guidance_scale7.5, ).images[0]要点from_config(pipe.scheduler.config)会继承原调度器的num_train_timesteps、beta_start、beta_end、beta_schedule、prediction_type等关键配置避免手动重复指定官方文档建议solver_order取 2 或 3见 deis.md其中solver_order1等价于DDIMScheduler对于 CFG 引导采样推荐solver_order2无条件采样推荐solver_order3见 源码参数文档。三、构造参数全解析DEISMultistepScheduler继承自SchedulerMixin与ConfigMixin因此天然支持save_config、from_pretrained、from_config等通用能力详见 配置基类。所有参数均通过register_to_config注册到config中构造后可通过scheduler.config.xxx访问。3.1 噪声计划beta 计划参数默认值说明num_train_timesteps1000训练时的扩散步数决定 beta 序列长度beta_start0.0001beta 序列起始值beta_end0.02beta 序列终止值beta_schedulelinear可选linear、scaled_linear、squaredcos_cap_v2trained_betasNone直接传入训练好的 beta 数组以绕过beta_start/beta_end在 源码第 192-211 行 中可以看到三种 beta schedule 的具体实现lineartorch.linspace(beta_start, beta_end, num_train_timesteps)等距线性插值scaled_linear先对 beta 开方后线性插值再平方**专门针对潜在扩散模型latent diffusion**设计Stable Diffusion 系列默认使用squaredcos_cap_v2GLIDE 风格余弦计划调用betas_for_alpha_bar生成该辅助函数还支持cosine、exp、laplace三种alpha_transform_type见 源码第 33-83 行。在__init__中调度器还会由 beta 派生出一系列量alphas、alphas_cumprod、alpha_t、sigma_t、lambda_tlog(alpha) - log(sigma)以及sigmas ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5见 源码第 213-219 行。注意注释明确说明当前仅支持 VP 型噪声计划Currently we only support VP-type noise schedule。3.2 求解器阶数与预测类型参数默认值说明solver_order2DEIS 阶数取1、2或31等价于 DDIMprediction_typeepsilon可选epsilon、sample、v_prediction、flow_predictionalgorithm_typedeis求解器算法类型当前仅支持deissolver_typelogrho求解器类型当前仅支持logrholower_order_finalTrue最后几步是否降阶使用低阶求解器仅对 15 步推理有效阶数选择建议官方文档 Tips 与源码 docstring 双重确认solver_order1等价于DDIMSchedulersolver_order2推荐用于引导采样guided sampling如 CFGsolver_order3推荐用于无条件采样unconditional sampling。lower_order_finalTrue时当推理步数少于 15 步最后两步会分别降为二阶、一阶更新以稳定数值见 step 方法中的判断逻辑。预测类型在convert_model_output中对应四种不同的反推x0公式见 源码第 618-631 行epsilonx0_pred (sample - sigma_t * model_output) / alpha_t预测噪声samplex0_pred model_output直接预测干净样本v_predictionx0_pred alpha_t * sample - sigma_t * model_outputImagen Video 论文中的 v 预测见 Imagen Videoflow_predictionx0_pred sample - sigma_t * model_outputflow-matching 类模型。3.3 动态阈值化Dynamic Thresholding参数默认值说明thresholdingFalse是否启用 Imagen 提出的动态阈值化dynamic_thresholding_ratio0.995分位数比例仅thresholdingTrue时生效sample_max_value1.0阈值上限仅thresholdingTrue时生效重要限制动态阈值化不适合潜在空间扩散模型如 Stable Diffusion只适用于像素空间扩散模型官方文档 Tips 明确指出。其原理来自 Imagen 论文见 _threshold_sample 源码注释在每个采样步取x_t0t 时刻对x_0的预测绝对像素值的某个分位数作为s若s 1则将x_t0裁剪到[-s, s]再除以s。这会把接近饱和接近 -1 和 1的像素向内推防止每步饱和从而显著提升照片真实感与图文对齐尤其在使用很大引导权重时。实现细节_threshold_sample会将样本展平后沿 batch 维度计算torch.quantile(abs_sample, ratio, dim1)再clamp(min1, maxsample_max_value)——当 clamp 到最小值 1 时等价于标准的[-1, 1]裁剪见 源码第 386-393 行。fp16 样本会先上转为 float32 做分位数计算再转回原 dtype相关正确性由 test_fp16_support 测试 覆盖。3.4 噪声调度sigma schedule与时间步参数默认值说明use_karras_sigmasFalse使用 Karras 噪声调度EDM 论文use_exponential_sigmasFalse使用指数 sigma 调度use_beta_sigmasFalse使用 Beta 分布采样调度Beta Sampling is All You Needuse_flow_sigmasFalse使用 flow sigma 调度适配 flow-matching 模型flow_shift1.0flow 模型的 shift 参数timestep_spacinglinspace可选linspace、leading、trailingsteps_offset0推理步的偏移量部分模型家族需要use_dynamic_shiftingFalse是否使用动态 shiftingtime_shift_typeexponential时间偏移类型当前仅支持exponential互斥约束use_karras_sigmas、use_exponential_sigmas、use_beta_sigmas三者同时只能开启一个否则构造时抛出ValueError且use_beta_sigmasTrue要求安装scipy见 源码第 177-191 行。beta 调度的实现使用scipy.stats.beta.ppf生成 sigma 序列参数alpha0.6, beta0.6见 _convert_to_beta。时间步三种间距对应论文《Common Diffusion Noise Schedules and Sample Steps are Flawed》Table 2linspace默认在[0, num_train_timesteps-1]上等距取整leading按step_ratio取整生成会叠加steps_offsettrailing从num_train_timesteps倒推step_ratio步长取整并减 1。具体实现见 set_timesteps 方法第 288-311 行。四、采样流程与核心方法4.1 采样前的准备set_timesteps推理前必须调用set_timesteps(num_inference_steps)否则step会抛出 Number of inference steps is None 异常见 step 方法第 943-946 行。该方法完成根据timestep_spacing生成离散时间步序列按配置选择 Karras / exponential / beta / flow sigma 或默认插值 sigma重置内部状态model_outputs长度为solver_order的历史输出缓存与lower_order_nums计数器初始化_step_index/_begin_index索引计数器。若开启use_dynamic_shifting还可传入mu参数flow_shift exp(mu)见 set_timesteps 第 285-287 行。4.2 单步推进stepstep(model_output, timestep, sample, return_dictTrue)是采样循环的核心流程如下见 step 方法若step_index未初始化通过_init_step_index依据当前 timestep 定位索引判断最后一步len(timesteps) 15且lower_order_finalTrue时是否降阶调用convert_model_output将模型输出统一转换为 DEIS 所需的“噪声型”输出将新输出压入model_outputs历史缓存长度固定为solver_order滚动覆盖按阶数选择更新公式solver_order 1或历史不足/最后一步 →deis_first_order_update等价于 DDIMsolver_order 2或历史不足两步/倒数第二步 →multistep_deis_second_order_update否则 →multistep_deis_third_order_updatelower_order_nums递增不超过solver_orderstep_index加一返回SchedulerOutput(prev_sample...)或(prev_sample,)元组。4.3 一阶更新与 DDIM 的等价关系一阶 DEIS 更新公式为见 deis_first_order_updateh lambda_t - lambda_s x_t (alpha_t / alpha_s) * sample - sigma_t * (exp(h) - 1.0) * model_output其中lambda_t log(alpha_t) - log(sigma_t)。这正是 DDIM 的闭式解形式也是文档中solver_order1等价于DDIMScheduler的数学来源。4.4 二/三阶多步更新log-rho 空间的闭式系数高阶更新在 log-rho 空间rho sigma / alpha对模型输出做多项式插值后精确积分。二阶更新见 multistep_deis_second_order_update# 辅助积分函数 ind_fn(t, b, c) Integrate[(log(t) - log(c)) / (log(b) - log(c)), {t}] def ind_fn(t, b, c): return t * (-np.log(c) np.log(t) - 1) / (np.log(b) - np.log(c)) coef1 ind_fn(rho_t, rho_s0, rho_s1) - ind_fn(rho_s0, rho_s0, rho_s1) coef2 ind_fn(rho_t, rho_s1, rho_s0) - ind_fn(rho_s0, rho_s1, rho_s0) x_t alpha_t * (sample / alpha_s0 coef1 * m0 coef2 * m1)三阶更新见 multistep_deis_third_order_update对二次插值多项式做解析积分得到三个闭式系数coef1/coef2/coef3x_t alpha_t * (sample / alpha_s0 coef1 * m0 coef2 * m1 coef3 * m2)正是因为在 log-rho 空间做多项式拟合这些系数才能以闭式表达避免了论文原版中对数值求解器的依赖——这是本仓库实现区别于原论文的核心技术点见 deis.md 第 17 行。4.5 其余关键方法方法作用convert_model_output将模型输出按prediction_type转换为 DEIS 所需的统一形式并可选执行动态阈值化scale_model_input恒等返回输入保证与需要缩放输入的调度器接口互换见 源码第 981-994 行add_noise依据 sigma 调度向原始样本添加噪声用于 img2img / inpainting 等中途启动场景见 源码第 996-1044 行set_begin_index设置起始索引pipeline 在推理前调用拷贝自 DPM-Solverindex_for_timestep在调度表中定位 timestep 的索引支持重复 timestep 场景__len__返回num_train_timesteps五、兼容性与降级逻辑DEISMultistepScheduler被列入KarrasDiffusionSchedulers枚举族见 源码第 148 行在 schedulers/init.py 与 diffusers/init.py 中公开导出。值得注意的向后兼容降级逻辑见 源码第 224-235 行若传入algorithm_typedpmsolver或dpmsolver会被静默改写为deis兼容旧配置若传入solver_typemidpoint、heun、bh1、bh2会被静默改写为logrho其他未支持的取值则抛出NotImplementedError。也就是说从 DPM-Solver 或旧版 DEIS 配置迁移时无需修改配置即可直接加载调度器会自动落到唯一受支持的deislogrho组合。另外DEISMultistepScheduler也被 StableDiffusionSAGPipelineSelf-Attention Guidance 列为受支持的调度器之一说明其与 Stable Diffusion 生态的兼容性良好。六、测试验证与数值稳定性仓库在 tests/schedulers/test_scheduler_deis.py 中提供了完整的测试覆盖可作为使用与验证的参考test_switch/test_full_loop_no_noise用固定 dummy 模型跑 10 步完整循环断言mean(|sample|)等于0.23916 ± 1e-3且与DPMSolverSinglestep、DPMSolverMultistep、UniPCMultistep往返转换from_config后结果一致——这说明DEIS 与同族多步求解器配置互通、输出可复现test_full_loop_with_v_prediction验证v_prediction模式下期望均值为0.091 ± 1e-3test_full_loop_with_noise验证中途加入噪声img2img 场景后sum ≈ 315.3016、mean ≈ 0.41054test_solver_order_and_type遍历solver_order ∈ {1,2,3}×prediction_type ∈ {epsilon, sample}断言无 NaNtest_thresholding遍历阶数与sample_max_value ∈ {0.5, 1.0, 2.0}验证动态阈值化test_inference_steps覆盖[1, 2, 3, 5, 10, 50, 100, 999, 1000]各种推理步数test_timesteps覆盖num_train_timesteps ∈ {25, 50, 100, 999, 1000}test_fp16_support验证半精度推理全程保持float16test_beta_sigmas/test_exponential_sigmas验证两种 sigma 调度的可用性。测试默认配置见 get_scheduler_config为num_train_timesteps1000、beta_start0.0001、beta_end0.02、beta_schedulelinear、solver_order2这也是实践中最常用的起步配置。七、实践调优建议起步配置沿用solver_order2、prediction_typeepsilon与 Stable Diffusion 权重匹配先用 25 步对比 DDIM 效果再逐步降至 10 步观察质量衰减引导 vs 无条件CFG 引导场景保持solver_order2无条件/低引导场景可尝试solver_order3获得更高精度小步数稳定性推理步数少于 15 时保持lower_order_finalTrue默认让末尾两步自动降阶避免高阶插值在终点附近振荡像素空间模型如果模型在像素空间非 latent可开启thresholdingTrue并配合dynamic_thresholding_ratio0.995、sample_max_value1.0改善高引导权重下的饱和度问题latent 模型如 Stable Diffusion请勿开启噪声调度实验use_karras_sigmas常能改善低步数质量use_beta_sigmas需先安装 scipy且三者互斥配置继承通过from_config(pipe.scheduler.config)替换调度器可自动继承权重对应的 beta 计划与预测类型避免手动配置不一致。相关文档与源码索引官方 API 文档docs/source/en/api/schedulers/deis.md调度器实现src/diffusers/schedulers/scheduling_deis_multistep.py单元测试tests/schedulers/test_scheduler_deis.py公共输出结构SchedulerOutput定义于 src/diffusers/schedulers/scheduling_utils.py调度器注册与导出src/diffusers/schedulers/init.py、src/diffusers/init.py【免费下载链接】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),仅供参考