Spaces:
Paused
Paused
Fabrice-TIERCELIN
commited on
Commit
•
0051b62
1
Parent(s):
99f420c
Fix runtime
Browse files- sgm/modules/encoders/modules.py +1064 -1062
sgm/modules/encoders/modules.py
CHANGED
@@ -1,1062 +1,1064 @@
|
|
1 |
-
from contextlib import nullcontext
|
2 |
-
from functools import partial
|
3 |
-
from typing import Dict, List, Optional, Tuple, Union
|
4 |
-
|
5 |
-
import kornia
|
6 |
-
import numpy as np
|
7 |
-
import open_clip
|
8 |
-
import torch
|
9 |
-
import torch.nn as nn
|
10 |
-
from einops import rearrange, repeat
|
11 |
-
from omegaconf import ListConfig
|
12 |
-
from torch.utils.checkpoint import checkpoint
|
13 |
-
from transformers import (
|
14 |
-
ByT5Tokenizer,
|
15 |
-
CLIPTextModel,
|
16 |
-
CLIPTokenizer,
|
17 |
-
T5EncoderModel,
|
18 |
-
T5Tokenizer,
|
19 |
-
)
|
20 |
-
|
21 |
-
from ...modules.autoencoding.regularizers import DiagonalGaussianRegularizer
|
22 |
-
from ...modules.diffusionmodules.model import Encoder
|
23 |
-
from ...modules.diffusionmodules.openaimodel import Timestep
|
24 |
-
from ...modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule
|
25 |
-
from ...modules.distributions.distributions import DiagonalGaussianDistribution
|
26 |
-
from ...util import (
|
27 |
-
autocast,
|
28 |
-
count_params,
|
29 |
-
default,
|
30 |
-
disabled_train,
|
31 |
-
expand_dims_like,
|
32 |
-
instantiate_from_config,
|
33 |
-
)
|
34 |
-
|
35 |
-
from CKPT_PTH import SDXL_CLIP1_PATH, SDXL_CLIP2_CKPT_PTH
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
self.
|
42 |
-
self.
|
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 |
-
embedder.
|
94 |
-
embedder.
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
f"
|
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 |
-
embedder.ucg_rate
|
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 |
-
self.
|
333 |
-
self.
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
uc =
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
self.
|
371 |
-
self.
|
372 |
-
self.
|
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 |
-
self.
|
414 |
-
self.
|
415 |
-
self.
|
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 |
-
self.
|
464 |
-
self.
|
465 |
-
self.
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
self.
|
470 |
-
self.
|
471 |
-
|
472 |
-
|
473 |
-
assert
|
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 |
-
self.
|
539 |
-
|
540 |
-
self.
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
self.layer_idx =
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
if self.return_pooled:
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
x =
|
572 |
-
x =
|
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 |
-
if (
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
x = r
|
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 |
-
self.
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
self.layer_idx =
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
x =
|
662 |
-
x =
|
663 |
-
x = x.permute(1, 0, 2) #
|
664 |
-
x = self.model.
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
if (
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
x = r
|
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 |
-
self.
|
713 |
-
self.
|
714 |
-
self.
|
715 |
-
self.
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
self.
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
self.
|
730 |
-
self.
|
731 |
-
self.
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
x =
|
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 |
-
if self.
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
z_ = z
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
z.shape[
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
if
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
815 |
-
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
x
|
822 |
-
|
823 |
-
x = (
|
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 |
-
self.
|
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 |
-
x =
|
926 |
-
|
927 |
-
|
928 |
-
|
929 |
-
|
930 |
-
|
931 |
-
|
932 |
-
|
933 |
-
|
934 |
-
|
935 |
-
|
936 |
-
|
937 |
-
|
938 |
-
|
939 |
-
|
940 |
-
|
941 |
-
|
942 |
-
|
943 |
-
|
944 |
-
|
945 |
-
|
946 |
-
self.
|
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 |
-
self.
|
975 |
-
|
976 |
-
|
977 |
-
|
978 |
-
|
979 |
-
|
980 |
-
|
981 |
-
|
982 |
-
|
983 |
-
self.register_buffer("
|
984 |
-
|
985 |
-
|
986 |
-
|
987 |
-
|
988 |
-
|
989 |
-
|
990 |
-
|
991 |
-
|
992 |
-
|
993 |
-
|
994 |
-
|
995 |
-
|
996 |
-
|
997 |
-
|
998 |
-
|
999 |
-
|
1000 |
-
|
1001 |
-
|
1002 |
-
|
1003 |
-
|
1004 |
-
|
1005 |
-
*
|
1006 |
-
|
1007 |
-
|
1008 |
-
|
1009 |
-
|
1010 |
-
|
1011 |
-
|
1012 |
-
|
1013 |
-
|
1014 |
-
|
1015 |
-
|
1016 |
-
|
1017 |
-
|
1018 |
-
|
1019 |
-
|
1020 |
-
|
1021 |
-
|
1022 |
-
|
1023 |
-
|
1024 |
-
|
1025 |
-
|
1026 |
-
|
1027 |
-
|
1028 |
-
|
1029 |
-
|
1030 |
-
|
1031 |
-
|
1032 |
-
|
1033 |
-
|
1034 |
-
|
1035 |
-
|
1036 |
-
|
1037 |
-
|
1038 |
-
|
1039 |
-
|
1040 |
-
|
1041 |
-
|
1042 |
-
|
1043 |
-
|
1044 |
-
|
1045 |
-
|
1046 |
-
|
1047 |
-
|
1048 |
-
|
1049 |
-
|
1050 |
-
|
1051 |
-
|
1052 |
-
|
1053 |
-
self.
|
1054 |
-
|
1055 |
-
|
1056 |
-
|
1057 |
-
|
1058 |
-
|
1059 |
-
log
|
1060 |
-
|
1061 |
-
|
1062 |
-
|
|
|
|
|
|
1 |
+
from contextlib import nullcontext
|
2 |
+
from functools import partial
|
3 |
+
from typing import Dict, List, Optional, Tuple, Union
|
4 |
+
|
5 |
+
import kornia
|
6 |
+
import numpy as np
|
7 |
+
import open_clip
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
from einops import rearrange, repeat
|
11 |
+
from omegaconf import ListConfig
|
12 |
+
from torch.utils.checkpoint import checkpoint
|
13 |
+
from transformers import (
|
14 |
+
ByT5Tokenizer,
|
15 |
+
CLIPTextModel,
|
16 |
+
CLIPTokenizer,
|
17 |
+
T5EncoderModel,
|
18 |
+
T5Tokenizer,
|
19 |
+
)
|
20 |
+
|
21 |
+
from ...modules.autoencoding.regularizers import DiagonalGaussianRegularizer
|
22 |
+
from ...modules.diffusionmodules.model import Encoder
|
23 |
+
from ...modules.diffusionmodules.openaimodel import Timestep
|
24 |
+
from ...modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule
|
25 |
+
from ...modules.distributions.distributions import DiagonalGaussianDistribution
|
26 |
+
from ...util import (
|
27 |
+
autocast,
|
28 |
+
count_params,
|
29 |
+
default,
|
30 |
+
disabled_train,
|
31 |
+
expand_dims_like,
|
32 |
+
instantiate_from_config,
|
33 |
+
)
|
34 |
+
|
35 |
+
#from CKPT_PTH import SDXL_CLIP1_PATH, SDXL_CLIP2_CKPT_PTH
|
36 |
+
from CKPT_PTH import SDXL_CLIP1_PATH
|
37 |
+
|
38 |
+
class AbstractEmbModel(nn.Module):
|
39 |
+
def __init__(self):
|
40 |
+
super().__init__()
|
41 |
+
self._is_trainable = None
|
42 |
+
self._ucg_rate = None
|
43 |
+
self._input_key = None
|
44 |
+
|
45 |
+
@property
|
46 |
+
def is_trainable(self) -> bool:
|
47 |
+
return self._is_trainable
|
48 |
+
|
49 |
+
@property
|
50 |
+
def ucg_rate(self) -> Union[float, torch.Tensor]:
|
51 |
+
return self._ucg_rate
|
52 |
+
|
53 |
+
@property
|
54 |
+
def input_key(self) -> str:
|
55 |
+
return self._input_key
|
56 |
+
|
57 |
+
@is_trainable.setter
|
58 |
+
def is_trainable(self, value: bool):
|
59 |
+
self._is_trainable = value
|
60 |
+
|
61 |
+
@ucg_rate.setter
|
62 |
+
def ucg_rate(self, value: Union[float, torch.Tensor]):
|
63 |
+
self._ucg_rate = value
|
64 |
+
|
65 |
+
@input_key.setter
|
66 |
+
def input_key(self, value: str):
|
67 |
+
self._input_key = value
|
68 |
+
|
69 |
+
@is_trainable.deleter
|
70 |
+
def is_trainable(self):
|
71 |
+
del self._is_trainable
|
72 |
+
|
73 |
+
@ucg_rate.deleter
|
74 |
+
def ucg_rate(self):
|
75 |
+
del self._ucg_rate
|
76 |
+
|
77 |
+
@input_key.deleter
|
78 |
+
def input_key(self):
|
79 |
+
del self._input_key
|
80 |
+
|
81 |
+
|
82 |
+
class GeneralConditioner(nn.Module):
|
83 |
+
OUTPUT_DIM2KEYS = {2: "vector", 3: "crossattn", 4: "concat", 5: "concat"}
|
84 |
+
KEY2CATDIM = {"vector": 1, "crossattn": 2, "concat": 1, 'control_vector': 1}
|
85 |
+
|
86 |
+
def __init__(self, emb_models: Union[List, ListConfig]):
|
87 |
+
super().__init__()
|
88 |
+
embedders = []
|
89 |
+
for n, embconfig in enumerate(emb_models):
|
90 |
+
embedder = instantiate_from_config(embconfig)
|
91 |
+
assert isinstance(
|
92 |
+
embedder, AbstractEmbModel
|
93 |
+
), f"embedder model {embedder.__class__.__name__} has to inherit from AbstractEmbModel"
|
94 |
+
embedder.is_trainable = embconfig.get("is_trainable", False)
|
95 |
+
embedder.ucg_rate = embconfig.get("ucg_rate", 0.0)
|
96 |
+
if not embedder.is_trainable:
|
97 |
+
embedder.train = disabled_train
|
98 |
+
for param in embedder.parameters():
|
99 |
+
param.requires_grad = False
|
100 |
+
embedder.eval()
|
101 |
+
print(
|
102 |
+
f"Initialized embedder #{n}: {embedder.__class__.__name__} "
|
103 |
+
f"with {count_params(embedder, False)} params. Trainable: {embedder.is_trainable}"
|
104 |
+
)
|
105 |
+
|
106 |
+
if "input_key" in embconfig:
|
107 |
+
embedder.input_key = embconfig["input_key"]
|
108 |
+
elif "input_keys" in embconfig:
|
109 |
+
embedder.input_keys = embconfig["input_keys"]
|
110 |
+
else:
|
111 |
+
raise KeyError(
|
112 |
+
f"need either 'input_key' or 'input_keys' for embedder {embedder.__class__.__name__}"
|
113 |
+
)
|
114 |
+
|
115 |
+
embedder.legacy_ucg_val = embconfig.get("legacy_ucg_value", None)
|
116 |
+
if embedder.legacy_ucg_val is not None:
|
117 |
+
embedder.ucg_prng = np.random.RandomState()
|
118 |
+
|
119 |
+
embedders.append(embedder)
|
120 |
+
self.embedders = nn.ModuleList(embedders)
|
121 |
+
|
122 |
+
def possibly_get_ucg_val(self, embedder: AbstractEmbModel, batch: Dict) -> Dict:
|
123 |
+
assert embedder.legacy_ucg_val is not None
|
124 |
+
p = embedder.ucg_rate
|
125 |
+
val = embedder.legacy_ucg_val
|
126 |
+
for i in range(len(batch[embedder.input_key])):
|
127 |
+
if embedder.ucg_prng.choice(2, p=[1 - p, p]):
|
128 |
+
batch[embedder.input_key][i] = val
|
129 |
+
return batch
|
130 |
+
|
131 |
+
def forward(
|
132 |
+
self, batch: Dict, force_zero_embeddings: Optional[List] = None
|
133 |
+
) -> Dict:
|
134 |
+
output = dict()
|
135 |
+
if force_zero_embeddings is None:
|
136 |
+
force_zero_embeddings = []
|
137 |
+
for embedder in self.embedders:
|
138 |
+
embedding_context = nullcontext if embedder.is_trainable else torch.no_grad
|
139 |
+
with embedding_context():
|
140 |
+
if hasattr(embedder, "input_key") and (embedder.input_key is not None):
|
141 |
+
if embedder.legacy_ucg_val is not None:
|
142 |
+
batch = self.possibly_get_ucg_val(embedder, batch)
|
143 |
+
emb_out = embedder(batch[embedder.input_key])
|
144 |
+
elif hasattr(embedder, "input_keys"):
|
145 |
+
emb_out = embedder(*[batch[k] for k in embedder.input_keys])
|
146 |
+
assert isinstance(
|
147 |
+
emb_out, (torch.Tensor, list, tuple)
|
148 |
+
), f"encoder outputs must be tensors or a sequence, but got {type(emb_out)}"
|
149 |
+
if not isinstance(emb_out, (list, tuple)):
|
150 |
+
emb_out = [emb_out]
|
151 |
+
for emb in emb_out:
|
152 |
+
out_key = self.OUTPUT_DIM2KEYS[emb.dim()]
|
153 |
+
if embedder.ucg_rate > 0.0 and embedder.legacy_ucg_val is None:
|
154 |
+
emb = (
|
155 |
+
expand_dims_like(
|
156 |
+
torch.bernoulli(
|
157 |
+
(1.0 - embedder.ucg_rate)
|
158 |
+
* torch.ones(emb.shape[0], device=emb.device)
|
159 |
+
),
|
160 |
+
emb,
|
161 |
+
)
|
162 |
+
* emb
|
163 |
+
)
|
164 |
+
if (
|
165 |
+
hasattr(embedder, "input_key")
|
166 |
+
and embedder.input_key in force_zero_embeddings
|
167 |
+
):
|
168 |
+
emb = torch.zeros_like(emb)
|
169 |
+
if out_key in output:
|
170 |
+
output[out_key] = torch.cat(
|
171 |
+
(output[out_key], emb), self.KEY2CATDIM[out_key]
|
172 |
+
)
|
173 |
+
else:
|
174 |
+
output[out_key] = emb
|
175 |
+
return output
|
176 |
+
|
177 |
+
def get_unconditional_conditioning(
|
178 |
+
self, batch_c, batch_uc=None, force_uc_zero_embeddings=None
|
179 |
+
):
|
180 |
+
if force_uc_zero_embeddings is None:
|
181 |
+
force_uc_zero_embeddings = []
|
182 |
+
ucg_rates = list()
|
183 |
+
for embedder in self.embedders:
|
184 |
+
ucg_rates.append(embedder.ucg_rate)
|
185 |
+
embedder.ucg_rate = 0.0
|
186 |
+
c = self(batch_c)
|
187 |
+
uc = self(batch_c if batch_uc is None else batch_uc, force_uc_zero_embeddings)
|
188 |
+
|
189 |
+
for embedder, rate in zip(self.embedders, ucg_rates):
|
190 |
+
embedder.ucg_rate = rate
|
191 |
+
return c, uc
|
192 |
+
|
193 |
+
|
194 |
+
class GeneralConditionerWithControl(GeneralConditioner):
|
195 |
+
def forward(
|
196 |
+
self, batch: Dict, force_zero_embeddings: Optional[List] = None
|
197 |
+
) -> Dict:
|
198 |
+
output = dict()
|
199 |
+
if force_zero_embeddings is None:
|
200 |
+
force_zero_embeddings = []
|
201 |
+
for embedder in self.embedders:
|
202 |
+
embedding_context = nullcontext if embedder.is_trainable else torch.no_grad
|
203 |
+
with embedding_context():
|
204 |
+
if hasattr(embedder, "input_key") and (embedder.input_key is not None):
|
205 |
+
if embedder.legacy_ucg_val is not None:
|
206 |
+
batch = self.possibly_get_ucg_val(embedder, batch)
|
207 |
+
emb_out = embedder(batch[embedder.input_key])
|
208 |
+
elif hasattr(embedder, "input_keys"):
|
209 |
+
emb_out = embedder(*[batch[k] for k in embedder.input_keys])
|
210 |
+
assert isinstance(
|
211 |
+
emb_out, (torch.Tensor, list, tuple)
|
212 |
+
), f"encoder outputs must be tensors or a sequence, but got {type(emb_out)}"
|
213 |
+
if not isinstance(emb_out, (list, tuple)):
|
214 |
+
emb_out = [emb_out]
|
215 |
+
for emb in emb_out:
|
216 |
+
if 'control_vector' in embedder.input_key:
|
217 |
+
out_key = 'control_vector'
|
218 |
+
else:
|
219 |
+
out_key = self.OUTPUT_DIM2KEYS[emb.dim()]
|
220 |
+
if embedder.ucg_rate > 0.0 and embedder.legacy_ucg_val is None:
|
221 |
+
emb = (
|
222 |
+
expand_dims_like(
|
223 |
+
torch.bernoulli(
|
224 |
+
(1.0 - embedder.ucg_rate)
|
225 |
+
* torch.ones(emb.shape[0], device=emb.device)
|
226 |
+
),
|
227 |
+
emb,
|
228 |
+
)
|
229 |
+
* emb
|
230 |
+
)
|
231 |
+
if (
|
232 |
+
hasattr(embedder, "input_key")
|
233 |
+
and embedder.input_key in force_zero_embeddings
|
234 |
+
):
|
235 |
+
emb = torch.zeros_like(emb)
|
236 |
+
if out_key in output:
|
237 |
+
output[out_key] = torch.cat(
|
238 |
+
(output[out_key], emb), self.KEY2CATDIM[out_key]
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
output[out_key] = emb
|
242 |
+
|
243 |
+
output["control"] = batch["control"]
|
244 |
+
return output
|
245 |
+
|
246 |
+
|
247 |
+
class PreparedConditioner(nn.Module):
|
248 |
+
def __init__(self, cond_pth, un_cond_pth=None):
|
249 |
+
super().__init__()
|
250 |
+
conditions = torch.load(cond_pth)
|
251 |
+
for k, v in conditions.items():
|
252 |
+
self.register_buffer(k, v)
|
253 |
+
self.un_cond_pth = un_cond_pth
|
254 |
+
if un_cond_pth is not None:
|
255 |
+
un_conditions = torch.load(un_cond_pth)
|
256 |
+
for k, v in un_conditions.items():
|
257 |
+
self.register_buffer(k+'_uc', v)
|
258 |
+
|
259 |
+
|
260 |
+
@torch.no_grad()
|
261 |
+
def forward(
|
262 |
+
self, batch: Dict, return_uc=False
|
263 |
+
) -> Dict:
|
264 |
+
output = dict()
|
265 |
+
for k, v in self.state_dict().items():
|
266 |
+
if not return_uc:
|
267 |
+
if k.endswith("_uc"):
|
268 |
+
continue
|
269 |
+
else:
|
270 |
+
output[k] = v.detach().clone().repeat(batch['control'].shape[0], *[1 for _ in range(v.ndim - 1)])
|
271 |
+
else:
|
272 |
+
if k.endswith("_uc"):
|
273 |
+
output[k[:-3]] = v.detach().clone().repeat(batch['control'].shape[0], *[1 for _ in range(v.ndim - 1)])
|
274 |
+
else:
|
275 |
+
continue
|
276 |
+
output["control"] = batch["control"]
|
277 |
+
|
278 |
+
for k, v in output.items():
|
279 |
+
if isinstance(v, torch.Tensor):
|
280 |
+
assert (torch.isnan(v).any()) is not None
|
281 |
+
return output
|
282 |
+
|
283 |
+
def get_unconditional_conditioning(
|
284 |
+
self, batch_c, batch_uc=None, force_uc_zero_embeddings=None
|
285 |
+
):
|
286 |
+
c = self(batch_c)
|
287 |
+
if self.un_cond_pth is not None:
|
288 |
+
uc = self(batch_c, return_uc=True)
|
289 |
+
else:
|
290 |
+
uc = None
|
291 |
+
return c, uc
|
292 |
+
|
293 |
+
|
294 |
+
|
295 |
+
class InceptionV3(nn.Module):
|
296 |
+
"""Wrapper around the https://github.com/mseitzer/pytorch-fid inception
|
297 |
+
port with an additional squeeze at the end"""
|
298 |
+
|
299 |
+
def __init__(self, normalize_input=False, **kwargs):
|
300 |
+
super().__init__()
|
301 |
+
from pytorch_fid import inception
|
302 |
+
|
303 |
+
kwargs["resize_input"] = True
|
304 |
+
self.model = inception.InceptionV3(normalize_input=normalize_input, **kwargs)
|
305 |
+
|
306 |
+
def forward(self, inp):
|
307 |
+
# inp = kornia.geometry.resize(inp, (299, 299),
|
308 |
+
# interpolation='bicubic',
|
309 |
+
# align_corners=False,
|
310 |
+
# antialias=True)
|
311 |
+
# inp = inp.clamp(min=-1, max=1)
|
312 |
+
|
313 |
+
outp = self.model(inp)
|
314 |
+
|
315 |
+
if len(outp) == 1:
|
316 |
+
return outp[0].squeeze()
|
317 |
+
|
318 |
+
return outp
|
319 |
+
|
320 |
+
|
321 |
+
class IdentityEncoder(AbstractEmbModel):
|
322 |
+
def encode(self, x):
|
323 |
+
return x
|
324 |
+
|
325 |
+
def forward(self, x):
|
326 |
+
return x
|
327 |
+
|
328 |
+
|
329 |
+
class ClassEmbedder(AbstractEmbModel):
|
330 |
+
def __init__(self, embed_dim, n_classes=1000, add_sequence_dim=False):
|
331 |
+
super().__init__()
|
332 |
+
self.embedding = nn.Embedding(n_classes, embed_dim)
|
333 |
+
self.n_classes = n_classes
|
334 |
+
self.add_sequence_dim = add_sequence_dim
|
335 |
+
|
336 |
+
def forward(self, c):
|
337 |
+
c = self.embedding(c)
|
338 |
+
if self.add_sequence_dim:
|
339 |
+
c = c[:, None, :]
|
340 |
+
return c
|
341 |
+
|
342 |
+
def get_unconditional_conditioning(self, bs, device="cuda"):
|
343 |
+
uc_class = (
|
344 |
+
self.n_classes - 1
|
345 |
+
) # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
|
346 |
+
uc = torch.ones((bs,), device=device) * uc_class
|
347 |
+
uc = {self.key: uc.long()}
|
348 |
+
return uc
|
349 |
+
|
350 |
+
|
351 |
+
class ClassEmbedderForMultiCond(ClassEmbedder):
|
352 |
+
def forward(self, batch, key=None, disable_dropout=False):
|
353 |
+
out = batch
|
354 |
+
key = default(key, self.key)
|
355 |
+
islist = isinstance(batch[key], list)
|
356 |
+
if islist:
|
357 |
+
batch[key] = batch[key][0]
|
358 |
+
c_out = super().forward(batch, key, disable_dropout)
|
359 |
+
out[key] = [c_out] if islist else c_out
|
360 |
+
return out
|
361 |
+
|
362 |
+
|
363 |
+
class FrozenT5Embedder(AbstractEmbModel):
|
364 |
+
"""Uses the T5 transformer encoder for text"""
|
365 |
+
|
366 |
+
def __init__(
|
367 |
+
self, version="google/t5-v1_1-xxl", device="cuda", max_length=77, freeze=True
|
368 |
+
): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
|
369 |
+
super().__init__()
|
370 |
+
self.tokenizer = T5Tokenizer.from_pretrained(version)
|
371 |
+
self.transformer = T5EncoderModel.from_pretrained(version)
|
372 |
+
self.device = device
|
373 |
+
self.max_length = max_length
|
374 |
+
if freeze:
|
375 |
+
self.freeze()
|
376 |
+
|
377 |
+
def freeze(self):
|
378 |
+
self.transformer = self.transformer.eval()
|
379 |
+
|
380 |
+
for param in self.parameters():
|
381 |
+
param.requires_grad = False
|
382 |
+
|
383 |
+
# @autocast
|
384 |
+
def forward(self, text):
|
385 |
+
batch_encoding = self.tokenizer(
|
386 |
+
text,
|
387 |
+
truncation=True,
|
388 |
+
max_length=self.max_length,
|
389 |
+
return_length=True,
|
390 |
+
return_overflowing_tokens=False,
|
391 |
+
padding="max_length",
|
392 |
+
return_tensors="pt",
|
393 |
+
)
|
394 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
395 |
+
with torch.autocast("cuda", enabled=False):
|
396 |
+
outputs = self.transformer(input_ids=tokens)
|
397 |
+
z = outputs.last_hidden_state
|
398 |
+
return z
|
399 |
+
|
400 |
+
def encode(self, text):
|
401 |
+
return self(text)
|
402 |
+
|
403 |
+
|
404 |
+
class FrozenByT5Embedder(AbstractEmbModel):
|
405 |
+
"""
|
406 |
+
Uses the ByT5 transformer encoder for text. Is character-aware.
|
407 |
+
"""
|
408 |
+
|
409 |
+
def __init__(
|
410 |
+
self, version="google/byt5-base", device="cuda", max_length=77, freeze=True
|
411 |
+
): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
|
412 |
+
super().__init__()
|
413 |
+
self.tokenizer = ByT5Tokenizer.from_pretrained(version)
|
414 |
+
self.transformer = T5EncoderModel.from_pretrained(version)
|
415 |
+
self.device = device
|
416 |
+
self.max_length = max_length
|
417 |
+
if freeze:
|
418 |
+
self.freeze()
|
419 |
+
|
420 |
+
def freeze(self):
|
421 |
+
self.transformer = self.transformer.eval()
|
422 |
+
|
423 |
+
for param in self.parameters():
|
424 |
+
param.requires_grad = False
|
425 |
+
|
426 |
+
def forward(self, text):
|
427 |
+
batch_encoding = self.tokenizer(
|
428 |
+
text,
|
429 |
+
truncation=True,
|
430 |
+
max_length=self.max_length,
|
431 |
+
return_length=True,
|
432 |
+
return_overflowing_tokens=False,
|
433 |
+
padding="max_length",
|
434 |
+
return_tensors="pt",
|
435 |
+
)
|
436 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
437 |
+
with torch.autocast("cuda", enabled=False):
|
438 |
+
outputs = self.transformer(input_ids=tokens)
|
439 |
+
z = outputs.last_hidden_state
|
440 |
+
return z
|
441 |
+
|
442 |
+
def encode(self, text):
|
443 |
+
return self(text)
|
444 |
+
|
445 |
+
|
446 |
+
class FrozenCLIPEmbedder(AbstractEmbModel):
|
447 |
+
"""Uses the CLIP transformer encoder for text (from huggingface)"""
|
448 |
+
|
449 |
+
LAYERS = ["last", "pooled", "hidden"]
|
450 |
+
|
451 |
+
def __init__(
|
452 |
+
self,
|
453 |
+
version="openai/clip-vit-large-patch14",
|
454 |
+
device="cuda",
|
455 |
+
max_length=77,
|
456 |
+
freeze=True,
|
457 |
+
layer="last",
|
458 |
+
layer_idx=None,
|
459 |
+
always_return_pooled=False,
|
460 |
+
): # clip-vit-base-patch32
|
461 |
+
super().__init__()
|
462 |
+
assert layer in self.LAYERS
|
463 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(version if SDXL_CLIP1_PATH is None else SDXL_CLIP1_PATH)
|
464 |
+
self.transformer = CLIPTextModel.from_pretrained(version if SDXL_CLIP1_PATH is None else SDXL_CLIP1_PATH)
|
465 |
+
self.device = device
|
466 |
+
self.max_length = max_length
|
467 |
+
if freeze:
|
468 |
+
self.freeze()
|
469 |
+
self.layer = layer
|
470 |
+
self.layer_idx = layer_idx
|
471 |
+
self.return_pooled = always_return_pooled
|
472 |
+
if layer == "hidden":
|
473 |
+
assert layer_idx is not None
|
474 |
+
assert 0 <= abs(layer_idx) <= 12
|
475 |
+
|
476 |
+
def freeze(self):
|
477 |
+
self.transformer = self.transformer.eval()
|
478 |
+
|
479 |
+
for param in self.parameters():
|
480 |
+
param.requires_grad = False
|
481 |
+
|
482 |
+
@autocast
|
483 |
+
def forward(self, text):
|
484 |
+
batch_encoding = self.tokenizer(
|
485 |
+
text,
|
486 |
+
truncation=True,
|
487 |
+
max_length=self.max_length,
|
488 |
+
return_length=True,
|
489 |
+
return_overflowing_tokens=False,
|
490 |
+
padding="max_length",
|
491 |
+
return_tensors="pt",
|
492 |
+
)
|
493 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
494 |
+
outputs = self.transformer(
|
495 |
+
input_ids=tokens, output_hidden_states=self.layer == "hidden"
|
496 |
+
)
|
497 |
+
if self.layer == "last":
|
498 |
+
z = outputs.last_hidden_state
|
499 |
+
elif self.layer == "pooled":
|
500 |
+
z = outputs.pooler_output[:, None, :]
|
501 |
+
else:
|
502 |
+
z = outputs.hidden_states[self.layer_idx]
|
503 |
+
if self.return_pooled:
|
504 |
+
return z, outputs.pooler_output
|
505 |
+
return z
|
506 |
+
|
507 |
+
def encode(self, text):
|
508 |
+
return self(text)
|
509 |
+
|
510 |
+
|
511 |
+
class FrozenOpenCLIPEmbedder2(AbstractEmbModel):
|
512 |
+
"""
|
513 |
+
Uses the OpenCLIP transformer encoder for text
|
514 |
+
"""
|
515 |
+
|
516 |
+
LAYERS = ["pooled", "last", "penultimate"]
|
517 |
+
|
518 |
+
def __init__(
|
519 |
+
self,
|
520 |
+
arch="ViT-H-14",
|
521 |
+
version="laion2b_s32b_b79k",
|
522 |
+
device="cuda",
|
523 |
+
max_length=77,
|
524 |
+
freeze=True,
|
525 |
+
layer="last",
|
526 |
+
always_return_pooled=False,
|
527 |
+
legacy=True,
|
528 |
+
):
|
529 |
+
super().__init__()
|
530 |
+
assert layer in self.LAYERS
|
531 |
+
model, _, _ = open_clip.create_model_and_transforms(
|
532 |
+
arch,
|
533 |
+
device=torch.device("cpu"),
|
534 |
+
#pretrained=version if SDXL_CLIP2_CKPT_PTH is None else SDXL_CLIP2_CKPT_PTH,
|
535 |
+
pretrained=version,
|
536 |
+
)
|
537 |
+
del model.visual
|
538 |
+
self.model = model
|
539 |
+
|
540 |
+
self.device = device
|
541 |
+
self.max_length = max_length
|
542 |
+
self.return_pooled = always_return_pooled
|
543 |
+
if freeze:
|
544 |
+
self.freeze()
|
545 |
+
self.layer = layer
|
546 |
+
if self.layer == "last":
|
547 |
+
self.layer_idx = 0
|
548 |
+
elif self.layer == "penultimate":
|
549 |
+
self.layer_idx = 1
|
550 |
+
else:
|
551 |
+
raise NotImplementedError()
|
552 |
+
self.legacy = legacy
|
553 |
+
|
554 |
+
def freeze(self):
|
555 |
+
self.model = self.model.eval()
|
556 |
+
for param in self.parameters():
|
557 |
+
param.requires_grad = False
|
558 |
+
|
559 |
+
@autocast
|
560 |
+
def forward(self, text):
|
561 |
+
tokens = open_clip.tokenize(text)
|
562 |
+
z = self.encode_with_transformer(tokens.to(self.device))
|
563 |
+
if not self.return_pooled and self.legacy:
|
564 |
+
return z
|
565 |
+
if self.return_pooled:
|
566 |
+
assert not self.legacy
|
567 |
+
return z[self.layer], z["pooled"]
|
568 |
+
return z[self.layer]
|
569 |
+
|
570 |
+
def encode_with_transformer(self, text):
|
571 |
+
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
|
572 |
+
x = x + self.model.positional_embedding
|
573 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
574 |
+
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
|
575 |
+
if self.legacy:
|
576 |
+
x = x[self.layer]
|
577 |
+
x = self.model.ln_final(x)
|
578 |
+
return x
|
579 |
+
else:
|
580 |
+
# x is a dict and will stay a dict
|
581 |
+
o = x["last"]
|
582 |
+
o = self.model.ln_final(o)
|
583 |
+
pooled = self.pool(o, text)
|
584 |
+
x["pooled"] = pooled
|
585 |
+
return x
|
586 |
+
|
587 |
+
def pool(self, x, text):
|
588 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
589 |
+
x = (
|
590 |
+
x[torch.arange(x.shape[0]), text.argmax(dim=-1)]
|
591 |
+
@ self.model.text_projection
|
592 |
+
)
|
593 |
+
return x
|
594 |
+
|
595 |
+
def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
|
596 |
+
outputs = {}
|
597 |
+
for i, r in enumerate(self.model.transformer.resblocks):
|
598 |
+
if i == len(self.model.transformer.resblocks) - 1:
|
599 |
+
outputs["penultimate"] = x.permute(1, 0, 2) # LND -> NLD
|
600 |
+
if (
|
601 |
+
self.model.transformer.grad_checkpointing
|
602 |
+
and not torch.jit.is_scripting()
|
603 |
+
):
|
604 |
+
x = checkpoint(r, x, attn_mask)
|
605 |
+
else:
|
606 |
+
x = r(x, attn_mask=attn_mask)
|
607 |
+
outputs["last"] = x.permute(1, 0, 2) # LND -> NLD
|
608 |
+
return outputs
|
609 |
+
|
610 |
+
def encode(self, text):
|
611 |
+
return self(text)
|
612 |
+
|
613 |
+
|
614 |
+
class FrozenOpenCLIPEmbedder(AbstractEmbModel):
|
615 |
+
LAYERS = [
|
616 |
+
# "pooled",
|
617 |
+
"last",
|
618 |
+
"penultimate",
|
619 |
+
]
|
620 |
+
|
621 |
+
def __init__(
|
622 |
+
self,
|
623 |
+
arch="ViT-H-14",
|
624 |
+
version="laion2b_s32b_b79k",
|
625 |
+
device="cuda",
|
626 |
+
max_length=77,
|
627 |
+
freeze=True,
|
628 |
+
layer="last",
|
629 |
+
):
|
630 |
+
super().__init__()
|
631 |
+
assert layer in self.LAYERS
|
632 |
+
model, _, _ = open_clip.create_model_and_transforms(
|
633 |
+
arch, device=torch.device("cpu"), pretrained=version
|
634 |
+
)
|
635 |
+
del model.visual
|
636 |
+
self.model = model
|
637 |
+
|
638 |
+
self.device = device
|
639 |
+
self.max_length = max_length
|
640 |
+
if freeze:
|
641 |
+
self.freeze()
|
642 |
+
self.layer = layer
|
643 |
+
if self.layer == "last":
|
644 |
+
self.layer_idx = 0
|
645 |
+
elif self.layer == "penultimate":
|
646 |
+
self.layer_idx = 1
|
647 |
+
else:
|
648 |
+
raise NotImplementedError()
|
649 |
+
|
650 |
+
def freeze(self):
|
651 |
+
self.model = self.model.eval()
|
652 |
+
for param in self.parameters():
|
653 |
+
param.requires_grad = False
|
654 |
+
|
655 |
+
def forward(self, text):
|
656 |
+
tokens = open_clip.tokenize(text)
|
657 |
+
z = self.encode_with_transformer(tokens.to(self.device))
|
658 |
+
return z
|
659 |
+
|
660 |
+
def encode_with_transformer(self, text):
|
661 |
+
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
|
662 |
+
x = x + self.model.positional_embedding
|
663 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
664 |
+
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
|
665 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
666 |
+
x = self.model.ln_final(x)
|
667 |
+
return x
|
668 |
+
|
669 |
+
def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
|
670 |
+
for i, r in enumerate(self.model.transformer.resblocks):
|
671 |
+
if i == len(self.model.transformer.resblocks) - self.layer_idx:
|
672 |
+
break
|
673 |
+
if (
|
674 |
+
self.model.transformer.grad_checkpointing
|
675 |
+
and not torch.jit.is_scripting()
|
676 |
+
):
|
677 |
+
x = checkpoint(r, x, attn_mask)
|
678 |
+
else:
|
679 |
+
x = r(x, attn_mask=attn_mask)
|
680 |
+
return x
|
681 |
+
|
682 |
+
def encode(self, text):
|
683 |
+
return self(text)
|
684 |
+
|
685 |
+
|
686 |
+
class FrozenOpenCLIPImageEmbedder(AbstractEmbModel):
|
687 |
+
"""
|
688 |
+
Uses the OpenCLIP vision transformer encoder for images
|
689 |
+
"""
|
690 |
+
|
691 |
+
def __init__(
|
692 |
+
self,
|
693 |
+
arch="ViT-H-14",
|
694 |
+
version="laion2b_s32b_b79k",
|
695 |
+
device="cuda",
|
696 |
+
max_length=77,
|
697 |
+
freeze=True,
|
698 |
+
antialias=True,
|
699 |
+
ucg_rate=0.0,
|
700 |
+
unsqueeze_dim=False,
|
701 |
+
repeat_to_max_len=False,
|
702 |
+
num_image_crops=0,
|
703 |
+
output_tokens=False,
|
704 |
+
):
|
705 |
+
super().__init__()
|
706 |
+
model, _, _ = open_clip.create_model_and_transforms(
|
707 |
+
arch,
|
708 |
+
device=torch.device("cpu"),
|
709 |
+
pretrained=version,
|
710 |
+
)
|
711 |
+
del model.transformer
|
712 |
+
self.model = model
|
713 |
+
self.max_crops = num_image_crops
|
714 |
+
self.pad_to_max_len = self.max_crops > 0
|
715 |
+
self.repeat_to_max_len = repeat_to_max_len and (not self.pad_to_max_len)
|
716 |
+
self.device = device
|
717 |
+
self.max_length = max_length
|
718 |
+
if freeze:
|
719 |
+
self.freeze()
|
720 |
+
|
721 |
+
self.antialias = antialias
|
722 |
+
|
723 |
+
self.register_buffer(
|
724 |
+
"mean", torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False
|
725 |
+
)
|
726 |
+
self.register_buffer(
|
727 |
+
"std", torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False
|
728 |
+
)
|
729 |
+
self.ucg_rate = ucg_rate
|
730 |
+
self.unsqueeze_dim = unsqueeze_dim
|
731 |
+
self.stored_batch = None
|
732 |
+
self.model.visual.output_tokens = output_tokens
|
733 |
+
self.output_tokens = output_tokens
|
734 |
+
|
735 |
+
def preprocess(self, x):
|
736 |
+
# normalize to [0,1]
|
737 |
+
x = kornia.geometry.resize(
|
738 |
+
x,
|
739 |
+
(224, 224),
|
740 |
+
interpolation="bicubic",
|
741 |
+
align_corners=True,
|
742 |
+
antialias=self.antialias,
|
743 |
+
)
|
744 |
+
x = (x + 1.0) / 2.0
|
745 |
+
# renormalize according to clip
|
746 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
747 |
+
return x
|
748 |
+
|
749 |
+
def freeze(self):
|
750 |
+
self.model = self.model.eval()
|
751 |
+
for param in self.parameters():
|
752 |
+
param.requires_grad = False
|
753 |
+
|
754 |
+
@autocast
|
755 |
+
def forward(self, image, no_dropout=False):
|
756 |
+
z = self.encode_with_vision_transformer(image)
|
757 |
+
tokens = None
|
758 |
+
if self.output_tokens:
|
759 |
+
z, tokens = z[0], z[1]
|
760 |
+
z = z.to(image.dtype)
|
761 |
+
if self.ucg_rate > 0.0 and not no_dropout and not (self.max_crops > 0):
|
762 |
+
z = (
|
763 |
+
torch.bernoulli(
|
764 |
+
(1.0 - self.ucg_rate) * torch.ones(z.shape[0], device=z.device)
|
765 |
+
)[:, None]
|
766 |
+
* z
|
767 |
+
)
|
768 |
+
if tokens is not None:
|
769 |
+
tokens = (
|
770 |
+
expand_dims_like(
|
771 |
+
torch.bernoulli(
|
772 |
+
(1.0 - self.ucg_rate)
|
773 |
+
* torch.ones(tokens.shape[0], device=tokens.device)
|
774 |
+
),
|
775 |
+
tokens,
|
776 |
+
)
|
777 |
+
* tokens
|
778 |
+
)
|
779 |
+
if self.unsqueeze_dim:
|
780 |
+
z = z[:, None, :]
|
781 |
+
if self.output_tokens:
|
782 |
+
assert not self.repeat_to_max_len
|
783 |
+
assert not self.pad_to_max_len
|
784 |
+
return tokens, z
|
785 |
+
if self.repeat_to_max_len:
|
786 |
+
if z.dim() == 2:
|
787 |
+
z_ = z[:, None, :]
|
788 |
+
else:
|
789 |
+
z_ = z
|
790 |
+
return repeat(z_, "b 1 d -> b n d", n=self.max_length), z
|
791 |
+
elif self.pad_to_max_len:
|
792 |
+
assert z.dim() == 3
|
793 |
+
z_pad = torch.cat(
|
794 |
+
(
|
795 |
+
z,
|
796 |
+
torch.zeros(
|
797 |
+
z.shape[0],
|
798 |
+
self.max_length - z.shape[1],
|
799 |
+
z.shape[2],
|
800 |
+
device=z.device,
|
801 |
+
),
|
802 |
+
),
|
803 |
+
1,
|
804 |
+
)
|
805 |
+
return z_pad, z_pad[:, 0, ...]
|
806 |
+
return z
|
807 |
+
|
808 |
+
def encode_with_vision_transformer(self, img):
|
809 |
+
# if self.max_crops > 0:
|
810 |
+
# img = self.preprocess_by_cropping(img)
|
811 |
+
if img.dim() == 5:
|
812 |
+
assert self.max_crops == img.shape[1]
|
813 |
+
img = rearrange(img, "b n c h w -> (b n) c h w")
|
814 |
+
img = self.preprocess(img)
|
815 |
+
if not self.output_tokens:
|
816 |
+
assert not self.model.visual.output_tokens
|
817 |
+
x = self.model.visual(img)
|
818 |
+
tokens = None
|
819 |
+
else:
|
820 |
+
assert self.model.visual.output_tokens
|
821 |
+
x, tokens = self.model.visual(img)
|
822 |
+
if self.max_crops > 0:
|
823 |
+
x = rearrange(x, "(b n) d -> b n d", n=self.max_crops)
|
824 |
+
# drop out between 0 and all along the sequence axis
|
825 |
+
x = (
|
826 |
+
torch.bernoulli(
|
827 |
+
(1.0 - self.ucg_rate)
|
828 |
+
* torch.ones(x.shape[0], x.shape[1], 1, device=x.device)
|
829 |
+
)
|
830 |
+
* x
|
831 |
+
)
|
832 |
+
if tokens is not None:
|
833 |
+
tokens = rearrange(tokens, "(b n) t d -> b t (n d)", n=self.max_crops)
|
834 |
+
print(
|
835 |
+
f"You are running very experimental token-concat in {self.__class__.__name__}. "
|
836 |
+
f"Check what you are doing, and then remove this message."
|
837 |
+
)
|
838 |
+
if self.output_tokens:
|
839 |
+
return x, tokens
|
840 |
+
return x
|
841 |
+
|
842 |
+
def encode(self, text):
|
843 |
+
return self(text)
|
844 |
+
|
845 |
+
|
846 |
+
class FrozenCLIPT5Encoder(AbstractEmbModel):
|
847 |
+
def __init__(
|
848 |
+
self,
|
849 |
+
clip_version="openai/clip-vit-large-patch14",
|
850 |
+
t5_version="google/t5-v1_1-xl",
|
851 |
+
device="cuda",
|
852 |
+
clip_max_length=77,
|
853 |
+
t5_max_length=77,
|
854 |
+
):
|
855 |
+
super().__init__()
|
856 |
+
self.clip_encoder = FrozenCLIPEmbedder(
|
857 |
+
clip_version, device, max_length=clip_max_length
|
858 |
+
)
|
859 |
+
self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
|
860 |
+
print(
|
861 |
+
f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder) * 1.e-6:.2f} M parameters, "
|
862 |
+
f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder) * 1.e-6:.2f} M params."
|
863 |
+
)
|
864 |
+
|
865 |
+
def encode(self, text):
|
866 |
+
return self(text)
|
867 |
+
|
868 |
+
def forward(self, text):
|
869 |
+
clip_z = self.clip_encoder.encode(text)
|
870 |
+
t5_z = self.t5_encoder.encode(text)
|
871 |
+
return [clip_z, t5_z]
|
872 |
+
|
873 |
+
|
874 |
+
class SpatialRescaler(nn.Module):
|
875 |
+
def __init__(
|
876 |
+
self,
|
877 |
+
n_stages=1,
|
878 |
+
method="bilinear",
|
879 |
+
multiplier=0.5,
|
880 |
+
in_channels=3,
|
881 |
+
out_channels=None,
|
882 |
+
bias=False,
|
883 |
+
wrap_video=False,
|
884 |
+
kernel_size=1,
|
885 |
+
remap_output=False,
|
886 |
+
):
|
887 |
+
super().__init__()
|
888 |
+
self.n_stages = n_stages
|
889 |
+
assert self.n_stages >= 0
|
890 |
+
assert method in [
|
891 |
+
"nearest",
|
892 |
+
"linear",
|
893 |
+
"bilinear",
|
894 |
+
"trilinear",
|
895 |
+
"bicubic",
|
896 |
+
"area",
|
897 |
+
]
|
898 |
+
self.multiplier = multiplier
|
899 |
+
self.interpolator = partial(torch.nn.functional.interpolate, mode=method)
|
900 |
+
self.remap_output = out_channels is not None or remap_output
|
901 |
+
if self.remap_output:
|
902 |
+
print(
|
903 |
+
f"Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing."
|
904 |
+
)
|
905 |
+
self.channel_mapper = nn.Conv2d(
|
906 |
+
in_channels,
|
907 |
+
out_channels,
|
908 |
+
kernel_size=kernel_size,
|
909 |
+
bias=bias,
|
910 |
+
padding=kernel_size // 2,
|
911 |
+
)
|
912 |
+
self.wrap_video = wrap_video
|
913 |
+
|
914 |
+
def forward(self, x):
|
915 |
+
if self.wrap_video and x.ndim == 5:
|
916 |
+
B, C, T, H, W = x.shape
|
917 |
+
x = rearrange(x, "b c t h w -> b t c h w")
|
918 |
+
x = rearrange(x, "b t c h w -> (b t) c h w")
|
919 |
+
|
920 |
+
for stage in range(self.n_stages):
|
921 |
+
x = self.interpolator(x, scale_factor=self.multiplier)
|
922 |
+
|
923 |
+
if self.wrap_video:
|
924 |
+
x = rearrange(x, "(b t) c h w -> b t c h w", b=B, t=T, c=C)
|
925 |
+
x = rearrange(x, "b t c h w -> b c t h w")
|
926 |
+
if self.remap_output:
|
927 |
+
x = self.channel_mapper(x)
|
928 |
+
return x
|
929 |
+
|
930 |
+
def encode(self, x):
|
931 |
+
return self(x)
|
932 |
+
|
933 |
+
|
934 |
+
class LowScaleEncoder(nn.Module):
|
935 |
+
def __init__(
|
936 |
+
self,
|
937 |
+
model_config,
|
938 |
+
linear_start,
|
939 |
+
linear_end,
|
940 |
+
timesteps=1000,
|
941 |
+
max_noise_level=250,
|
942 |
+
output_size=64,
|
943 |
+
scale_factor=1.0,
|
944 |
+
):
|
945 |
+
super().__init__()
|
946 |
+
self.max_noise_level = max_noise_level
|
947 |
+
self.model = instantiate_from_config(model_config)
|
948 |
+
self.augmentation_schedule = self.register_schedule(
|
949 |
+
timesteps=timesteps, linear_start=linear_start, linear_end=linear_end
|
950 |
+
)
|
951 |
+
self.out_size = output_size
|
952 |
+
self.scale_factor = scale_factor
|
953 |
+
|
954 |
+
def register_schedule(
|
955 |
+
self,
|
956 |
+
beta_schedule="linear",
|
957 |
+
timesteps=1000,
|
958 |
+
linear_start=1e-4,
|
959 |
+
linear_end=2e-2,
|
960 |
+
cosine_s=8e-3,
|
961 |
+
):
|
962 |
+
betas = make_beta_schedule(
|
963 |
+
beta_schedule,
|
964 |
+
timesteps,
|
965 |
+
linear_start=linear_start,
|
966 |
+
linear_end=linear_end,
|
967 |
+
cosine_s=cosine_s,
|
968 |
+
)
|
969 |
+
alphas = 1.0 - betas
|
970 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
971 |
+
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
|
972 |
+
|
973 |
+
(timesteps,) = betas.shape
|
974 |
+
self.num_timesteps = int(timesteps)
|
975 |
+
self.linear_start = linear_start
|
976 |
+
self.linear_end = linear_end
|
977 |
+
assert (
|
978 |
+
alphas_cumprod.shape[0] == self.num_timesteps
|
979 |
+
), "alphas have to be defined for each timestep"
|
980 |
+
|
981 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
982 |
+
|
983 |
+
self.register_buffer("betas", to_torch(betas))
|
984 |
+
self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod))
|
985 |
+
self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev))
|
986 |
+
|
987 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
988 |
+
self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod)))
|
989 |
+
self.register_buffer(
|
990 |
+
"sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod))
|
991 |
+
)
|
992 |
+
self.register_buffer(
|
993 |
+
"log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod))
|
994 |
+
)
|
995 |
+
self.register_buffer(
|
996 |
+
"sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod))
|
997 |
+
)
|
998 |
+
self.register_buffer(
|
999 |
+
"sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1))
|
1000 |
+
)
|
1001 |
+
|
1002 |
+
def q_sample(self, x_start, t, noise=None):
|
1003 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
1004 |
+
return (
|
1005 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
1006 |
+
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
|
1007 |
+
* noise
|
1008 |
+
)
|
1009 |
+
|
1010 |
+
def forward(self, x):
|
1011 |
+
z = self.model.encode(x)
|
1012 |
+
if isinstance(z, DiagonalGaussianDistribution):
|
1013 |
+
z = z.sample()
|
1014 |
+
z = z * self.scale_factor
|
1015 |
+
noise_level = torch.randint(
|
1016 |
+
0, self.max_noise_level, (x.shape[0],), device=x.device
|
1017 |
+
).long()
|
1018 |
+
z = self.q_sample(z, noise_level)
|
1019 |
+
if self.out_size is not None:
|
1020 |
+
z = torch.nn.functional.interpolate(z, size=self.out_size, mode="nearest")
|
1021 |
+
# z = z.repeat_interleave(2, -2).repeat_interleave(2, -1)
|
1022 |
+
return z, noise_level
|
1023 |
+
|
1024 |
+
def decode(self, z):
|
1025 |
+
z = z / self.scale_factor
|
1026 |
+
return self.model.decode(z)
|
1027 |
+
|
1028 |
+
|
1029 |
+
class ConcatTimestepEmbedderND(AbstractEmbModel):
|
1030 |
+
"""embeds each dimension independently and concatenates them"""
|
1031 |
+
|
1032 |
+
def __init__(self, outdim):
|
1033 |
+
super().__init__()
|
1034 |
+
self.timestep = Timestep(outdim)
|
1035 |
+
self.outdim = outdim
|
1036 |
+
|
1037 |
+
def forward(self, x):
|
1038 |
+
if x.ndim == 1:
|
1039 |
+
x = x[:, None]
|
1040 |
+
assert len(x.shape) == 2
|
1041 |
+
b, dims = x.shape[0], x.shape[1]
|
1042 |
+
x = rearrange(x, "b d -> (b d)")
|
1043 |
+
emb = self.timestep(x)
|
1044 |
+
emb = rearrange(emb, "(b d) d2 -> b (d d2)", b=b, d=dims, d2=self.outdim)
|
1045 |
+
return emb
|
1046 |
+
|
1047 |
+
|
1048 |
+
class GaussianEncoder(Encoder, AbstractEmbModel):
|
1049 |
+
def __init__(
|
1050 |
+
self, weight: float = 1.0, flatten_output: bool = True, *args, **kwargs
|
1051 |
+
):
|
1052 |
+
super().__init__(*args, **kwargs)
|
1053 |
+
self.posterior = DiagonalGaussianRegularizer()
|
1054 |
+
self.weight = weight
|
1055 |
+
self.flatten_output = flatten_output
|
1056 |
+
|
1057 |
+
def forward(self, x) -> Tuple[Dict, torch.Tensor]:
|
1058 |
+
z = super().forward(x)
|
1059 |
+
z, log = self.posterior(z)
|
1060 |
+
log["loss"] = log["kl_loss"]
|
1061 |
+
log["weight"] = self.weight
|
1062 |
+
if self.flatten_output:
|
1063 |
+
z = rearrange(z, "b c h w -> b (h w ) c")
|
1064 |
+
return log, z
|