|
| 1 | +import torch |
| 2 | +from comfy_api.latest import ComfyExtension, io |
| 3 | +from typing_extensions import override |
| 4 | + |
| 5 | + |
| 6 | +class NAGuidance(io.ComfyNode): |
| 7 | + @classmethod |
| 8 | + def define_schema(cls) -> io.Schema: |
| 9 | + return io.Schema( |
| 10 | + node_id="NAGuidance", |
| 11 | + display_name="Normalized Attention Guidance", |
| 12 | + description="Applies Normalized Attention Guidance to models, enabling negative prompts on distilled/schnell models.", |
| 13 | + category="", |
| 14 | + is_experimental=True, |
| 15 | + inputs=[ |
| 16 | + io.Model.Input("model", tooltip="The model to apply NAG to."), |
| 17 | + io.Float.Input("nag_scale", min=0.0, default=5.0, max=50.0, step=0.1, tooltip="The guidance scale factor. Higher values push further from the negative prompt."), |
| 18 | + io.Float.Input("nag_alpha", min=0.0, default=0.5, max=1.0, step=0.01, tooltip="Blending factor for the normalized attention. 1.0 is full replacement, 0.0 is no effect."), |
| 19 | + io.Float.Input("nag_tau", min=1.0, default=1.5, max=10.0, step=0.01), |
| 20 | + # io.Float.Input("start_percent", min=0.0, default=0.0, max=1.0, step=0.01, tooltip="The relative sampling step to begin applying NAG."), |
| 21 | + # io.Float.Input("end_percent", min=0.0, default=1.0, max=1.0, step=0.01, tooltip="The relative sampling step to stop applying NAG."), |
| 22 | + ], |
| 23 | + outputs=[ |
| 24 | + io.Model.Output(tooltip="The patched model with NAG enabled."), |
| 25 | + ], |
| 26 | + ) |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def execute(cls, model: io.Model.Type, nag_scale: float, nag_alpha: float, nag_tau: float) -> io.NodeOutput: |
| 30 | + m = model.clone() |
| 31 | + |
| 32 | + # sigma_start = m.get_model_object("model_sampling").percent_to_sigma(start_percent) |
| 33 | + # sigma_end = m.get_model_object("model_sampling").percent_to_sigma(end_percent) |
| 34 | + |
| 35 | + def nag_attention_output_patch(out, extra_options): |
| 36 | + cond_or_uncond = extra_options.get("cond_or_uncond", None) |
| 37 | + if cond_or_uncond is None: |
| 38 | + return out |
| 39 | + |
| 40 | + if not (1 in cond_or_uncond and 0 in cond_or_uncond): |
| 41 | + return out |
| 42 | + |
| 43 | + # sigma = extra_options.get("sigmas", None) |
| 44 | + # if sigma is not None and len(sigma) > 0: |
| 45 | + # sigma = sigma[0].item() |
| 46 | + # if sigma > sigma_start or sigma < sigma_end: |
| 47 | + # return out |
| 48 | + |
| 49 | + img_slice = extra_options.get("img_slice", None) |
| 50 | + |
| 51 | + if img_slice is not None: |
| 52 | + orig_out = out |
| 53 | + out = out[:, img_slice[0]:img_slice[1]] # only apply on img part |
| 54 | + |
| 55 | + batch_size = out.shape[0] |
| 56 | + half_size = batch_size // len(cond_or_uncond) |
| 57 | + |
| 58 | + ind_neg = cond_or_uncond.index(1) |
| 59 | + ind_pos = cond_or_uncond.index(0) |
| 60 | + z_pos = out[half_size * ind_pos:half_size * (ind_pos + 1)] |
| 61 | + z_neg = out[half_size * ind_neg:half_size * (ind_neg + 1)] |
| 62 | + |
| 63 | + guided = z_pos * nag_scale - z_neg * (nag_scale - 1.0) |
| 64 | + |
| 65 | + eps = 1e-6 |
| 66 | + norm_pos = torch.norm(z_pos, p=1, dim=-1, keepdim=True).clamp_min(eps) |
| 67 | + norm_guided = torch.norm(guided, p=1, dim=-1, keepdim=True).clamp_min(eps) |
| 68 | + |
| 69 | + ratio = norm_guided / norm_pos |
| 70 | + scale_factor = torch.minimum(ratio, torch.full_like(ratio, nag_tau)) / ratio |
| 71 | + |
| 72 | + guided_normalized = guided * scale_factor |
| 73 | + |
| 74 | + z_final = guided_normalized * nag_alpha + z_pos * (1.0 - nag_alpha) |
| 75 | + |
| 76 | + if img_slice is not None: |
| 77 | + orig_out[half_size * ind_neg:half_size * (ind_neg + 1), img_slice[0]:img_slice[1]] = z_final |
| 78 | + orig_out[half_size * ind_pos:half_size * (ind_pos + 1), img_slice[0]:img_slice[1]] = z_final |
| 79 | + return orig_out |
| 80 | + else: |
| 81 | + out[half_size * ind_pos:half_size * (ind_pos + 1)] = z_final |
| 82 | + return out |
| 83 | + |
| 84 | + m.set_model_attn1_output_patch(nag_attention_output_patch) |
| 85 | + m.disable_model_cfg1_optimization() |
| 86 | + |
| 87 | + return io.NodeOutput(m) |
| 88 | + |
| 89 | + |
| 90 | +class NagExtension(ComfyExtension): |
| 91 | + @override |
| 92 | + async def get_node_list(self) -> list[type[io.ComfyNode]]: |
| 93 | + return [ |
| 94 | + NAGuidance, |
| 95 | + ] |
| 96 | + |
| 97 | + |
| 98 | +async def comfy_entrypoint() -> NagExtension: |
| 99 | + return NagExtension() |
0 commit comments