CFG Scale(Classifier-Free Guidance Scale,无分类器指导缩放)是Stable Diffusion中的一个关键参数,它控制生成图像在遵循文本提示的严格程度。
CFG Scale控制了两种预测之间的平衡:
根据代码分析,CFG Scale的核心公式实现在modules/sd_samplers_cfg_denoiser.py
文件中:
pythondef combine_denoised(self, x_out, conds_list, uncond, cond_scale):
denoised_uncond = x_out[-uncond.shape[0]:]
denoised = torch.clone(denoised_uncond)
for i, conds in enumerate(conds_list):
for cond_index, weight in conds:
denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
return denoised
这就是CFG的核心实现,可简化为以下公式:
最终去噪结果 = 无条件预测 + CFG_Scale * (条件预测 - 无条件预测)
或者写成数学形式:
在repositories/k-diffusion/k_diffusion/sampling.py
中,classifier-free guidance的实现类似:
pythonelif guidance_type == "classifier-free":
if guidance_scale == 1. or unconditional_condition is None:
return noise_pred_fn(x, t_continuous, cond=condition)
else:
x_in = torch.cat([x] * 2)
t_in = torch.cat([t_continuous] * 2)
c_in = torch.cat([unconditional_condition, condition])
noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2)
return noise_uncond + guidance_scale * (noise - noise_uncond)
modules/processing.py
中,CFG Scale作为参数传入到处理类中:pythonclass StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
# ...
def init(self, all_prompts, all_seeds, all_subseeds):
# ...
self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model)
python# modules/sd_samplers_kdiffusion.py
self.sampler_extra_args = {
'cond': conditioning,
'image_cond': image_conditioning,
'uncond': unconditional_conditioning,
'cond_scale': p.cfg_scale,
's_min_uncond': self.s_min_uncond
}
CFGDenoiser.forward
方法中应用公式,将条件和无条件预测组合起来CFG Scale本质上是控制生成图像在多大程度上遵循文本提示。它是一个平衡因子:
在实际使用中:
CFG Scale是文生图中最重要的参数之一,它直接影响生成图像与文本提示的一致性。
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!