-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathconditioning.py
More file actions
2014 lines (1590 loc) · 85.6 KB
/
conditioning.py
File metadata and controls
2014 lines (1590 loc) · 85.6 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
import math
from torch import Tensor
from typing import Optional, Callable, Tuple, Dict, Any, Union, TYPE_CHECKING, TypeVar, List
from dataclasses import dataclass, field
import copy
import base64
import pickle # used strictly for serializing conditioning in the ConditioningToBase64 and Base64ToConditioning nodes for API use. (Offloading T5 processing to another machine to avoid model shuffling.)
import comfy.supported_models
import node_helpers
import gc
from .sigmas import get_sigmas
from .helper import initialize_or_scale, precision_tool, get_res4lyf_scheduler_list, pad_tensor_list_to_max_len
from .latents import get_orthogonal, get_collinear
from .res4lyf import RESplain
from .beta.constants import MAX_STEPS
from .attention_masks import FullAttentionMask, FullAttentionMaskHiDream, CrossAttentionMask, SplitAttentionMask, RegionalContext
from .flux.redux import ReReduxImageEncoder
def multiply_nested_tensors(structure, scalar):
if isinstance(structure, torch.Tensor):
return structure * scalar
elif isinstance(structure, list):
return [multiply_nested_tensors(item, scalar) for item in structure]
elif isinstance(structure, dict):
return {key: multiply_nested_tensors(value, scalar) for key, value in structure.items()}
else:
return structure
def pad_to_same_tokens(x1, x2, pad_value=0.0):
T1, T2 = x1.shape[1], x2.shape[1]
if T1 == T2:
return x1, x2
max_T = max(T1, T2)
x1_padded = F.pad(x1, (0, 0, 0, max_T - T1), value=pad_value)
x2_padded = F.pad(x2, (0, 0, 0, max_T - T2), value=pad_value)
return x1_padded, x2_padded
class ConditioningOrthoCollin:
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"conditioning_0": ("CONDITIONING", ),
"conditioning_1": ("CONDITIONING", ),
"t5_strength" : ("FLOAT", {"default": 1.0, "min": -10000, "max": 10000, "step":0.01}),
"clip_strength" : ("FLOAT", {"default": 1.0, "min": -10000, "max": 10000, "step":0.01}),
}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "combine"
CATEGORY = "RES4LYF/conditioning"
EXPERIMENTAL = True
def combine(self, conditioning_0, conditioning_1, t5_strength, clip_strength):
t5_0_1_collin = get_collinear (conditioning_0[0][0], conditioning_1[0][0])
t5_1_0_ortho = get_orthogonal(conditioning_1[0][0], conditioning_0[0][0])
t5_combined = t5_0_1_collin + t5_1_0_ortho
t5_1_0_collin = get_collinear (conditioning_1[0][0], conditioning_0[0][0])
t5_0_1_ortho = get_orthogonal(conditioning_0[0][0], conditioning_1[0][0])
t5_B_combined = t5_1_0_collin + t5_0_1_ortho
pooled_0_1_collin = get_collinear (conditioning_0[0][1]['pooled_output'].unsqueeze(0), conditioning_1[0][1]['pooled_output'].unsqueeze(0)).squeeze(0)
pooled_1_0_ortho = get_orthogonal(conditioning_1[0][1]['pooled_output'].unsqueeze(0), conditioning_0[0][1]['pooled_output'].unsqueeze(0)).squeeze(0)
pooled_combined = pooled_0_1_collin + pooled_1_0_ortho
#conditioning_0[0][0] = conditioning_0[0][0] + t5_strength * (t5_combined - conditioning_0[0][0])
#conditioning_0[0][0] = t5_strength * t5_combined + (1-t5_strength) * t5_B_combined
conditioning_0[0][0] = t5_strength * t5_0_1_collin + (1-t5_strength) * t5_1_0_collin
conditioning_0[0][1]['pooled_output'] = conditioning_0[0][1]['pooled_output'] + clip_strength * (pooled_combined - conditioning_0[0][1]['pooled_output'])
return (conditioning_0, )
class CLIPTextEncodeFluxUnguided:
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"clip" : ("CLIP", ),
"clip_l": ("STRING", {"multiline": True, "dynamicPrompts": True}),
"t5xxl" : ("STRING", {"multiline": True, "dynamicPrompts": True}),
}}
RETURN_TYPES = ("CONDITIONING","INT","INT",)
RETURN_NAMES = ("conditioning", "clip_l_end", "t5xxl_end",)
FUNCTION = "encode"
CATEGORY = "RES4LYF/conditioning"
EXPERIMENTAL = True
def encode(self, clip, clip_l, t5xxl):
tokens = clip.tokenize(clip_l)
tokens["t5xxl"] = clip.tokenize(t5xxl)["t5xxl"]
clip_l_end=0
for i in range(len(tokens['l'][0])):
if tokens['l'][0][i][0] == 49407:
clip_l_end=i
break
t5xxl_end=0
for i in range(len(tokens['l'][0])): # bug? should this be t5xxl?
if tokens['t5xxl'][0][i][0] == 1:
t5xxl_end=i
break
output = clip.encode_from_tokens(tokens, return_pooled=True, return_dict=True)
cond = output.pop("cond")
conditioning = [[cond, output]]
conditioning[0][1]['clip_l_end'] = clip_l_end
conditioning[0][1]['t5xxl_end'] = t5xxl_end
return (conditioning, clip_l_end, t5xxl_end,)
class StyleModelApplyStyle:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning": ("CONDITIONING", ),
"style_model": ("STYLE_MODEL", ),
"clip_vision_output": ("CLIP_VISION_OUTPUT", ),
"strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.001}),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
DESCRIPTION = "Use with Flux Redux."
EXPERIMENTAL = True
def main(self, clip_vision_output, style_model, conditioning, strength=1.0):
c = style_model.model.feature_match(conditioning, clip_vision_output)
#cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
#cond = strength * cond
#c = []
#for t in conditioning:
# n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
# c.append(n)
return (c, )
class ConditioningZeroAndTruncate:
# needs updating to ensure dims are correct for arbitrary models without hardcoding.
# vanilla ConditioningZeroOut node doesn't truncate and SD3.5M degrades badly with large embeddings, even if zeroed out, as the negative conditioning
@classmethod
def INPUT_TYPES(cls):
return { "required": {"conditioning": ("CONDITIONING", )}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "zero_out"
CATEGORY = "RES4LYF/conditioning"
DESCRIPTION = "Use for negative conditioning with SD3.5. ConditioningZeroOut does not truncate the embedding, \
which results in severe degradation of image quality with SD3.5 when the token limit is exceeded."
def zero_out(self, conditioning):
c = []
for t in conditioning:
d = t[1].copy()
pooled_output = d.get("pooled_output", None)
if pooled_output is not None:
d["pooled_output"] = torch.zeros((1,2048), dtype=t[0].dtype, device=t[0].device)
n = [torch.zeros((1,154,4096), dtype=t[0].dtype, device=t[0].device), d]
c.append(n)
return (c, )
class ConditioningTruncate:
# needs updating to ensure dims are correct for arbitrary models without hardcoding.
@classmethod
def INPUT_TYPES(cls):
return { "required": {"conditioning": ("CONDITIONING", )}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "zero_out"
CATEGORY = "RES4LYF/conditioning"
DESCRIPTION = "Use for positive conditioning with SD3.5. Tokens beyond 77 result in degradation of image quality."
EXPERIMENTAL = True
def zero_out(self, conditioning):
c = []
for t in conditioning:
d = t[1].copy()
pooled_output = d.get("pooled_output", None)
if pooled_output is not None:
d["pooled_output"] = d["pooled_output"][:, :2048]
n = [t[0][:, :154, :4096], d]
c.append(n)
return (c, )
class ConditioningMultiply:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"conditioning": ("CONDITIONING", ),
"multiplier": ("FLOAT", {"default": 1.0, "min": -1000000000.0, "max": 1000000000.0, "step": 0.01})
}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
def main(self, conditioning, multiplier):
c = multiply_nested_tensors(conditioning, multiplier)
return (c,)
class ConditioningAdd:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"conditioning_1": ("CONDITIONING", ),
"conditioning_2": ("CONDITIONING", ),
"multiplier": ("FLOAT", {"default": 1.0, "min": -1000000000.0, "max": 1000000000.0, "step": 0.01})
}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
def main(self, conditioning_1, conditioning_2, multiplier):
conditioning_1[0][0] += multiplier * conditioning_2[0][0]
conditioning_1[0][1]['pooled_output'] += multiplier * conditioning_2[0][1]['pooled_output']
return (conditioning_1,)
class ConditioningCombine:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "combine"
CATEGORY = "RES4LYF/conditioning"
def combine(self, conditioning_1, conditioning_2):
return (conditioning_1 + conditioning_2, )
class ConditioningAverage :
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning_to": ("CONDITIONING", ),
"conditioning_from": ("CONDITIONING", ),
"conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
CATEGORY = "RES4LYF/conditioning"
FUNCTION = "addWeighted"
def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength):
out = []
if len(conditioning_from) > 1:
RESplain("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
cond_from = conditioning_from[0][0]
pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
for i in range(len(conditioning_to)):
t1 = conditioning_to[i][0]
pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
t0 = cond_from[:,:t1.shape[1]]
if t0.shape[1] < t1.shape[1]:
t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
t_to = conditioning_to[i][1].copy()
if pooled_output_from is not None and pooled_output_to is not None:
t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
elif pooled_output_from is not None:
t_to["pooled_output"] = pooled_output_from
n = [tw, t_to]
out.append(n)
return (out, )
class ConditioningSetTimestepRange:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"conditioning": ("CONDITIONING", ),
"start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
}}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "set_range"
CATEGORY = "RES4LYF/conditioning"
def set_range(self, conditioning, start, end):
c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start,
"end_percent": end})
return (c, )
class ConditioningAverageScheduler: # don't think this is implemented correctly. needs to be reworked
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning_0": ("CONDITIONING", ),
"conditioning_1": ("CONDITIONING", ),
"ratio": ("SIGMAS", ),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
EXPERIMENTAL = True
@staticmethod
def addWeighted(conditioning_to, conditioning_from, conditioning_to_strength): #this function borrowed from comfyui
out = []
if len(conditioning_from) > 1:
RESplain("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
cond_from = conditioning_from[0][0]
pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
for i in range(len(conditioning_to)):
t1 = conditioning_to[i][0]
pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
t0 = cond_from[:,:t1.shape[1]]
if t0.shape[1] < t1.shape[1]:
t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
t_to = conditioning_to[i][1].copy()
if pooled_output_from is not None and pooled_output_to is not None:
t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
elif pooled_output_from is not None:
t_to["pooled_output"] = pooled_output_from
n = [tw, t_to]
out.append(n)
return out
@staticmethod
def create_percent_array(steps):
step_size = 1.0 / steps
return [{"start_percent": i * step_size, "end_percent": (i + 1) * step_size} for i in range(steps)]
def main(self, conditioning_0, conditioning_1, ratio):
steps = len(ratio)
percents = self.create_percent_array(steps)
cond = []
for i in range(steps):
average = self.addWeighted(conditioning_0, conditioning_1, ratio[i].item())
cond += node_helpers.conditioning_set_values(average, {"start_percent": percents[i]["start_percent"], "end_percent": percents[i]["end_percent"]})
return (cond,)
class StableCascade_StageB_Conditioning64:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning": ("CONDITIONING",),
"stage_c": ("LATENT",),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "set_prior"
CATEGORY = "RES4LYF/conditioning"
@precision_tool.cast_tensor
def set_prior(self, conditioning, stage_c):
c = []
for t in conditioning:
d = t[1].copy()
d['stable_cascade_prior'] = stage_c['samples']
n = [t[0], d]
c.append(n)
return (c, )
class Conditioning_Recast64:
@classmethod
def INPUT_TYPES(cls):
return {"required": { "cond_0": ("CONDITIONING",),
},
"optional": { "cond_1": ("CONDITIONING",),}
}
RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
RETURN_NAMES = ("cond_0_recast","cond_1_recast",)
FUNCTION = "main"
CATEGORY = "RES4LYF/precision"
EXPERIMENTAL = True
@precision_tool.cast_tensor
def main(self, cond_0, cond_1 = None):
cond_0[0][0] = cond_0[0][0].to(torch.float64)
if 'pooled_output' in cond_0[0][1]:
cond_0[0][1]["pooled_output"] = cond_0[0][1]["pooled_output"].to(torch.float64)
if cond_1 is not None:
cond_1[0][0] = cond_1[0][0].to(torch.float64)
if 'pooled_output' in cond_0[0][1]:
cond_1[0][1]["pooled_output"] = cond_1[0][1]["pooled_output"].to(torch.float64)
return (cond_0, cond_1,)
class ConditioningToBase64:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning": ("CONDITIONING",),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
FUNCTION = "notify"
OUTPUT_NODE = True
OUTPUT_IS_LIST = (True,)
CATEGORY = "RES4LYF/utilities"
def notify(self, unique_id=None, extra_pnginfo=None, conditioning=None):
conditioning_pickle = pickle.dumps(conditioning)
conditioning_base64 = base64.b64encode(conditioning_pickle).decode('utf-8')
text = [conditioning_base64]
if unique_id is not None and extra_pnginfo is not None:
if not isinstance(extra_pnginfo, list):
RESplain("Error: extra_pnginfo is not a list")
elif (
not isinstance(extra_pnginfo[0], dict)
or "workflow" not in extra_pnginfo[0]
):
RESplain("Error: extra_pnginfo[0] is not a dict or missing 'workflow' key")
else:
workflow = extra_pnginfo[0]["workflow"]
node = next(
(x for x in workflow["nodes"] if str(x["id"]) == str(unique_id[0])),
None,
)
if node:
node["widgets_values"] = [text]
return {"ui": {"text": text}, "result": (text,)}
class Base64ToConditioning:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"data": ("STRING", {"default": ""}),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/utilities"
def main(self, data):
conditioning_pickle = base64.b64decode(data)
conditioning = pickle.loads(conditioning_pickle)
return (conditioning,)
class ConditioningDownsampleT5:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning": ("CONDITIONING",),
"token_limit" : ("INT", {'default': 128, 'min': 1, 'max': 16384}),
},
"optional": {
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
EXPERIMENTAL = True
def main(self, conditioning, token_limit):
conditioning[0][0] = downsample_tokens(conditioning[0][0], token_limit)
return (conditioning, )
"""class ConditioningBatch4:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning_0": ("CONDITIONING",),
},
"optional": {
"conditioning_1": ("CONDITIONING",),
"conditioning_2": ("CONDITIONING",),
"conditioning_3": ("CONDITIONING",),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
def main(self, conditioning_0, conditioning_1=None, conditioning_2=None, conditioning_3=None, ):
c = copy.deepcopy(conditioning_0)
if conditioning_1 is not None:
c.append(conditioning_1[0])
if conditioning_2 is not None:
c.append(conditioning_2[0])
if conditioning_3 is not None:
c.append(conditioning_3[0])
return (c, )"""
class ConditioningBatch4:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning_0": ("CONDITIONING",),
},
"optional": {
"conditioning_1": ("CONDITIONING",),
"conditioning_2": ("CONDITIONING",),
"conditioning_3": ("CONDITIONING",),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
def main(self, conditioning_0, conditioning_1=None, conditioning_2=None, conditioning_3=None, ):
c = []
c.append(conditioning_0)
if conditioning_1 is not None:
c.append(conditioning_1)
if conditioning_2 is not None:
c.append(conditioning_2)
if conditioning_3 is not None:
c.append(conditioning_3)
return (c, )
class ConditioningBatch8:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"conditioning_0": ("CONDITIONING",),
},
"optional": {
"conditioning_1": ("CONDITIONING",),
"conditioning_2": ("CONDITIONING",),
"conditioning_3": ("CONDITIONING",),
"conditioning_4": ("CONDITIONING",),
"conditioning_5": ("CONDITIONING",),
"conditioning_6": ("CONDITIONING",),
"conditioning_7": ("CONDITIONING",),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "main"
CATEGORY = "RES4LYF/conditioning"
def main(self, conditioning_0, conditioning_1=None, conditioning_2=None, conditioning_3=None, conditioning_4=None, conditioning_5=None, conditioning_6=None, conditioning_7=None, ):
c = []
c.append(conditioning_0)
if conditioning_1 is not None:
c.append(conditioning_1)
if conditioning_2 is not None:
c.append(conditioning_2)
if conditioning_3 is not None:
c.append(conditioning_3)
if conditioning_4 is not None:
c.append(conditioning_4)
if conditioning_5 is not None:
c.append(conditioning_5)
if conditioning_6 is not None:
c.append(conditioning_6)
if conditioning_7 is not None:
c.append(conditioning_7)
return (c, )
class EmptyConditioningGenerator:
def __init__(self, model=None, conditioning=None, device=None, dtype=None):
""" device, dtype currently unused """
if model is not None:
self.device = device
self.dtype = dtype
import comfy.supported_models
self.model_config = model.model.model_config
self.llama3_shape = None
self.pooled_len = 0
if isinstance(self.model_config, comfy.supported_models.SD3):
self.text_len_base = 154
self.text_channels = 4096
self.pooled_len = 2048
elif isinstance(self.model_config, (comfy.supported_models.Flux, comfy.supported_models.FluxSchnell, comfy.supported_models.Chroma)):
self.text_len_base = 256
self.text_channels = 4096
self.pooled_len = 768
elif isinstance(self.model_config, comfy.supported_models.AuraFlow):
self.text_len_base = 256
self.text_channels = 2048
#self.pooled_len = 1
elif isinstance(self.model_config, comfy.supported_models.Stable_Cascade_C):
self.text_len_base = 77
self.text_channels = 1280
self.pooled_len = 1280
elif isinstance(self.model_config, comfy.supported_models.WAN21_T2V) or isinstance(self.model_config, comfy.supported_models.WAN21_I2V):
self.text_len_base = 512
self.text_channels = 5120 # sometimes needs to be 4096, like when initializing in samplers_py in shark?
#self.pooled_len = 1
elif isinstance(self.model_config, comfy.supported_models.HiDream):
self.text_len_base = 128
self.text_channels = 4096 # sometimes needs to be 4096, like when initializing in samplers_py in shark?
self.pooled_len = 2048
self.llama3_shape = torch.Size([1,32,128,4096])
elif isinstance(self.model_config, comfy.supported_models.LTXV):
self.text_len_base = 128
self.text_channels = 4096
#self.pooled_len = 1
elif isinstance(self.model_config, comfy.supported_models.SD15):
self.text_len_base = 77
self.text_channels = 768
self.pooled_len = 768
elif isinstance(self.model_config, comfy.supported_models.SDXL):
self.text_len_base = 77
self.text_channels = 2048
self.pooled_len = 1280
elif isinstance(self.model_config, comfy.supported_models.HunyuanVideo) or \
isinstance (self.model_config, comfy.supported_models.HunyuanVideoI2V) or \
isinstance (self.model_config, comfy.supported_models.HunyuanVideoSkyreelsI2V):
self.text_len_base = 128
self.text_channels = 4096
#self.pooled_len = 1
else:
raise ValueError(f"Unknown model config: {type(self.model_config)}")
elif conditioning is not None:
self.device = conditioning[0][0].device
self.dtype = conditioning[0][0].dtype
self.text_len_base = conditioning[0][0].shape[-2]
if 'pooled_output' in conditioning[0][1]:
self.pooled_len = conditioning[0][1]['pooled_output'].shape[-1]
else:
self.pooled_len = 0
self.text_channels = conditioning[0][0].shape[-1]
def get_empty_conditioning(self):
if self.llama3_shape is not None and self.pooled_len > 0:
return [[
torch.zeros((1, self.text_len_base, self.text_channels)),
{
'pooled_output' : torch.zeros((1, self.pooled_len)),
'conditioning_llama3': torch.zeros(self.llama3_shape),
}
]]
elif self.pooled_len > 0:
return [[
torch.zeros((1, self.text_len_base, self.text_channels)),
{
'pooled_output': torch.zeros((1, self.pooled_len)),
}
]]
else:
return [[
torch.zeros((1, self.text_len_base, self.text_channels)),
]]
def get_empty_conditionings(self, count):
return [self.get_empty_conditioning() for _ in range(count)]
def zero_none_conditionings_(self, *conds):
if len(conds) == 1 and isinstance(conds[0], (list, tuple)):
conds = conds[0]
for i, cond in enumerate(conds):
conds[i] = self.get_empty_conditioning() if cond is None else cond
return conds
"""def zero_conditioning_from_list(conds):
for cond in conds:
if cond is not None:
for i in range(len(cond)):
pooled = cond[i][1].get('pooled_output')
pooled_len = pooled.shape[-1] if pooled is not None else 1 # 1 default pooled_output len for those without it
cond_zero = [[
torch.zeros_like(cond[i][0]),
{"pooled_output": torch.zeros((1,pooled_len), dtype=cond[i][0].dtype, device=cond[i][0].device)},
]]
return cond_zero"""
def zero_conditioning_from_list(conds):
for cond in conds:
if cond is not None:
for i in range(len(cond)):
pooled = cond[i][1].get('pooled_output')
llama3 = cond[i][1].get('conditioning_llama3')
pooled_len = pooled.shape[-1] if pooled is not None else 1
llama3_shape = llama3.shape if llama3 is not None else (1, 32, 128, 4096)
cond_zero = [[
torch.zeros_like(cond[i][0]),
{
"pooled_output": torch.zeros((1, pooled_len), dtype=cond[i][0].dtype, device=cond[i][0].device),
"conditioning_llama3": torch.zeros(llama3_shape, dtype=cond[i][0].dtype, device=cond[i][0].device),
},
]]
return cond_zero
class TemporalMaskGenerator:
@classmethod
def INPUT_TYPES(cls):
return {"required":
{
"switch_frame": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"frames": ("INT", {"default": 65, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"invert_mask": ("BOOLEAN", {"default": False}),
},
"optional":
{
}
}
RETURN_TYPES = ("MASK",)
RETURN_NAMES = ("temporal_mask",)
FUNCTION = "main"
CATEGORY = "RES4LYF/masks"
EXPERIMENTAL = True
def main(self,
switch_frame = 33,
frames = 65,
invert_mask = False,
):
switch_frame = switch_frame // 4
frames = frames // 4 + 1
temporal_mask = torch.ones((frames, 2, 2))
temporal_mask[switch_frame:,...] = 0.0
if invert_mask:
temporal_mask = 1 - temporal_mask
return (temporal_mask,)
class TemporalSplitAttnMask_Midframe:
@classmethod
def INPUT_TYPES(cls):
return {"required":
{
"self_attn_midframe": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"cross_attn_midframe": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"self_attn_invert": ("BOOLEAN", {"default": False}),
"cross_attn_invert": ("BOOLEAN", {"default": False}),
"frames": ("INT", {"default": 65, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
},
"optional":
{
}
}
RETURN_TYPES = ("MASK",)
RETURN_NAMES = ("temporal_mask",)
FUNCTION = "main"
CATEGORY = "RES4LYF/masks"
EXPERIMENTAL = True
def main(self,
self_attn_midframe = 33,
cross_attn_midframe = 33,
self_attn_invert = False,
cross_attn_invert = False,
frames = 65,
):
frames = frames // 4 + 1
temporal_self_mask = torch.ones((frames, 2, 2))
temporal_cross_mask = torch.ones((frames, 2, 2))
self_attn_midframe = self_attn_midframe // 4
cross_attn_midframe = cross_attn_midframe // 4
temporal_self_mask[self_attn_midframe :,...] = 0.0
temporal_cross_mask[cross_attn_midframe:,...] = 0.0
if self_attn_invert:
temporal_self_mask = 1 - temporal_self_mask
if cross_attn_invert:
temporal_cross_mask = 1 - temporal_cross_mask
temporal_attn_masks = torch.stack([temporal_cross_mask, temporal_self_mask])
return (temporal_attn_masks,)
class TemporalSplitAttnMask:
@classmethod
def INPUT_TYPES(cls):
return {"required":
{
"self_attn_start": ("INT", {"default": 1, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"self_attn_stop": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"cross_attn_start": ("INT", {"default": 1, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"cross_attn_stop": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
#"frames": ("INT", {"default": 65, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
},
"optional":
{
}
}
RETURN_TYPES = ("MASK",)
RETURN_NAMES = ("temporal_mask",)
FUNCTION = "main"
CATEGORY = "RES4LYF/masks"
def main(self,
self_attn_start = 0,
self_attn_stop = 33,
cross_attn_start = 0,
cross_attn_stop = 33,
#frames = 65,
):
#frames = frames // 4 + 1
self_attn_start = self_attn_start // 4 #+ 1
self_attn_stop = self_attn_stop // 4 + 1
cross_attn_start = cross_attn_start // 4 #+ 1
cross_attn_stop = cross_attn_stop // 4 + 1
max_stop = max(self_attn_stop, cross_attn_stop)
temporal_self_mask = torch.zeros((max_stop, 1, 1))
temporal_cross_mask = torch.zeros((max_stop, 1, 1))
temporal_self_mask [ self_attn_start: self_attn_stop,...] = 1.0
temporal_cross_mask[cross_attn_start:cross_attn_stop,...] = 1.0
temporal_attn_masks = torch.stack([temporal_cross_mask, temporal_self_mask])
return (temporal_attn_masks,)
class TemporalCrossAttnMask:
@classmethod
def INPUT_TYPES(cls):
return {"required":
{
"cross_attn_start": ("INT", {"default": 1, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
"cross_attn_stop": ("INT", {"default": 33, "min": 1, "step": 4, "max": 0xffffffffffffffff}),
},
"optional":
{
}
}
RETURN_TYPES = ("MASK",)
RETURN_NAMES = ("temporal_mask",)
FUNCTION = "main"
CATEGORY = "RES4LYF/masks"
def main(self,
cross_attn_start = 0,
cross_attn_stop = 33,
):
cross_attn_start = cross_attn_start // 4 #+ 1
cross_attn_stop = cross_attn_stop // 4 + 1
temporal_self_mask = torch.zeros((cross_attn_stop, 1, 1)) # dummy to satisfy stack
temporal_cross_mask = torch.zeros((cross_attn_stop, 1, 1))
temporal_cross_mask[cross_attn_start:cross_attn_stop,...] = 1.0
temporal_attn_masks = torch.stack([temporal_cross_mask, temporal_self_mask])
return (temporal_attn_masks,)
@dataclass
class RegionalParameters:
weights : List[float] = field(default_factory=list)
floors : List[float] = field(default_factory=list)
REG_MASK_TYPE_2 = [
"gradient",
"gradient_masked",
"gradient_unmasked",
"boolean",
"boolean_masked",
"boolean_unmasked",
]
REG_MASK_TYPE_3 = [
"gradient",
"gradient_A",
"gradient_B",
"gradient_unmasked",
"gradient_AB",
"gradient_A,unmasked",