File size: 13,354 Bytes
3dabe4a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
import gradio as gr
import logging
import torch
import torchvision.transforms as F
from modules import shared, scripts, devices, patches, script_callbacks
from modules.script_callbacks import CFGDenoiserParams
from modules.processing import StableDiffusionProcessing
from scripts.incantation_base import UIWrapper
from scripts.scfg import scfg_combine_denoised
logger = logging.getLogger(__name__)
class CFGCombinerScript(UIWrapper):
""" Some scripts modify the CFGs in ways that are not compatible with each other.
This script will patch the CFG denoiser function to apply CFG in an ordered way.
This script adds a dict named 'incant_cfg_params' to the processing object.
This dict contains the following:
'denoiser': the denoiser object
'pag_params': list of PAG parameters
'scfg_params': the S-CFG parameters
...
"""
def __init__(self):
pass
# Extension title in menu UI
def title(self):
return "CFG Combiner"
# Decide to show menu in txt2img or img2img
def show(self, is_img2img):
return scripts.AlwaysVisible
# Setup menu ui detail
def setup_ui(self, is_img2img):
self.infotext_fields = []
self.paste_field_names = []
return []
def before_process(self, p: StableDiffusionProcessing, *args, **kwargs):
logger.debug("CFGCombinerScript before_process")
cfg_dict = {
"denoiser": None,
"pag_params": None,
"scfg_params": None
}
setattr(p, 'incant_cfg_params', cfg_dict)
def process(self, p: StableDiffusionProcessing, *args, **kwargs):
pass
def before_process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
pass
def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
""" Process the batch and hook the CFG denoiser if PAG or S-CFG is active """
logger.debug("CFGCombinerScript process_batch")
pag_active = p.extra_generation_params.get('PAG Active', False)
cfg_active = p.extra_generation_params.get('CFG Interval Enable', False)
scfg_active = p.extra_generation_params.get('SCFG Active', False)
if not any([
pag_active,
cfg_active,
scfg_active
]):
return
#logger.debug("CFGCombinerScript process_batch: pag_active or scfg_active")
cfg_denoise_lambda = lambda params: self.on_cfg_denoiser_callback(params, p.incant_cfg_params)
unhook_lambda = lambda: self.unhook_callbacks()
script_callbacks.on_cfg_denoiser(cfg_denoise_lambda)
script_callbacks.on_script_unloaded(unhook_lambda)
logger.debug('Hooked callbacks')
def postprocess_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
logger.debug("CFGCombinerScript postprocess_batch")
script_callbacks.remove_current_script_callbacks()
def unhook_callbacks(self, cfg_dict = None):
if not cfg_dict:
return
self.unpatch_cfg_denoiser(cfg_dict)
def on_cfg_denoiser_callback(self, params: CFGDenoiserParams, cfg_dict: dict):
""" Callback for when the CFG denoiser is called
Patches the combine_denoised function with a custom one.
"""
if cfg_dict['denoiser'] is None:
cfg_dict['denoiser'] = params.denoiser
else:
self.unpatch_cfg_denoiser(cfg_dict)
self.patch_cfg_denoiser(params.denoiser, cfg_dict)
def patch_cfg_denoiser(self, denoiser, cfg_dict: dict):
""" Patch the CFG Denoiser combine_denoised function """
if not cfg_dict:
logger.error("Unable to patch CFG Denoiser, no dict passed as cfg_dict")
return
if not denoiser:
logger.error("Unable to patch CFG Denoiser, denoiser is None")
return
if getattr(denoiser, 'combine_denoised_patched', False) is False:
try:
setattr(denoiser, 'combine_denoised_original', denoiser.combine_denoised)
# create patch that references the original function
pass_conds_func = lambda *args, **kwargs: combine_denoised_pass_conds_list(
*args,
**kwargs,
original_func = denoiser.combine_denoised_original,
pag_params = cfg_dict['pag_params'],
scfg_params = cfg_dict['scfg_params']
)
patched_combine_denoised = patches.patch(__name__, denoiser, "combine_denoised", pass_conds_func)
setattr(denoiser, 'combine_denoised_patched', True)
setattr(denoiser, 'combine_denoised_original', patches.original(__name__, denoiser, "combine_denoised"))
except KeyError:
logger.exception("KeyError patching combine_denoised")
pass
except RuntimeError:
logger.exception("RuntimeError patching combine_denoised")
pass
def unpatch_cfg_denoiser(self, cfg_dict = None):
""" Unpatch the CFG Denoiser combine_denoised function """
if cfg_dict is None:
return
denoiser = cfg_dict.get('denoiser', None)
if denoiser is None:
return
setattr(denoiser, 'combine_denoised_patched', False)
try:
patches.undo(__name__, denoiser, "combine_denoised")
except KeyError:
logger.exception("KeyError unhooking combine_denoised")
pass
except RuntimeError:
logger.exception("RuntimeError unhooking combine_denoised")
pass
cfg_dict['denoiser'] = None
def combine_denoised_pass_conds_list(*args, **kwargs):
""" Hijacked function for combine_denoised in CFGDenoiser
Currently relies on the original function not having any kwargs
If any of the params are not None, it will apply the corresponding guidance
The order of guidance is:
1. CFG and S-CFG are combined multiplicatively
2. PAG guidance is added to the result
3. ...
...
"""
original_func = kwargs.get('original_func', None)
pag_params = kwargs.get('pag_params', None)
scfg_params = kwargs.get('scfg_params', None)
if pag_params is None and scfg_params is None:
logger.warning("No reason to hijack combine_denoised")
return original_func(*args)
def new_combine_denoised(x_out, conds_list, uncond, cond_scale):
denoised_uncond = x_out[-uncond.shape[0]:]
denoised = torch.clone(denoised_uncond)
### Variables
# 0. Standard CFG Value
cfg_scale = cond_scale
# 1. CFG Interval
# Overrides cfg_scale if pag_params is not None
if pag_params is not None:
if pag_params.cfg_interval_enable:
cfg_scale = pag_params.cfg_interval_scheduled_value
# 2. PAG
pag_x_out = None
pag_scale = None
run_pag = False
if pag_params is not None:
pag_active = pag_params.pag_active
pag_x_out = pag_params.pag_x_out
pag_scale = pag_params.pag_scale
if not pag_active:
pass
# Not within step interval?
elif not pag_params.pag_start_step <= pag_params.step <= pag_params.pag_end_step:
pass
# Scale is zero?
elif pag_scale <= 0:
pass
else:
run_pag = pag_active
# 3. Saliency Map
use_saliency_map = False
if pag_params is not None:
use_saliency_map = pag_params.pag_sanf
### Combine Denoised
for i, conds in enumerate(conds_list):
for cond_index, weight in conds:
model_delta = x_out[cond_index] - denoised_uncond[i]
# S-CFG
rate = 1.0
if scfg_params is not None:
rate = scfg_combine_denoised(
model_delta = model_delta,
cfg_scale = cfg_scale,
scfg_params = scfg_params,
)
# If rate is not an int, convert to tensor
if rate is None:
logger.error("scfg_combine_denoised returned None, using default rate of 1.0")
rate = 1.0
elif not isinstance(rate, int) and not isinstance(rate, float):
rate = rate.to(device=shared.device, dtype=model_delta.dtype)
else:
# rate is tensor, probably
pass
# 1. Experimental formulation for S-CFG combined with CFG
cfg_x = (model_delta) * rate * (weight * cfg_scale)
if not use_saliency_map or not run_pag:
denoised[i] += cfg_x
del rate
# 2. PAG
# PAG is added like CFG
if pag_params is not None:
if not run_pag:
pass
# do pag
else:
try:
pag_delta = x_out[cond_index] - pag_x_out[i]
pag_x = pag_delta * (weight * pag_scale)
if not use_saliency_map:
denoised[i] += pag_x
# 3. Saliency Adaptive Noise Fusion arXiv.2311.10329v5
# Smooth the saliency maps
if use_saliency_map:
blur = F.GaussianBlur(kernel_size=3, sigma=1).to(device=shared.device)
omega_rt = blur(torch.abs(cfg_x))
omega_rs = blur(torch.abs(pag_x))
soft_rt = torch.softmax(omega_rt, dim=0)
soft_rs = torch.softmax(omega_rs, dim=0)
m = torch.stack([soft_rt, soft_rs], dim=0) # 2 c h w
_, argmax_indices = torch.max(m, dim=0)
# select from cfg_x or pag_x
m1 = torch.where(argmax_indices == 0, 1, 0)
# hadamard product
sal_cfg = cfg_x * m1 + pag_x * (1 - m1)
denoised[i] += sal_cfg
except Exception as e:
logger.exception("Exception in combine_denoised_pass_conds_list - %s", e)
#torch.cuda.empty_cache()
devices.torch_gc()
return denoised
return new_combine_denoised(*args) |