-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathnodes.py
More file actions
1326 lines (1111 loc) · 60.5 KB
/
nodes.py
File metadata and controls
1326 lines (1111 loc) · 60.5 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn.functional as F
from math import ceil, floor
from copy import deepcopy
import comfy.model_patcher
from comfy.sampler_helpers import convert_cond
from comfy.samplers import calc_cond_batch, encode_model_conds
from comfy.ldm.modules.attention import optimized_attention_for_device
from nodes import ConditioningConcat, ConditioningSetTimestepRange
import comfy.model_management as model_management
from comfy.latent_formats import SDXL as SDXL_Latent
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
SDXL_Latent = SDXL_Latent()
sdxl_latent_rgb_factors = SDXL_Latent.latent_rgb_factors
ConditioningConcat = ConditioningConcat()
ConditioningSetTimestepRange = ConditioningSetTimestepRange()
default_attention = optimized_attention_for_device(model_management.get_torch_device())
default_device = model_management.get_torch_device()
weighted_average = lambda tensor1, tensor2, weight1: (weight1 * tensor1 + (1 - weight1) * tensor2)
selfnorm = lambda x: x / x.norm()
minmaxnorm = lambda x: torch.nan_to_num((x - x.min()) / (x.max() - x.min()), nan=0.0, posinf=1.0, neginf=0.0)
normlike = lambda x, y: x / x.norm() * y.norm()
def get_sigma_min_max(model):
model_sampling = model.model.model_sampling
sigma_min = model_sampling.sigma(model_sampling.timestep(model_sampling.sigma_min)).item()
sigma_max = model_sampling.sigma(model_sampling.timestep(model_sampling.sigma_max)).item()
return sigma_min, sigma_max
@torch.no_grad()
def make_new_uncond_at_scale(cond,uncond,cond_scale,new_scale):
new_scale_ratio = (new_scale - 1) / (cond_scale - 1)
return cond * (1 - new_scale_ratio) + uncond * new_scale_ratio
@torch.no_grad()
def make_new_uncond_at_scale_co(conds_out,cond_scale,new_scale):
new_scale_ratio = (new_scale - 1) / (cond_scale - 1)
return conds_out[0] * (1 - new_scale_ratio) + conds_out[1] * new_scale_ratio
@torch.no_grad()
def get_denoised_at_scale(x_orig,cond,uncond,cond_scale):
return x_orig - ((x_orig - uncond) + cond_scale * ((x_orig - cond) - (x_orig - uncond)))
class pre_cfg_perp_neg:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"neg_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 1/10, "round": 0.01}),
"set_context_length" : ("BOOLEAN", {"default": False}),
"context_length": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
"start_at_sigma": ("FLOAT", {"default": 15, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
# "cond_or_uncond": (["both","uncond"], {"default":"uncond"}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, clip, neg_scale, set_context_length, context_length, start_at_sigma, end_at_sigma, cond_or_uncond="uncond"):
empty_cond, pooled = clip.encode_from_tokens(clip.tokenize(""), return_pooled=True)
nocond = [[empty_cond, {"pooled_output": pooled}]]
if context_length > 1 and set_context_length:
short_nocond = deepcopy(nocond)
for x in range(context_length - 1):
(nocond,) = ConditioningConcat.concat(nocond, short_nocond)
nocond = convert_cond(nocond)
@torch.no_grad()
def pre_cfg_perp_neg_function(args):
conds_out = args["conds_out"]
noise_pred_pos = conds_out[0]
if args["sigma"][0] > start_at_sigma or args["sigma"][0] <= end_at_sigma or not torch.any(conds_out[1]):
return conds_out
noise_pred_neg = conds_out[1]
model_options = args["model_options"]
timestep = args["timestep"]
model = args["model"]
x = args["input"]
nocond_processed = encode_model_conds(model.extra_conds, nocond, x, x.device, "negative")
(noise_pred_nocond,) = calc_cond_batch(model, [nocond_processed], x, timestep, model_options)
pos = noise_pred_pos - noise_pred_nocond
neg = noise_pred_neg - noise_pred_nocond
perp = neg - ((torch.mul(neg, pos).sum())/(torch.norm(pos)**2)) * pos
perp_neg = perp * neg_scale
if cond_or_uncond == "both":
perp_p = pos - ((torch.mul(neg, pos).sum())/(torch.norm(neg)**2)) * neg
perp_pos = perp_p * neg_scale
conds_out[0] = noise_pred_nocond + perp_pos
else:
conds_out[0] = noise_pred_nocond + pos
conds_out[1] = noise_pred_nocond + perp_neg
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(pre_cfg_perp_neg_function)
return (m, )
class pre_cfg_re_negative:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"model": ("MODEL",),
"clip": ("CLIP",),
"empty_proportion": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 1/20, "round": 0.01}),
"progressive_scale" : ("BOOLEAN", {"default": False}),
"set_context_length" : ("BOOLEAN", {"default": False}),
"context_length": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, clip, empty_proportion, progressive_scale, set_context_length, context_length, end_at_sigma):
sigma_min, sigma_max = get_sigma_min_max(model)
empty_cond, pooled = clip.encode_from_tokens(clip.tokenize(""), return_pooled=True)
nocond = [[empty_cond, {"pooled_output": pooled}]]
if context_length > 1 and set_context_length:
short_nocond = deepcopy(nocond)
for x in range(context_length - 1):
(nocond,) = ConditioningConcat.concat(nocond, short_nocond)
nocond = convert_cond(nocond)
@torch.no_grad()
def pre_cfg_patch(args):
conds_out = args["conds_out"]
sigma = args["sigma"][0]
# cond_scale = args["cond_scale"]
if sigma <= end_at_sigma or not torch.any(conds_out[1]):
return conds_out
model_options = args["model_options"]
timestep = args["timestep"]
model = args["model"]
x_orig = args["input"]
nocond_processed = encode_model_conds(model.extra_conds, nocond, x_orig, x_orig.device, "negative")
(noise_pred_nocond,) = calc_cond_batch(model, [nocond_processed], x_orig, timestep, model_options)
if progressive_scale:
progression = (sigma - sigma_min) / (sigma_max - sigma_min)
current_scale = progression * empty_proportion + (1 - progression) * (1 - empty_proportion)
current_scale = torch.clamp(current_scale, min=0, max=1)
conds_out[1] = current_scale * noise_pred_nocond + conds_out[1] * (1 - current_scale)
else:
conds_out[1] = empty_proportion * noise_pred_nocond + conds_out[1] * (1 - empty_proportion)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(pre_cfg_patch)
return (m, )
@torch.no_grad()
def normalize_adjust(a,b,strength=1):
norm_a = torch.linalg.norm(a)
a = selfnorm(a)
b = selfnorm(b)
res = b - a * (a * b).sum()
if res.isnan().any():
res = torch.nan_to_num(res, nan=0.0)
a = a - res * strength
return a * norm_a
class condDiffSharpeningNode:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"model": ("MODEL",),
"do_on": (["both","cond","uncond"], {"default": "both"},),
"scale": ("FLOAT", {"default": 0.75, "min": -10.0, "max": 10.0, "step": 1/20, "round": 1/100}),
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 100.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 01.0, "min": 0.0, "max": 100.0, "step": 1/100, "round": 1/100}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, do_on, scale, start_at_sigma, end_at_sigma):
model_sampling = model.model.model_sampling
sigma_max = model_sampling.sigma(model_sampling.timestep(model_sampling.sigma_max)).item()
prev_cond = None
prev_uncond = None
@torch.no_grad()
def sharpen_conds_pre_cfg(args):
nonlocal prev_cond, prev_uncond
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
sigma = args["sigma"][0].item()
first_step = sigma > (sigma_max - 1)
if first_step:
prev_cond = None
prev_uncond = None
for b in range(len(conds_out[0])):
for c in range(len(conds_out[0][b])):
if not first_step and sigma > end_at_sigma and sigma <= start_at_sigma:
if prev_cond is not None and do_on in ['both','cond']:
conds_out[0][b][c] = normalize_adjust(conds_out[0][b][c], prev_cond[b][c], scale)
if prev_uncond is not None and uncond and do_on in ['both','uncond']:
conds_out[1][b][c] = normalize_adjust(conds_out[1][b][c], prev_uncond[b][c], scale)
prev_cond = conds_out[0]
if uncond:
prev_uncond = conds_out[1]
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(sharpen_conds_pre_cfg)
return (m, )
@torch.no_grad()
def normalized_pow(t,p):
t_norm = t.norm()
t_sign = t.sign()
t_pow = (t / t_norm).abs().pow(p)
t_pow = selfnorm(t_pow) * t_norm * t_sign
return t_pow
class condExpNode:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"model": ("MODEL",),
"do_on": (["both","cond","uncond"], {"default": "both"},),
"exponent": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 10.0, "step": 1/20, "round": 1/100}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, do_on, exponent):
@torch.no_grad()
def exponentiate_conds_pre_cfg(args):
if args["sigma"][0] <= 1: return args["conds_out"]
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
if do_on in ['both','uncond'] and not uncond:
return conds_out
for b in range(len(conds_out[0])):
if do_on in ['both','cond']:
conds_out[0][b] = normalized_pow(conds_out[0][b], exponent)
if uncond and do_on in ['both','uncond']:
conds_out[1][b] = normalized_pow(conds_out[1][b], exponent)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(exponentiate_conds_pre_cfg)
return (m, )
@torch.no_grad()
def topk_average(latent, top_k=0.25, measure="average"):
max_values = torch.topk(latent.flatten(), k=ceil(latent.numel()*top_k), largest=True ).values
min_values = torch.topk(latent.flatten(), k=ceil(latent.numel()*top_k), largest=False).values
value_range = measuring_methods[measure](max_values, min_values)
return value_range
apply_scaling_methods = {
"individual": lambda c, m: c * torch.tensor(m).view(c.shape[0],1,1).to(c.device),
"all_as_one": lambda c, m: c * m[0],
"average_of_all_channels" : lambda c, m: c * (sum(m) / len(m)),
"smallest_of_all_channels": lambda c, m: c * min(m),
"biggest_of_all_channels" : lambda c, m: c * max(m),
}
measuring_methods = {
"difference": lambda x, y: (x.mean() - y.mean()).abs() / 2,
"average": lambda x, y: (x.mean() + y.abs().mean()) / 2,
"biggest": lambda x, y: max(x.mean(), y.abs().mean()),
}
class automatic_pre_cfg:
@classmethod
def INPUT_TYPES(s):
scaling_methods_names = [k for k in apply_scaling_methods]
measuring_methods_names = [k for k in measuring_methods]
return {"required": {
"model": ("MODEL",),
"scaling_method": (scaling_methods_names, {"default": scaling_methods_names[0]}),
"min_max_method": ([m for m in measuring_methods], {"default": measuring_methods_names[1]}),
"reference_CFG": ("FLOAT", {"default": 8, "min": 0.0, "max": 100, "step": 1/10, "round": 1/100}),
"scale_multiplier": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 100, "step": 1/100, "round": 1/100}),
"top_k": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 0.5, "step": 1/20, "round": 1/100}),
},
"optional": {
"channels_selection": ("CHANS",),
}
}
RETURN_TYPES = ("MODEL","STRING",)
RETURN_NAMES = ("MODEL","parameters",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, scaling_method, min_max_method="difference", reference_CFG=8, scale_multiplier=0.8, top_k=0.25, channels_selection=None):
parameters_string = f"scaling_method: {scaling_method}\nmin_max_method: {min_max_method}"
if channels_selection is not None:
for x in range(len(channels_selection)):
parameters_string += f"\nchannel {x+1}: {channels_selection[x]}"
scaling_methods_names = [k for k in apply_scaling_methods]
@torch.no_grad()
def automatic_pre_cfg(args):
conds_out = args["conds_out"]
cond_scale = args["cond_scale"]
uncond = torch.any(conds_out[1])
if reference_CFG == 0:
reference_scale = cond_scale
else:
reference_scale = reference_CFG
if not uncond:
return conds_out
if channels_selection is None:
channels = [True for _ in range(conds_out[0].shape[-3])]
else:
channels = channels_selection
for b in range(len(conds_out[0])):
chans = []
if scaling_method == scaling_methods_names[1]:
if all(channels):
mes = topk_average(reference_scale * conds_out[0][b] - (reference_scale - 1) * conds_out[1][b], top_k=top_k, measure=min_max_method)
else:
cond_for_measure = torch.stack([conds_out[0][b][j] for j in range(len(channels)) if channels[j]])
uncond_for_measure = torch.stack([conds_out[1][b][j] for j in range(len(channels)) if channels[j]])
mes = topk_average(reference_scale * cond_for_measure - (reference_scale - 1) * uncond_for_measure, top_k=top_k, measure=min_max_method)
chans.append(scale_multiplier / max(mes,0.01))
else:
for c in range(len(conds_out[0][b])):
if not channels[c]:
if scaling_method == scaling_methods_names[0]:
chans.append(1)
continue
mes = topk_average(reference_scale * conds_out[0][b][c] - (reference_scale - 1) * conds_out[1][b][c], top_k=top_k, measure=min_max_method)
new_scale = scale_multiplier / max(mes,0.01)
chans.append(new_scale)
conds_out[0][b] = apply_scaling_methods[scaling_method](conds_out[0][b],chans)
conds_out[1][b] = apply_scaling_methods[scaling_method](conds_out[1][b],chans)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(automatic_pre_cfg)
return (m, parameters_string,)
class channel_selection_node:
CHANNELS_AMOUNT = 4
@classmethod
def INPUT_TYPES(s):
toggles = {f"channel_{x}" : ("BOOLEAN", {"default": True}) for x in range(s.CHANNELS_AMOUNT)}
return {"required": toggles}
RETURN_TYPES = ("CHANS",)
FUNCTION = "exec"
CATEGORY = "model_patches/Pre CFG/channels_selectors"
def exec(self, **kwargs):
chans = []
for k, v in kwargs.items():
if "channel_" in k:
chans.append(v)
return (chans, )
class individual_channel_selection_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"exclude" : ("BOOLEAN", {"default": False}),
"selected_channel": ("INT", {"default": 1, "min": 1, "max": 128}),
"total_channels" : ("INT", {"default": 4, "min": 1, "max": 128}),
}
}
RETURN_TYPES = ("CHANS",)
FUNCTION = "exec"
CATEGORY = "model_patches/Pre CFG/channels_selectors"
def exec(self, exclude, selected_channel, total_channels):
chans = [exclude for _ in range(total_channels)]
chans[selected_channel - 1] = not exclude
return (chans, )
class channel_multiplier_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"model": ("MODEL",),
"channel_1": ("FLOAT", {"default": 1, "min": -10.0, "max": 10.0, "step": 1/100, "round": 1/100}),
"channel_2": ("FLOAT", {"default": 1, "min": -10.0, "max": 10.0, "step": 1/100, "round": 1/100}),
"channel_3": ("FLOAT", {"default": 1, "min": -10.0, "max": 10.0, "step": 1/100, "round": 1/100}),
"channel_4": ("FLOAT", {"default": 1, "min": -10.0, "max": 10.0, "step": 1/100, "round": 1/100}),
"selection": (["both","cond","uncond"],),
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 100.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 01.0, "min": 0.0, "max": 100.0, "step": 1/100, "round": 1/100}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, channel_1, channel_2, channel_3, channel_4, selection, start_at_sigma, end_at_sigma):
chans = [channel_1, channel_2, channel_3, channel_4]
@torch.no_grad()
def channel_multiplier_function(args):
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
sigma = args["sigma"]
if sigma[0] <= end_at_sigma or sigma[0] > start_at_sigma:
return conds_out
for b in range(len(conds_out[0])):
for c in range(len(conds_out[0][b])):
if selection in ["both","cond"]:
conds_out[0][b][c] *= chans[c]
if uncond and selection in ["both","uncond"]:
conds_out[1][b][c] *= chans[c]
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(channel_multiplier_function)
return (m, )
class support_empty_uncond_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"method": (["from cond","divide by CFG"],),
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, method):
@torch.no_grad()
def support_empty_uncond(args):
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
cond_scale = args["cond_scale"]
if not uncond and cond_scale > 1:
if method == "divide by CFG":
conds_out[0] /= cond_scale
else:
conds_out[1] = conds_out[0].clone()
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(support_empty_uncond)
return (m, )
def replace_timestep(cond):
cond = deepcopy(cond)
cond[0]['timestep_start'] = 999999999.9
cond[0]['timestep_end'] = 0.0
return cond
def check_if_in_timerange(conds,timestep_in):
for c in conds:
all_good = True
if 'timestep_start' in c:
timestep_start = c['timestep_start']
if timestep_in[0] > timestep_start:
all_good = False
if 'timestep_end' in c:
timestep_end = c['timestep_end']
if timestep_in[0] < timestep_end:
all_good = False
if all_good: return True
return False
class zero_attention_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"do_on": (["cond","uncond"], {"default": "uncond"},),
"mix_scale": ("FLOAT", {"default": 1.5, "min": -2.0, "max": 2.0, "step": 1/2, "round": 1/100}),
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
# "attention": (["both","self","cross"],),
# "unet_block": (["input","middle","output"],),
# "unet_block_id": ("INT", {"default": 8, "min": 0, "max": 20}),
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, do_on, mix_scale, start_at_sigma, end_at_sigma, attention="both", unet_block="input", unet_block_id=8):
cond_index = 1 if do_on == "uncond" else 0
attn = {"both":["attn1","attn2"],"self":["attn1"],"cross":["attn2"]}[attention]
def zero_attention_function(q, k, v, extra_options, mask=None):
return torch.zeros_like(q)
@torch.no_grad()
def zero_attention_pre_cfg_patch(args):
conds_out = args["conds_out"]
sigma = args["sigma"][0].item()
if sigma > start_at_sigma or sigma <= end_at_sigma:
return conds_out
conds = args["conds"]
cond_to_process = conds[cond_index]
cond_generated = torch.any(conds_out[cond_index])
if not cond_generated:
cond_to_process = replace_timestep(cond_to_process)
elif mix_scale == 1:
print(" Mix scale at one!\nPrediction not generated.\nUse the node ConditioningSetTimestepRange to avoid generating if you want to use this node.")
return conds_out
model_options = deepcopy(args["model_options"])
for att in attn:
model_options = comfy.model_patcher.set_model_options_patch_replace(model_options, zero_attention_function, att, unet_block, unet_block_id)
(noise_pred,) = calc_cond_batch(args['model'], [cond_to_process], args['input'], args['timestep'], model_options)
if mix_scale == 1 or not cond_generated:
conds_out[cond_index] = noise_pred
elif cond_generated:
conds_out[cond_index] = weighted_average(noise_pred,conds_out[cond_index],mix_scale)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(zero_attention_pre_cfg_patch)
return (m, )
class perturbed_attention_guidance_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"scale": ("FLOAT", {"default": 0.5, "min": -2.0, "max": 10.0, "step": 1/20, "round": 1/100}),
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, scale, start_at_sigma, end_at_sigma, do_on="cond", attention="self", unet_block="middle", unet_block_id=0):
cond_index = 1 if do_on == "uncond" else 0
attn = {"both":["attn1","attn2"],"self":["attn1"],"cross":["attn2"]}[attention]
def perturbed_attention_guidance(q, k, v, extra_options, mask=None):
return v
@torch.no_grad()
def perturbed_attention_guidance_pre_cfg_patch(args):
conds_out = args["conds_out"]
sigma = args["sigma"][0].item()
if sigma > start_at_sigma or sigma <= end_at_sigma:
return conds_out
conds = args["conds"]
cond_to_process = conds[cond_index]
cond_generated = torch.any(conds_out[cond_index])
if not cond_generated:
return conds_out
model_options = deepcopy(args["model_options"])
for att in attn:
model_options = comfy.model_patcher.set_model_options_patch_replace(model_options, perturbed_attention_guidance, att, unet_block, unet_block_id)
(noise_pred,) = calc_cond_batch(args['model'], [cond_to_process], args['input'], args['timestep'], model_options)
conds_out[cond_index] = conds_out[cond_index] + (conds_out[cond_index] - noise_pred) * scale
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(perturbed_attention_guidance_pre_cfg_patch)
return (m, )
def sigma_to_percent(model_sampling, sigma_value):
if sigma_value >= 999999999.9:
return 0.0
if sigma_value <= 0.0:
return 1.0
sigma_tensor = torch.tensor([sigma_value], dtype=torch.float32)
timestep = model_sampling.timestep(sigma_tensor)
percent = 1.0 - (timestep.item() / 999.0)
return percent
class ConditioningSetTimestepRangeFromSigma:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"conditioning": ("CONDITIONING", ),
"sigma_start" : ("FLOAT", {"default": 15.0, "min": 0.0, "max": 10000.0, "step": 0.01}),
"sigma_end" : ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10000.0, "step": 0.01})
}}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "set_range"
CATEGORY = "advanced/conditioning"
def set_range(self, model, conditioning, sigma_start, sigma_end):
model_sampling = model.model.model_sampling
(c, ) = ConditioningSetTimestepRange.set_range(conditioning,sigma_to_percent(model_sampling, sigma_start),sigma_to_percent(model_sampling, sigma_end))
return (c, )
class ShapeAttentionNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"scale": ("FLOAT", {"default": 1.5, "min": 0.0, "max": 10.0, "step": 1/10, "round": 1/100}),
# "start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
# "end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
# "enabled" : ("BOOLEAN", {"default": True}),
# "attention": (["both","self","cross"],),
# "unet_block": (["input","middle","output"],),
# "unet_block_id": ("INT", {"default": 8, "min": 0, "max": 20}), # uncomment these lines if you want to have fun with the other layers
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches"
def patch(self, model, scale, start_at_sigma=999999999.9, end_at_sigma=0.0, enabled=True, attention="self", unet_block="input", unet_block_id=8):
attn = {"both":["attn1","attn2"],"self":["attn1"],"cross":["attn2"]}[attention]
if scale == 1:
print(" Shape attention disabled (scale is one)")
if not enabled or scale == 1:
return (model,)
m = model.clone()
def shape_attention(q, k, v, extra_options, mask=None):
sigma = extra_options['sigmas'][0]
if sigma > start_at_sigma or sigma <= end_at_sigma:
return default_attention(q, k, v, extra_options['n_heads'], mask)
if scale != 0:
return default_attention(q, k, v, extra_options['n_heads'], mask) * scale
else:
return torch.zeros_like(q)
for att in attn:
m.model_options = comfy.model_patcher.set_model_options_patch_replace(m.model_options, shape_attention, att, unet_block, unet_block_id)
return (m,)
class ExlAttentionNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"scale": ("FLOAT", {"default": 2, "min": -1.0, "max": 10.0, "step": 1/10, "round": 1/100}),
"enabled": ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches"
def patch(self, model, scale, enabled):
if not enabled:
return (model,)
m = model.clone()
def cross_patch(q, k, v, extra_options, mask=None):
first_attention = default_attention(q, k, v, extra_options['n_heads'], mask)
second_attention = normlike(q+(q-default_attention(first_attention, k, v, extra_options['n_heads'])), first_attention) * scale
return second_attention
m.model_options = comfy.model_patcher.set_model_options_patch_replace(m.model_options, cross_patch, "attn2", "middle", 0)
return (m,)
class PreCFGsubtractMeanNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
# "per_channel" : ("BOOLEAN", {"default": False}), #It's just not good
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"enabled" : ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, start_at_sigma, end_at_sigma, enabled, per_channel=False):
if not enabled: return (model,)
m = model.clone()
def pre_cfg_function(args):
conds_out = args["conds_out"]
sigma = args["sigma"][0].item()
if sigma > start_at_sigma or sigma <= end_at_sigma:
return conds_out
for x in range(len(conds_out)):
if torch.any(conds_out[x]):
for b in range(len(conds_out[x])):
if per_channel:
for c in range(len(conds_out[x][b])):
conds_out[x][b][c] -= conds_out[x][b][c].mean()
else:
conds_out[x][b] -= conds_out[x][b].mean()
return conds_out
m.set_model_sampler_pre_cfg_function(pre_cfg_function)
return (m,)
class PostCFGsubtractMeanNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
# "per_channel" : ("BOOLEAN", {"default": False}), #It's just not good
"start_at_sigma": ("FLOAT", {"default": 15.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"enabled" : ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches"
def patch(self, model, start_at_sigma, end_at_sigma, enabled, per_channel=False):
if not enabled: return (model,)
m = model.clone()
def post_cfg_function(args):
cfg_result = args["denoised"]
sigma = args["sigma"][0].item()
if sigma > start_at_sigma or sigma <= end_at_sigma:
return cfg_result
for b in range(len(cfg_result)):
if per_channel:
for c in range(len(cfg_result[b])):
cfg_result[b][c] -= cfg_result[b][c].mean()
else:
cfg_result[b] -= cfg_result[b].mean()
return cfg_result
m.set_model_sampler_post_cfg_function(post_cfg_function)
return (m,)
class PostCFGDotNode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model": ("MODEL",),
"batch": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
"channel": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
"coord_x": ("INT", {"default": 64, "min": 0, "max": 1000, "step": 1}),
"coord_y": ("INT", {"default": 64, "min": 0, "max": 1000, "step": 1}),
"value": ("FLOAT", {"default": 1, "min": -10.0, "max": 10.0, "step": 1/10, "round": 1/100}),
"start_at_sigma": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"enabled" : ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches"
def patch(self, model, batch, channel, coord_x, coord_y, value, start_at_sigma, end_at_sigma, enabled):
if not enabled: return (model,)
m = model.clone()
def post_cfg_function(args):
cfg_result = args["denoised"]
sigma = args["sigma"][0].item()
if sigma > start_at_sigma or sigma <= end_at_sigma:
return cfg_result
channel_norm = cfg_result[batch][channel].norm()
cfg_result[batch][channel] /= channel_norm
cfg_result[batch][channel][coord_y][coord_x] = value
cfg_result[batch][channel] *= channel_norm
return cfg_result
m.set_model_sampler_post_cfg_function(post_cfg_function)
return (m,)
class uncondZeroPreCFGNode:
@classmethod
def INPUT_TYPES(s):
scaling_methods_names = [k for k in apply_scaling_methods]
return {"required": {
"model": ("MODEL",),
"scale": ("FLOAT", {"default": 0.75, "min": 0.0, "max": 10.0, "step": 1/20, "round": 0.01}),
"start_at_sigma": ("FLOAT", {"default": 100, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"end_at_sigma": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1000.0, "step": 1/100, "round": 1/100}),
"scaling_method": (scaling_methods_names, {"default": scaling_methods_names[2]}),
}
}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, scale, start_at_sigma, end_at_sigma, scaling_method):
scaling_methods_names = [k for k in apply_scaling_methods]
@torch.no_grad()
def uncond_zero_pre_cfg(args):
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
sigma = args["sigma"][0].item()
if uncond or sigma <= end_at_sigma or sigma > start_at_sigma:
return conds_out
for b in range(len(conds_out[0])):
chans = []
if scaling_method == scaling_methods_names[1]:
mes = topk_average(8 * conds_out[0][b] - 7 * conds_out[1][b], measure="difference")
for c in range(len(conds_out[0][b])):
mes = topk_average(conds_out[0][b][c], measure="difference") ** 0.5
chans.append(scale / mes)
conds_out[0][b] = apply_scaling_methods[scaling_method](conds_out[0][b],chans)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(uncond_zero_pre_cfg)
return (m, )
class variable_scale_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"target_scale": ("FLOAT", {"default": 5.0, "min": 1.0, "max": 100.0, "step": 1/2, "round": 1/100}),
"target_as_start": ("BOOLEAN", {"default": True}),
"proportional_to": (["sigma","steps progression"],),
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, target_scale, target_as_start, proportional_to):
model_sampling = model.model.model_sampling
sigma_max = model_sampling.sigma(model_sampling.timestep(model_sampling.sigma_max)).item()
@torch.no_grad()
def variable_scale_pre_cfg_patch(args):
conds_out = args["conds_out"]
cond_scale = args["cond_scale"]
sigma = args["sigma"][0].item()
scales = [cond_scale,target_scale]
if not torch.any(conds_out[1]):
return conds_out
if proportional_to == "steps progression":
progression = sigma_to_percent(model_sampling, sigma)
else:
progression = 1 - sigma / sigma_max
progression = max(min(progression, 1), 0)
current_scale = scales[target_as_start] * (1 - progression) + scales[not target_as_start] * progression
new_scale = (current_scale - 1) / (cond_scale - 1)
conds_out[1] = weighted_average(conds_out[1], conds_out[0], new_scale)
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(variable_scale_pre_cfg_patch)
return (m, )
class latent_noise_subtract_mean_node:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {"required": {
"latent_input": ("LATENT", {"forceInput": True}),
"enabled" : ("BOOLEAN", {"default": True}),
}}
FUNCTION = "exec"
RETURN_TYPES = ("LATENT",)
CATEGORY = "latent"
def exec(self, latent_input, enabled):
if not enabled:
return (latent_input,)
new_latents = deepcopy(latent_input)
for x in range(len(new_latents['samples'])):
new_latents['samples'][x] -= torch.mean(new_latents['samples'][x])
return (new_latents,)
class flip_flip_conds_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"enabled" : ("BOOLEAN", {"default": True})
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, enabled):
@torch.no_grad()
def pre_cfg_patch(args):
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
if not uncond or not enabled:
return conds_out
conds_out[0], conds_out[1] = conds_out[1], conds_out[0]
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(pre_cfg_patch)
return (m, )
class norm_uncond_to_cond_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"enabled" : ("BOOLEAN", {"default": True})
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, enabled):
@torch.no_grad()
def pre_cfg_patch(args):
conds_out = args["conds_out"]
uncond = torch.any(conds_out[1])
if not uncond or not enabled:
return conds_out
conds_out[1] = conds_out[1] / conds_out[1].norm() * conds_out[0].norm()
return conds_out
m = model.clone()
m.set_model_sampler_pre_cfg_function(pre_cfg_patch)
return (m, )
class replace_uncond_channel_pre_cfg_node:
@classmethod
def INPUT_TYPES(s):
return {"required": {"model": ("MODEL",),
"channel": ("INT", {"default": 1, "min": 1, "max": 128, "step": 1}),
"enabled" : ("BOOLEAN", {"default": True})
}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "patch"
CATEGORY = "model_patches/Pre CFG"
def patch(self, model, channel, enabled):
@torch.no_grad()
def pre_cfg_patch(args):
conds_out = args["conds_out"]