Skip to content

Commit 650838f

Browse files
Experimental CFGNorm node. (Comfy-Org#8942)
This is from the new hidream e1 1 model code. Figured it might be useful as a generic cfg trick.
1 parent 491fafb commit 650838f

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

comfy_extras/nodes_cfg.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,32 @@ def cfg_zero_star(args):
4040
m.set_model_sampler_post_cfg_function(cfg_zero_star)
4141
return (m, )
4242

43+
class CFGNorm:
44+
@classmethod
45+
def INPUT_TYPES(s):
46+
return {"required": {"model": ("MODEL",),
47+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01}),
48+
}}
49+
RETURN_TYPES = ("MODEL",)
50+
RETURN_NAMES = ("patched_model",)
51+
FUNCTION = "patch"
52+
CATEGORY = "advanced/guidance"
53+
54+
def patch(self, model, strength):
55+
m = model.clone()
56+
def cfg_norm(args):
57+
cond_p = args['cond_denoised']
58+
pred_text_ = args["denoised"]
59+
60+
norm_full_cond = torch.norm(cond_p, dim=1, keepdim=True)
61+
norm_pred_text = torch.norm(pred_text_, dim=1, keepdim=True)
62+
scale = (norm_full_cond / (norm_pred_text + 1e-8)).clamp(min=0.0, max=1.0)
63+
return pred_text_ * scale * strength
64+
65+
m.set_model_sampler_post_cfg_function(cfg_norm)
66+
return (m, )
67+
4368
NODE_CLASS_MAPPINGS = {
44-
"CFGZeroStar": CFGZeroStar
69+
"CFGZeroStar": CFGZeroStar,
70+
"CFGNorm": CFGNorm,
4571
}

0 commit comments

Comments
 (0)