Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a0da7708e | ||
|
|
a51a53d5b7 | ||
|
|
475f96aede | ||
|
|
977f4a5c3a | ||
|
|
2a45675498 | ||
|
|
1d0516a2a9 | ||
|
|
8002d8a2f9 | ||
|
|
9a588a42ec | ||
|
|
509d6922f5 | ||
|
|
9fa4140159 | ||
|
|
8ce6916d72 | ||
|
|
0d0d28569a | ||
|
|
75109fdb79 | ||
|
|
5eae7087fa | ||
|
|
ea414c54ac | ||
|
|
0013ae0ece | ||
|
|
393fe78ec2 | ||
|
|
0e904e6035 | ||
|
|
5f4020b12d | ||
|
|
5da8a6b169 | ||
|
|
ce6e7b501d | ||
|
|
366f740d28 | ||
|
|
d45fe1ee22 | ||
|
|
da24890d53 | ||
|
|
95391f403d | ||
|
|
9e0b3afe4e | ||
|
|
ba1beba982 | ||
|
|
64c195167b | ||
|
|
cc9bf1e4f5 | ||
|
|
a64f115d35 | ||
|
|
e45f6f2fc4 | ||
|
|
1cd8df5c00 | ||
|
|
d2614a9a49 | ||
|
|
083a8458c4 | ||
|
|
1c2f17e8d7 | ||
|
|
9d45b9f0de | ||
|
|
833c6f50c7 | ||
|
|
d15cf3001f | ||
|
|
eebbcd5ee0 | ||
|
|
2633119505 | ||
|
|
90908df260 | ||
|
|
c80a488f70 | ||
|
|
e69e068b57 | ||
|
|
54c45500b0 | ||
|
|
e560366600 | ||
|
|
f880b321c6 | ||
|
|
51fcbd6b3d | ||
|
|
f583b56878 | ||
|
|
c59e52ca44 | ||
|
|
a0bdf20817 | ||
|
|
8ad7e50f33 | ||
|
|
d504c96174 | ||
|
|
43acf83adb | ||
|
|
fb00932cad | ||
|
|
d74cfc54e8 | ||
|
|
cfa883767f | ||
|
|
88a60d71ab | ||
|
|
b3ad381a65 | ||
|
|
41168b1e82 | ||
|
|
7251c996d2 | ||
|
|
67fcf0ba52 | ||
|
|
aa610cde2b | ||
|
|
6b286552b7 | ||
|
|
2ea824b9ab | ||
|
|
001040abc7 | ||
|
|
746d46e137 | ||
|
|
089329ef2e | ||
|
|
5c1f64197e | ||
|
|
54e938cd70 | ||
|
|
7495db7669 | ||
|
|
4e36aee658 | ||
|
|
56120d633e | ||
|
|
1f0861b649 | ||
|
|
7916f89c33 | ||
|
|
e294f417c0 | ||
|
|
ee011e66e9 | ||
|
|
d7fc563581 | ||
|
|
88defbfdd1 | ||
|
|
74f33df658 | ||
|
|
487c400e8e | ||
|
|
200f6943e3 | ||
|
|
8081e1337c | ||
|
|
9ecb80a58b | ||
|
|
967d15321d | ||
|
|
9cd79d3d4a | ||
|
|
7ecd55e92a | ||
|
|
99c0efdb45 | ||
|
|
a721fe3d0f | ||
|
|
e8ecda7240 | ||
|
|
7d88316bf8 | ||
|
|
6bcbfc54cf | ||
|
|
55463a6290 | ||
|
|
6aa0446706 | ||
|
|
848ceb2beb | ||
|
|
cc06d71ca0 | ||
|
|
e221fdd7ac | ||
|
|
c876108059 | ||
|
|
9cae986648 | ||
|
|
d2ce150490 | ||
|
|
904a019491 | ||
|
|
be02ec93cc | ||
|
|
50483a3b54 | ||
|
|
367c612ddb | ||
|
|
9a88b9e40a | ||
|
|
2fd5bb6ffa | ||
|
|
bb75cddd60 | ||
|
|
3d42bf62ce | ||
|
|
da43a51683 | ||
|
|
139bdf827f | ||
|
|
32eb6b480d | ||
|
|
6c38f8cb24 | ||
|
|
64ed8c4183 | ||
|
|
5a0456ed9e | ||
|
|
e2d8c9bef5 | ||
|
|
f1d1c83713 | ||
|
|
6d2ff33466 | ||
|
|
4c4e7defc2 | ||
|
|
7c09f1e171 | ||
|
|
d6864ec46e | ||
|
|
260c181e0e | ||
|
|
6075807e03 | ||
|
|
76ea2aa6a6 | ||
|
|
1e56fd1114 | ||
|
|
1d94082563 | ||
|
|
dd888f7a8d | ||
|
|
b27c1e5fcd | ||
|
|
269a14f413 | ||
|
|
5c74e5c99a | ||
|
|
a088425268 | ||
|
|
bb23263f78 | ||
|
|
174cba5759 | ||
|
|
c517cfbc17 | ||
|
|
d3010e37ab | ||
|
|
3167e088ed | ||
|
|
d20d271a24 | ||
|
|
05232fb966 | ||
|
|
00a5cb8e5c | ||
|
|
d380c7d219 | ||
|
|
71c8a4961b | ||
|
|
dd7c55f5d2 | ||
|
|
300e8a4786 | ||
|
|
f66c5df07d | ||
|
|
700aae60af | ||
|
|
1ad36cc5f9 | ||
|
|
697fff7442 | ||
|
|
8360666470 | ||
|
|
4b079bdf5a | ||
|
|
1316f57390 | ||
|
|
0730929558 | ||
|
|
1e88104558 | ||
|
|
28ae01e11b | ||
|
|
5d3c4223a8 | ||
|
|
ed167a0135 | ||
|
|
1ba1a1662b | ||
|
|
4f42dbfacf | ||
|
|
9b1ab5b5c7 | ||
|
|
bea3fcad8f | ||
|
|
d79686bc20 | ||
|
|
aefff3796e | ||
|
|
0ed0f54d11 | ||
|
|
4ba6c88ad8 | ||
|
|
358baa2c2a | ||
|
|
cf235c0728 | ||
|
|
ab31158673 | ||
|
|
37365817e8 | ||
|
|
86193e3cc9 | ||
|
|
05474da487 | ||
|
|
cfdae3b49f | ||
|
|
f05865de63 | ||
|
|
840553b261 | ||
|
|
b8c2bb0a93 | ||
|
|
0ba45a1645 | ||
|
|
17e2452d30 | ||
|
|
1c7e32d8af | ||
|
|
95cd0ef690 | ||
|
|
2c4dfaf4c8 | ||
|
|
1ab9803bda | ||
|
|
02583db554 | ||
|
|
7ebdcd4abc | ||
|
|
0ad92fad01 | ||
|
|
2c42ac65e9 | ||
|
|
718946ef13 | ||
|
|
fc3a684b0b | ||
|
|
0482667c78 | ||
|
|
6cb1241d48 | ||
|
|
28387fe37f | ||
|
|
b3ea982f6f | ||
|
|
a6dc8aeb64 | ||
|
|
b9fd93c19e | ||
|
|
a90ee9773f | ||
|
|
1cc8082452 | ||
|
|
0dc8a84564 | ||
|
|
795a74d756 | ||
|
|
14a1f8bd71 | ||
|
|
de4fcd6fb3 | ||
|
|
ca48988742 | ||
|
|
bca7236c73 | ||
|
|
e4627466f5 | ||
|
|
0f1ba64b80 | ||
|
|
7aa9086b48 | ||
|
|
72f5423d6a | ||
|
|
3acfb513ea | ||
|
|
543df461ff | ||
|
|
b2623b3a04 | ||
|
|
de304b10d1 | ||
|
|
623ce5a9fa | ||
|
|
b2c8cf969f | ||
|
|
9d002ddfbc | ||
|
|
b06562823b | ||
|
|
8bc1d6651a | ||
|
|
79583d4be3 | ||
|
|
7eafe77ba0 | ||
|
|
95f3307d5c | ||
|
|
e9672e8d56 | ||
|
|
6d05cc5cf9 | ||
|
|
8f2c1b7824 | ||
|
|
076c4a5c7e | ||
|
|
61c68365d2 | ||
|
|
70f8ac77dd | ||
|
|
7fa6be05b8 | ||
|
|
f6fc9cee6e | ||
|
|
699bad3887 | ||
|
|
d47ac9cbe0 | ||
|
|
1ff6bab5f5 | ||
|
|
538534c749 | ||
|
|
9063b99bd1 | ||
|
|
949647c4d0 | ||
|
|
d50ec8135e | ||
|
|
38fd791a77 | ||
|
|
8ce4432fef | ||
|
|
57586bed1d | ||
|
|
617f89e0f5 | ||
|
|
53d26032dd | ||
|
|
9cefe309e3 | ||
|
|
b9e49af4d1 | ||
|
|
c254ae4235 | ||
|
|
dd36ab46c6 | ||
|
|
7cb46ca8c3 | ||
|
|
e5ef9752a7 | ||
|
|
fe379fa77f | ||
|
|
e5955d8395 | ||
|
|
011c0ce38d | ||
|
|
ae768f53a4 | ||
|
|
bafd5503ac | ||
|
|
edea93286c | ||
|
|
fbf8f169b6 | ||
|
|
0ad2b00cc0 | ||
|
|
9b864b987b | ||
|
|
cbbf44f3bc | ||
|
|
c38da2242d | ||
|
|
d05796ffb3 | ||
|
|
488b6628c7 | ||
|
|
8131eaef23 | ||
|
|
242637db5c | ||
|
|
24ec3f6960 | ||
|
|
02da8fed47 | ||
|
|
7a29bcb18a | ||
|
|
617ce55938 | ||
|
|
e76bf4d899 | ||
|
|
493106b555 | ||
|
|
54391300b1 | ||
|
|
c57ffd8150 | ||
|
|
838e095dbd | ||
|
|
863ea45d23 | ||
|
|
44f9584f16 | ||
|
|
cc3b79ab18 | ||
|
|
cdfa3a8661 | ||
|
|
1492310544 | ||
|
|
0ad24cd7e7 | ||
|
|
c538cd4c8a | ||
|
|
3183589eff | ||
|
|
4cf23a5a40 | ||
|
|
0405dde5a2 | ||
|
|
42054724b7 | ||
|
|
42d7180759 | ||
|
|
82608009c8 | ||
|
|
f9755820de | ||
|
|
56e3366c26 | ||
|
|
43d8a2c8a5 | ||
|
|
d4d942c5ee | ||
|
|
30c2fca799 | ||
|
|
d9038d575f | ||
|
|
b8acd3ee48 | ||
|
|
9f84cd2254 | ||
|
|
b9b46638ac | ||
|
|
b1c8b8a280 | ||
|
|
79395b872c | ||
|
|
cedac626e2 | ||
|
|
4870b8f081 | ||
|
|
81dac31735 | ||
|
|
26a11c3044 | ||
|
|
10d3a0fbef | ||
|
|
40308f1c70 | ||
|
|
df0b8c419a | ||
|
|
45f129b287 | ||
|
|
a7cf6d4ed1 | ||
|
|
7dd0e1ac61 | ||
|
|
f36fa45c29 | ||
|
|
3a290cfd15 | ||
|
|
8f6507fa64 | ||
|
|
1e4cc84a30 | ||
|
|
88cf36936b | ||
|
|
876b5bda5c | ||
|
|
5f7a5d533b | ||
|
|
6a2053c9d1 | ||
|
|
0c8a883a36 | ||
|
|
044ff9f25e | ||
|
|
6978686272 | ||
|
|
740157bd61 | ||
|
|
704cca215b | ||
|
|
999a314652 | ||
|
|
f9be754980 | ||
|
|
a21e4b3210 | ||
|
|
469d9168da | ||
|
|
a053336c1a | ||
|
|
6faa24b7f2 | ||
|
|
a5621b8739 | ||
|
|
5266959a93 | ||
|
|
a37b12235f | ||
|
|
90c3bbb6c2 | ||
|
|
4bc1ffee24 | ||
|
|
56bd2ec5f6 | ||
|
|
a507a5763d | ||
|
|
c89b82e479 | ||
|
|
e241998f53 | ||
|
|
0538f5d600 | ||
|
|
a84d142cb2 | ||
|
|
5d17484cc5 | ||
|
|
636b252c7e | ||
|
|
2a3ca69c83 | ||
|
|
e85e1ff9e6 | ||
|
|
8e65fae3c5 | ||
|
|
96f7f6accd | ||
|
|
3c79851230 | ||
|
|
63d4b6aada | ||
|
|
748ec89aa8 | ||
|
|
a1ca0985ec | ||
|
|
30f185a19b | ||
|
|
4f13aa46d4 | ||
|
|
dfb2a59211 | ||
|
|
5f5f8ae30a | ||
|
|
82d2ab44e5 | ||
|
|
efcef40b00 | ||
|
|
6fce0e2d3b | ||
|
|
665ddd6811 | ||
|
|
e836134b90 | ||
|
|
17f02a91bf | ||
|
|
4d52c10148 | ||
|
|
9c63d8d04f | ||
|
|
288a7e96a9 | ||
|
|
d9def84332 | ||
|
|
42df277488 | ||
|
|
66d4c5b90d | ||
|
|
bc22008b66 | ||
|
|
c65f81d089 | ||
|
|
71c93f87fd | ||
|
|
0c3030a7d8 | ||
|
|
3d9b52cb10 | ||
|
|
61aa0e2ffd | ||
|
|
8a151b5402 | ||
|
|
54f745bb63 | ||
|
|
d39155213e | ||
|
|
9b98413e1e | ||
|
|
11f3e41e9a | ||
|
|
9076a3aae8 | ||
|
|
b7d7f9afe5 | ||
|
|
77d79f6878 | ||
|
|
9a2a13498a | ||
|
|
73cff6ebab | ||
|
|
5f521dc169 | ||
|
|
4eeaf1ea19 | ||
|
|
d0b9f2c907 | ||
|
|
948fdd369d | ||
|
|
b1ceaaeb2e | ||
|
|
bb5503c9bb | ||
|
|
ff1fe75919 | ||
|
|
49951a85b6 | ||
|
|
bfee623d77 | ||
|
|
c2923068e6 | ||
|
|
644f9aeaa3 | ||
|
|
65973b0251 | ||
|
|
2dfaeb0093 | ||
|
|
b4d2290859 | ||
|
|
bd0a634ec0 | ||
|
|
bd5f76a3c8 | ||
|
|
bcdd6dc664 | ||
|
|
fd6404bb2f | ||
|
|
8bd7a6318c | ||
|
|
6d51934ae8 | ||
|
|
ad008d369b | ||
|
|
1edc6ddb32 | ||
|
|
655e6557eb | ||
|
|
70bced06f4 | ||
|
|
68ef3ac468 | ||
|
|
6db2d113ba | ||
|
|
b39d6abc1b | ||
|
|
a0cf985bc3 | ||
|
|
053f26ce82 | ||
|
|
edf2a24519 | ||
|
|
8b4546896e | ||
|
|
a1220f7f36 | ||
|
|
ff779c9171 | ||
|
|
b9f32539fd | ||
|
|
35adf24d97 | ||
|
|
5375a01fb6 | ||
|
|
04a99fd4e2 | ||
|
|
cae24fc7e0 | ||
|
|
4aac86a828 | ||
|
|
39908c9aea | ||
|
|
2a0bd1c42d | ||
|
|
b6d4c172f0 | ||
|
|
d5399e8667 | ||
|
|
345c286c86 | ||
|
|
eec70ff3fb | ||
|
|
c3d75d5e60 | ||
|
|
10e1dd68ea | ||
|
|
4f9ef5b7a9 | ||
|
|
5a8f8730bd | ||
|
|
e2a5fe8b4b | ||
|
|
3cd6a930c3 | ||
|
|
e0eee40bde | ||
|
|
daa638befb | ||
|
|
61ec1ff641 | ||
|
|
f182b976f8 | ||
|
|
0b1fa14ade | ||
|
|
09710f9ca0 | ||
|
|
c16a7b5a7d | ||
|
|
282947d93a | ||
|
|
e4f422cf99 | ||
|
|
aa62d59d9e | ||
|
|
497fafe2ea | ||
|
|
427e7be6c2 | ||
|
|
1d7e0848e0 | ||
|
|
9a7dba06c1 | ||
|
|
be285f5258 | ||
|
|
689797bdb7 | ||
|
|
6181f30b37 | ||
|
|
6f83ca96bc | ||
|
|
1eb4db5ff9 | ||
|
|
b748ed8bdd | ||
|
|
4b4a3b4f8f | ||
|
|
d6ac1842fa | ||
|
|
7fc5ec305d | ||
|
|
e5b0b53265 | ||
|
|
e3ef4dd27b | ||
|
|
8bf010a835 | ||
|
|
0ced709f1b | ||
|
|
9659589d67 | ||
|
|
b60ab34db6 | ||
|
|
9f3a5962e6 | ||
|
|
2df76f3363 | ||
|
|
0beb5a8911 | ||
|
|
c05109ff82 | ||
|
|
3de816004d | ||
|
|
8d487f99b4 | ||
|
|
7d2c0b58e2 | ||
|
|
d6da0f17bb | ||
|
|
656f5b1132 | ||
|
|
8c4f2bb95e | ||
|
|
d6bee68845 | ||
|
|
4641665393 | ||
|
|
2e9e8c03ea | ||
|
|
03458ee955 | ||
|
|
f51c284354 | ||
|
|
f2fd411a7b | ||
|
|
ef8c4aba1d | ||
|
|
5cfc629de5 | ||
|
|
5e7c89bd00 | ||
|
|
994e6e3afb | ||
|
|
0c4426fc2b | ||
|
|
43447dbaf9 | ||
|
|
2f49c7fcdc | ||
|
|
7bf10bc800 | ||
|
|
8d8f388a3c | ||
|
|
e8145f2074 | ||
|
|
24683f1dad | ||
|
|
f3d5f6b3ab | ||
|
|
b29756a962 | ||
|
|
885fc25cb6 | ||
|
|
c9daa36ef7 | ||
|
|
5691ae5314 | ||
|
|
64a0c03673 | ||
|
|
e1c052ff43 | ||
|
|
8db5521463 | ||
|
|
54dbcacd57 | ||
|
|
4805b70d3b | ||
|
|
68e18eabb2 | ||
|
|
db86a1b838 | ||
|
|
00bcd1ce8b | ||
|
|
b08f10ffd8 | ||
|
|
d596901055 | ||
|
|
f933ad0840 | ||
|
|
083237051f | ||
|
|
8319c961c0 | ||
|
|
5420c5aad9 | ||
|
|
987e92cc43 | ||
|
|
a5ae70624d | ||
|
|
2c854c53ee | ||
|
|
06863fe2d2 | ||
|
|
97da701379 | ||
|
|
bf84e99dec | ||
|
|
057ee642f6 | ||
|
|
1e091d181b | ||
|
|
7c93aea182 | ||
|
|
341932b58f | ||
|
|
d6270ace0a | ||
|
|
abd350bbf4 | ||
|
|
19e88b0293 | ||
|
|
7e474b6b16 | ||
|
|
53e740a1e6 | ||
|
|
8185e9b3cb | ||
|
|
c4c06d2c94 | ||
|
|
31ae7a6227 | ||
|
|
af0b4d9a29 | ||
|
|
cf8e403f88 | ||
|
|
0da602f8e9 | ||
|
|
99c946ae43 | ||
|
|
f0e81d01c9 | ||
|
|
b57e245beb | ||
|
|
ceedc9e493 | ||
|
|
48fa904ad8 | ||
|
|
1757847e5f | ||
|
|
a4871802ad | ||
|
|
a64d8bb0df | ||
|
|
f82d47273c | ||
|
|
9be0eb133c | ||
|
|
db93edb665 | ||
|
|
e1acc2c4e7 | ||
|
|
d446e97309 | ||
|
|
ab06ac2f64 | ||
|
|
6191451e2c | ||
|
|
2a21c4f6ae | ||
|
|
69dd4689bf | ||
|
|
92eac2a9e1 | ||
|
|
9129c8cc1d | ||
|
|
bacb2a2053 | ||
|
|
8e71286b6d | ||
|
|
0e9b1973b0 | ||
|
|
6ec463288f | ||
|
|
1b73c10ed5 | ||
|
|
fc7f504e85 | ||
|
|
fe7e124329 | ||
|
|
78a7e20838 | ||
|
|
7862749cfe | ||
|
|
267e86704b | ||
|
|
7a00a875e7 | ||
|
|
3552478d02 | ||
|
|
801f543a7a | ||
|
|
88b5feb1ed | ||
|
|
1654741cdf | ||
|
|
5cde6f2216 | ||
|
|
26c1911e41 | ||
|
|
309a93c221 | ||
|
|
00875a65a6 | ||
|
|
c93e69fb9a | ||
|
|
b5199ec7e0 | ||
|
|
158b62dafa | ||
|
|
e9b537f23c | ||
|
|
7074688ced | ||
|
|
ed247d78b6 | ||
|
|
ce4ac89659 | ||
|
|
8035353cc0 | ||
|
|
99d012230f | ||
|
|
a9925496d5 | ||
|
|
907d1b0b0f | ||
|
|
25fe9ea642 | ||
|
|
168f3ccbee | ||
|
|
d9be7b9c26 | ||
|
|
e05864e751 | ||
|
|
83bb0e7f35 | ||
|
|
8321e19009 | ||
|
|
5406a72f62 | ||
|
|
9edab74562 | ||
|
|
7eebde487f | ||
|
|
945700d56e | ||
|
|
5bacc50088 | ||
|
|
b60814fb6b | ||
|
|
10b67de349 | ||
|
|
4cf2ffc979 | ||
|
|
ef23a6213d | ||
|
|
ee1e762a7f | ||
|
|
0cc4583653 | ||
|
|
e545b18627 | ||
|
|
4eabdcce78 | ||
|
|
138b377d1d | ||
|
|
9a5d752ba1 | ||
|
|
ec066008a8 | ||
|
|
406643f8ee | ||
|
|
6ef3ee83ef | ||
|
|
3f4e8433bd | ||
|
|
1570287db1 | ||
|
|
15a57d22f7 | ||
|
|
f835baa3d3 | ||
|
|
01e452c0d1 | ||
|
|
234cffbf24 | ||
|
|
de11d52348 | ||
|
|
6875b99611 | ||
|
|
e4fb931878 | ||
|
|
5238f40fe3 | ||
|
|
a49936b645 | ||
|
|
a3032e4363 | ||
|
|
7e290c67bf | ||
|
|
fb7073259f | ||
|
|
498c6859fe | ||
|
|
08d4569794 | ||
|
|
d6e9af7090 | ||
|
|
fd285a7e7d | ||
|
|
998a69cc0a | ||
|
|
3659c3f6e6 | ||
|
|
ee6e790d80 | ||
|
|
5e725ff8fb | ||
|
|
925ec31578 | ||
|
|
28da83c9b6 | ||
|
|
f61aae6158 | ||
|
|
f86d2b84a0 | ||
|
|
3567202e75 | ||
|
|
c0a4e8aa87 | ||
|
|
bc68d35e5a | ||
|
|
cb36e1013e | ||
|
|
df1476bf42 | ||
|
|
9a1ab1c656 | ||
|
|
5c36a4b111 | ||
|
|
3157e0389e | ||
|
|
34c2cc23a9 | ||
|
|
a35eb7dfa4 | ||
|
|
76750eec05 | ||
|
|
b89cf970e1 | ||
|
|
794a38cc7e | ||
|
|
73b7444baa | ||
|
|
ea36decf07 | ||
|
|
b3820055d0 | ||
|
|
35e637cbfd | ||
|
|
d6425cab02 | ||
|
|
59cd0dc272 | ||
|
|
838803d053 | ||
|
|
bdce322e65 | ||
|
|
66226a8a1b | ||
|
|
3ed58330d9 | ||
|
|
65ac9fa6d9 | ||
|
|
5e56e3649f | ||
|
|
0212ad7a2d | ||
|
|
1a1af02912 | ||
|
|
9d9b188b0b | ||
|
|
fa93f5b3c1 | ||
|
|
729b6fdf7c | ||
|
|
9c45f3a97d | ||
|
|
eea896dace | ||
|
|
70fcdff3c5 | ||
|
|
bfd6af8141 | ||
|
|
98fa84bb17 | ||
|
|
3988accdf3 | ||
|
|
9911b5e6f0 | ||
|
|
91515717d6 | ||
|
|
296baa30ce | ||
|
|
41d8bd9ec9 | ||
|
|
4bf78e5316 | ||
|
|
6ef9224dfe | ||
|
|
aeac12ed7a | ||
|
|
29ce253bb6 | ||
|
|
59add151eb | ||
|
|
e5b125cd89 | ||
|
|
0dba876979 | ||
|
|
bb82d63453 | ||
|
|
768a4b2d90 | ||
|
|
9f75b7e051 | ||
|
|
1f25bba463 | ||
|
|
47978275bb | ||
|
|
edd9b20691 | ||
|
|
d3aba90119 | ||
|
|
0f6fe96626 | ||
|
|
feddafcea2 | ||
|
|
5a305a7f9f | ||
|
|
cf18ecc2da | ||
|
|
c68f5f7439 | ||
|
|
c08296747f | ||
|
|
6b9565ed63 | ||
|
|
8b8da7d8fe | ||
|
|
8538c517e6 | ||
|
|
ed11e2bb3e | ||
|
|
a1cc320c36 | ||
|
|
0e920e5b18 | ||
|
|
55fc8a13e0 | ||
|
|
8919e65bab | ||
|
|
a7166fc1a4 | ||
|
|
712eecf64b | ||
|
|
605011a237 | ||
|
|
9039d95721 | ||
|
|
7c8020f8e8 | ||
|
|
0417c8ea00 | ||
|
|
6ee7ad508e | ||
|
|
31b2c686cf | ||
|
|
e011d031a8 | ||
|
|
6e5b493b28 | ||
|
|
8d7504144d | ||
|
|
d8e90a94c1 | ||
|
|
6bc53b771d | ||
|
|
2263d02a0a | ||
|
|
88f50a8fd9 | ||
|
|
17d48e3e45 | ||
|
|
a37c0e6ac8 | ||
|
|
24d3de2126 | ||
|
|
e1f5d185ee | ||
|
|
f96128bf2c | ||
|
|
8fd62b3e78 | ||
|
|
08669de287 | ||
|
|
b6d156afa5 | ||
|
|
1e4ed578ba | ||
|
|
365a1ce1d6 | ||
|
|
895c92febd | ||
|
|
039b211ef7 | ||
|
|
127bfa2c99 | ||
|
|
880194a1f9 | ||
|
|
98395f94ce | ||
|
|
1077d2323c | ||
|
|
15f0e62e5f | ||
|
|
49de5335c0 | ||
|
|
a9ba0e1cb4 | ||
|
|
5df3154112 | ||
|
|
6e930d16cc | ||
|
|
d71bed76af | ||
|
|
da2574d1bb | ||
|
|
456d04e318 | ||
|
|
b65f161e8b | ||
|
|
ce0bae1839 | ||
|
|
948805b6e5 | ||
|
|
b55ec9425b | ||
|
|
da98636599 | ||
|
|
8500514ef9 | ||
|
|
20e9914645 | ||
|
|
372e33bd5b | ||
|
|
a57d7aa002 | ||
|
|
d16e2aa2ff | ||
|
|
b355f2b839 | ||
|
|
aa6fc5b12e | ||
|
|
53ac085fc0 | ||
|
|
5e1a5c6cf6 | ||
|
|
79ed360009 | ||
|
|
ea183da9ba | ||
|
|
d903ea7d3d | ||
|
|
a35142b006 | ||
|
|
6ae5531bad | ||
|
|
ee1250c6bb | ||
|
|
20af8955c3 | ||
|
|
79134368b4 | ||
|
|
78cc3050e0 | ||
|
|
490b0a8ead | ||
|
|
32e5c4d200 | ||
|
|
3d7801cee4 | ||
|
|
ca3c58bb1a | ||
|
|
811dd32713 | ||
|
|
74c6d25486 | ||
|
|
974dd656da | ||
|
|
4e6a85a148 | ||
|
|
70e3c6b524 | ||
|
|
eb6de2e8d0 | ||
|
|
475f371016 | ||
|
|
06b932792f | ||
|
|
74a441ef93 | ||
|
|
de279dd060 | ||
|
|
ebe3068a8d | ||
|
|
8e9fb0e11c | ||
|
|
d687833c15 | ||
|
|
0a11c67a0c | ||
|
|
49430f900b | ||
|
|
f621d2a5fc | ||
|
|
e33d8c84ec | ||
|
|
8479624614 | ||
|
|
2da36b7fda | ||
|
|
b605308687 | ||
|
|
547bd4e45a | ||
|
|
4334ed58b4 | ||
|
|
c44eca13a9 | ||
|
|
c3ab39b068 | ||
|
|
157fbb1b7f | ||
|
|
2b96d9cef2 | ||
|
|
8387a64b15 | ||
|
|
38c98a6476 | ||
|
|
263333a0d1 | ||
|
|
09b4c3a865 | ||
|
|
f3614e6720 | ||
|
|
96e8914b33 | ||
|
|
1fe72d27aa | ||
|
|
b5cae8bf1a | ||
|
|
58104b620f | ||
|
|
058286fc0f | ||
|
|
e8daa145e4 | ||
|
|
dd1f3c3ecb | ||
|
|
b322192d93 | ||
|
|
c3ee35f3ec | ||
|
|
ad43eed0d0 | ||
|
|
e7c39757f6 | ||
|
|
f6df3d75ef | ||
|
|
34fecc3063 | ||
|
|
d34cabc985 | ||
|
|
23796233df | ||
|
|
bac29263da | ||
|
|
803ba1cd72 | ||
|
|
e8d3f1cca5 | ||
|
|
bdf7a3d02a | ||
|
|
c4040426fc | ||
|
|
0ac366ba03 |
+2
-1
@@ -10,4 +10,5 @@ logs/
|
||||
tools/
|
||||
.vscode/
|
||||
convert_*
|
||||
*.pt
|
||||
*.pt
|
||||
*.pth
|
||||
@@ -0,0 +1,157 @@
|
||||
from einops import rearrange
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
CACHE_T = 2
|
||||
|
||||
class RMS_norm(nn.Module):
|
||||
|
||||
def __init__(self, dim, channel_first=True, images=True, bias=False):
|
||||
super().__init__()
|
||||
broadcastable_dims = (1, 1, 1) if not images else (1, 1)
|
||||
shape = (dim, *broadcastable_dims) if channel_first else (dim,)
|
||||
|
||||
self.channel_first = channel_first
|
||||
self.scale = dim**0.5
|
||||
self.gamma = nn.Parameter(torch.ones(shape))
|
||||
self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
|
||||
|
||||
def forward(self, x):
|
||||
return F.normalize(
|
||||
x, dim=(1 if self.channel_first else
|
||||
-1)) * self.scale * self.gamma + self.bias
|
||||
|
||||
class CausalConv3d(nn.Conv3d):
|
||||
"""
|
||||
Causal 3d convolusion.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._padding = (self.padding[2], self.padding[2], self.padding[1],
|
||||
self.padding[1], 2 * self.padding[0], 0)
|
||||
self.padding = (0, 0, 0)
|
||||
|
||||
def forward(self, x, cache_x=None):
|
||||
padding = list(self._padding)
|
||||
if cache_x is not None and self._padding[4] > 0:
|
||||
cache_x = cache_x.to(x.device)
|
||||
x = torch.cat([cache_x, x], dim=2)
|
||||
padding[4] -= cache_x.shape[2]
|
||||
x = F.pad(x, padding, mode='replicate')
|
||||
|
||||
return super().forward(x)
|
||||
|
||||
class PixelShuffle3d(nn.Module):
|
||||
def __init__(self, ff, hh, ww):
|
||||
super().__init__()
|
||||
self.ff = ff
|
||||
self.hh = hh
|
||||
self.ww = ww
|
||||
|
||||
def forward(self, x):
|
||||
# x: (B, C, F, H, W)
|
||||
return rearrange(x,
|
||||
'b c (f ff) (h hh) (w ww) -> b (c ff hh ww) f h w',
|
||||
ff=self.ff, hh=self.hh, ww=self.ww)
|
||||
|
||||
class Buffer_LQ4x_Proj(nn.Module):
|
||||
|
||||
def __init__(self, in_dim, out_dim, layer_num=30):
|
||||
super().__init__()
|
||||
self.ff = 1
|
||||
self.hh = 16
|
||||
self.ww = 16
|
||||
self.hidden_dim1 = 2048
|
||||
self.hidden_dim2 = 3072
|
||||
self.layer_num = layer_num
|
||||
|
||||
self.pixel_shuffle = PixelShuffle3d(self.ff, self.hh, self.ww)
|
||||
|
||||
self.conv1 = CausalConv3d(in_dim*self.ff*self.hh*self.ww, self.hidden_dim1, (4, 3, 3), stride=(2, 1, 1), padding=(1, 1, 1)) # f -> f/2 h -> h w -> w
|
||||
self.norm1 = RMS_norm(self.hidden_dim1, images=False)
|
||||
self.act1 = nn.SiLU()
|
||||
|
||||
self.conv2 = CausalConv3d(self.hidden_dim1, self.hidden_dim2, (4, 3, 3), stride=(2, 1, 1), padding=(1, 1, 1)) # f -> f/2 h -> h w -> w
|
||||
self.norm2 = RMS_norm(self.hidden_dim2, images=False)
|
||||
self.act2 = nn.SiLU()
|
||||
|
||||
self.linear_layers = nn.ModuleList([nn.Linear(self.hidden_dim2, out_dim) for _ in range(layer_num)])
|
||||
|
||||
self.clip_idx = 0
|
||||
|
||||
def forward(self, video):
|
||||
self.clear_cache()
|
||||
# x: (B, C, F, H, W)
|
||||
|
||||
t = video.shape[2]
|
||||
iter_ = 1 + (t - 1) // 4
|
||||
first_frame = video[:, :, :1, :, :].repeat(1, 1, 3, 1, 1)
|
||||
video = torch.cat([first_frame, video], dim=2)
|
||||
|
||||
out_x = []
|
||||
for i in range(iter_):
|
||||
x = self.pixel_shuffle(video[:,:,i*4:(i+1)*4,:,:])
|
||||
cache1_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv1'] = cache1_x
|
||||
x = self.conv1(x, self.cache['conv1'])
|
||||
x = self.norm1(x)
|
||||
x = self.act1(x)
|
||||
cache2_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv2'] = cache2_x
|
||||
if i == 0:
|
||||
continue
|
||||
x = self.conv2(x, self.cache['conv2'])
|
||||
x = self.norm2(x)
|
||||
x = self.act2(x)
|
||||
out_x.append(x)
|
||||
out_x = torch.cat(out_x, dim = 2)
|
||||
|
||||
out_x = rearrange(out_x, 'b c f h w -> b (f h w) c')
|
||||
outputs = []
|
||||
for i in range(self.layer_num):
|
||||
outputs.append(self.linear_layers[i](out_x))
|
||||
self.clear_cache()
|
||||
return outputs
|
||||
|
||||
def clear_cache(self):
|
||||
self.cache = {}
|
||||
self.cache['conv1'] = None
|
||||
self.cache['conv2'] = None
|
||||
self.clip_idx = 0
|
||||
|
||||
def stream_forward(self, video_clip):
|
||||
if self.clip_idx == 0:
|
||||
# self.clear_cache()
|
||||
first_frame = video_clip[:, :, :1, :, :].repeat(1, 1, 3, 1, 1)
|
||||
video_clip = torch.cat([first_frame, video_clip], dim=2)
|
||||
x = self.pixel_shuffle(video_clip)
|
||||
cache1_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv1'] = cache1_x
|
||||
x = self.conv1(x, self.cache['conv1'])
|
||||
x = self.norm1(x)
|
||||
x = self.act1(x)
|
||||
cache2_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv2'] = cache2_x
|
||||
self.clip_idx += 1
|
||||
return None
|
||||
else:
|
||||
x = self.pixel_shuffle(video_clip)
|
||||
cache1_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv1'] = cache1_x
|
||||
x = self.conv1(x, self.cache['conv1'])
|
||||
x = self.norm1(x)
|
||||
x = self.act1(x)
|
||||
cache2_x = x[:, :, -CACHE_T:, :, :].clone()
|
||||
self.cache['conv2'] = cache2_x
|
||||
x = self.conv2(x, self.cache['conv2'])
|
||||
x = self.norm2(x)
|
||||
x = self.act2(x)
|
||||
out_x = rearrange(x, 'b c f h w -> b (f h w) c')
|
||||
outputs = []
|
||||
for i in range(self.layer_num):
|
||||
outputs.append(self.linear_layers[i](out_x))
|
||||
self.clip_idx += 1
|
||||
return outputs
|
||||
@@ -0,0 +1,261 @@
|
||||
"""
|
||||
Tiny AutoEncoder for Hunyuan Video (Decoder-only, pruned)
|
||||
- Encoder removed
|
||||
- Transplant/widening helpers removed
|
||||
- Deepening (IdentityConv2d+ReLU) is now built into the decoder structure itself
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from tqdm.auto import tqdm
|
||||
from collections import namedtuple
|
||||
from einops import rearrange
|
||||
import torch.nn.init as init
|
||||
|
||||
DecoderResult = namedtuple("DecoderResult", ("frame", "memory"))
|
||||
TWorkItem = namedtuple("TWorkItem", ("input_tensor", "block_index"))
|
||||
|
||||
# ----------------------------
|
||||
# Utility / building blocks
|
||||
# ----------------------------
|
||||
|
||||
class IdentityConv2d(nn.Conv2d):
|
||||
"""Same-shape Conv2d initialized to identity (Dirac)."""
|
||||
def __init__(self, C, kernel_size=3, bias=False):
|
||||
pad = kernel_size // 2
|
||||
super().__init__(C, C, kernel_size, padding=pad, bias=bias)
|
||||
with torch.no_grad():
|
||||
init.dirac_(self.weight)
|
||||
if self.bias is not None:
|
||||
self.bias.zero_()
|
||||
|
||||
def conv(n_in, n_out, **kwargs):
|
||||
return nn.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
|
||||
|
||||
class Clamp(nn.Module):
|
||||
def forward(self, x):
|
||||
return torch.tanh(x / 3) * 3
|
||||
|
||||
class MemBlock(nn.Module):
|
||||
def __init__(self, n_in, n_out):
|
||||
super().__init__()
|
||||
self.conv = nn.Sequential(
|
||||
conv(n_in * 2, n_out), nn.ReLU(inplace=True),
|
||||
conv(n_out, n_out), nn.ReLU(inplace=True),
|
||||
conv(n_out, n_out)
|
||||
)
|
||||
self.skip = nn.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identity()
|
||||
self.act = nn.ReLU(inplace=True)
|
||||
def forward(self, x, past):
|
||||
return self.act(self.conv(torch.cat([x, past], 1)) + self.skip(x))
|
||||
|
||||
class TPool(nn.Module):
|
||||
def __init__(self, n_f, stride):
|
||||
super().__init__()
|
||||
self.stride = stride
|
||||
self.conv = nn.Conv2d(n_f*stride, n_f, 1, bias=False)
|
||||
def forward(self, x):
|
||||
_NT, C, H, W = x.shape
|
||||
return self.conv(x.reshape(-1, self.stride * C, H, W))
|
||||
|
||||
class TGrow(nn.Module):
|
||||
def __init__(self, n_f, stride):
|
||||
super().__init__()
|
||||
self.stride = stride
|
||||
self.conv = nn.Conv2d(n_f, n_f*stride, 1, bias=False)
|
||||
def forward(self, x):
|
||||
_NT, C, H, W = x.shape
|
||||
x = self.conv(x)
|
||||
return x.reshape(-1, C, H, W)
|
||||
|
||||
class PixelShuffle3d(nn.Module):
|
||||
def __init__(self, ff, hh, ww):
|
||||
super().__init__()
|
||||
self.ff = ff
|
||||
self.hh = hh
|
||||
self.ww = ww
|
||||
def forward(self, x):
|
||||
# x: (B, C, F, H, W)
|
||||
B, C, F, H, W = x.shape
|
||||
if F % self.ff != 0:
|
||||
first_frame = x[:, :, 0:1, :, :].repeat(1, 1, self.ff - F % self.ff, 1, 1)
|
||||
x = torch.cat([first_frame, x], dim=2)
|
||||
return rearrange(
|
||||
x,
|
||||
'b c (f ff) (h hh) (w ww) -> b (c ff hh ww) f h w',
|
||||
ff=self.ff, hh=self.hh, ww=self.ww
|
||||
).transpose(1, 2)
|
||||
|
||||
# ----------------------------
|
||||
# Generic NTCHW graph executor (kept; used by decoder)
|
||||
# ----------------------------
|
||||
|
||||
def apply_model_with_memblocks(model, x, parallel, show_progress_bar, mem=None):
|
||||
"""
|
||||
Apply a sequential model with memblocks to the given input.
|
||||
Args:
|
||||
- model: nn.Sequential of blocks to apply
|
||||
- x: input data, of dimensions NTCHW
|
||||
- parallel: if True, parallelize over timesteps (fast but uses O(T) memory)
|
||||
if False, each timestep will be processed sequentially (slow but uses O(1) memory)
|
||||
- show_progress_bar: if True, enables tqdm progressbar display
|
||||
|
||||
Returns NTCHW tensor of output data.
|
||||
"""
|
||||
assert x.ndim == 5, f"TAEHV operates on NTCHW tensors, but got {x.ndim}-dim tensor"
|
||||
N, T, C, H, W = x.shape
|
||||
if parallel:
|
||||
x = x.reshape(N*T, C, H, W)
|
||||
for b in tqdm(model, disable=not show_progress_bar):
|
||||
if isinstance(b, MemBlock):
|
||||
NT, C, H, W = x.shape
|
||||
T = NT // N
|
||||
_x = x.reshape(N, T, C, H, W)
|
||||
mem = F.pad(_x, (0,0,0,0,0,0,1,0), value=0)[:,:T].reshape(x.shape)
|
||||
x = b(x, mem)
|
||||
else:
|
||||
x = b(x)
|
||||
NT, C, H, W = x.shape
|
||||
T = NT // N
|
||||
x = x.view(N, T, C, H, W)
|
||||
else:
|
||||
out = []
|
||||
work_queue = [TWorkItem(xt, 0) for t, xt in enumerate(x.reshape(N, T * C, H, W).chunk(T, dim=1))]
|
||||
progress_bar = tqdm(range(T), disable=not show_progress_bar)
|
||||
while work_queue:
|
||||
xt, i = work_queue.pop(0)
|
||||
if i == 0:
|
||||
progress_bar.update(1)
|
||||
if i == len(model):
|
||||
out.append(xt)
|
||||
else:
|
||||
b = model[i]
|
||||
if isinstance(b, MemBlock):
|
||||
if mem[i] is None:
|
||||
xt_new = b(xt, xt * 0)
|
||||
mem[i] = xt
|
||||
else:
|
||||
xt_new = b(xt, mem[i])
|
||||
mem[i].copy_(xt)
|
||||
work_queue.insert(0, TWorkItem(xt_new, i+1))
|
||||
elif isinstance(b, TPool):
|
||||
if mem[i] is None:
|
||||
mem[i] = []
|
||||
mem[i].append(xt)
|
||||
if len(mem[i]) > b.stride:
|
||||
raise ValueError("TPool internal state invalid.")
|
||||
elif len(mem[i]) == b.stride:
|
||||
N_, C_, H_, W_ = xt.shape
|
||||
xt = b(torch.cat(mem[i], 1).view(N_*b.stride, C_, H_, W_))
|
||||
mem[i] = []
|
||||
work_queue.insert(0, TWorkItem(xt, i+1))
|
||||
elif isinstance(b, TGrow):
|
||||
xt = b(xt)
|
||||
NT, C_, H_, W_ = xt.shape
|
||||
for xt_next in reversed(xt.view(N, b.stride*C_, H_, W_).chunk(b.stride, 1)):
|
||||
work_queue.insert(0, TWorkItem(xt_next, i+1))
|
||||
else:
|
||||
xt = b(xt)
|
||||
work_queue.insert(0, TWorkItem(xt, i+1))
|
||||
progress_bar.close()
|
||||
x = torch.stack(out, 1)
|
||||
return x, mem
|
||||
|
||||
# ----------------------------
|
||||
# Decoder-only TAEHV
|
||||
# ----------------------------
|
||||
|
||||
class TAEHV(nn.Module):
|
||||
image_channels = 3
|
||||
def __init__(
|
||||
self,
|
||||
decoder_time_upscale=(True, True),
|
||||
decoder_space_upscale=(True, True, True),
|
||||
channels = [256, 128, 64, 64],
|
||||
latent_channels = 16,
|
||||
dtype=torch.float32
|
||||
):
|
||||
"""Initialize TAEHV (decoder-only) with built-in deepening after every ReLU.
|
||||
Deepening config: how_many_each=1, k=3 (fixed as requested).
|
||||
"""
|
||||
super().__init__()
|
||||
self.dtype = dtype
|
||||
self.latent_channels = latent_channels
|
||||
n_f = channels
|
||||
self.frames_to_trim = 2**sum(decoder_time_upscale) - 1
|
||||
|
||||
# Build the decoder "skeleton"
|
||||
base_decoder = nn.Sequential(
|
||||
Clamp(), conv(self.latent_channels, n_f[0]), nn.ReLU(inplace=True),
|
||||
|
||||
MemBlock(n_f[0], n_f[0]), MemBlock(n_f[0], n_f[0]), MemBlock(n_f[0], n_f[0]),
|
||||
nn.Upsample(scale_factor=2 if decoder_space_upscale[0] else 1),
|
||||
TGrow(n_f[0], 1),
|
||||
conv(n_f[0], n_f[1], bias=False),
|
||||
|
||||
MemBlock(n_f[1], n_f[1]), MemBlock(n_f[1], n_f[1]), MemBlock(n_f[1], n_f[1]),
|
||||
nn.Upsample(scale_factor=2 if decoder_space_upscale[1] else 1),
|
||||
TGrow(n_f[1], 2 if decoder_time_upscale[0] else 1),
|
||||
conv(n_f[1], n_f[2], bias=False),
|
||||
|
||||
MemBlock(n_f[2], n_f[2]), MemBlock(n_f[2], n_f[2]), MemBlock(n_f[2], n_f[2]),
|
||||
nn.Upsample(scale_factor=2 if decoder_space_upscale[2] else 1),
|
||||
TGrow(n_f[2], 2 if decoder_time_upscale[1] else 1),
|
||||
conv(n_f[2], n_f[3], bias=False),
|
||||
|
||||
nn.ReLU(inplace=True), conv(n_f[3], TAEHV.image_channels),
|
||||
)
|
||||
|
||||
# Inline deepening: insert (IdentityConv2d(k=3) + ReLU) after every ReLU
|
||||
self.decoder = self._apply_identity_deepen(base_decoder, how_many_each=1, k=3)
|
||||
|
||||
self.pixel_shuffle = PixelShuffle3d(4, 8, 8)
|
||||
|
||||
# Initialize decoder mem state
|
||||
self.clean_mem()
|
||||
|
||||
@staticmethod
|
||||
def _apply_identity_deepen(decoder: nn.Sequential, how_many_each=1, k=3) -> nn.Sequential:
|
||||
"""Return a new Sequential where every nn.ReLU is followed by how_many_each*(IdentityConv2d(k)+ReLU)."""
|
||||
new_layers = []
|
||||
for b in decoder:
|
||||
new_layers.append(b)
|
||||
if isinstance(b, nn.ReLU):
|
||||
# Deduce channel count from preceding layer
|
||||
C = None
|
||||
if len(new_layers) >= 2 and isinstance(new_layers[-2], nn.Conv2d):
|
||||
C = new_layers[-2].out_channels
|
||||
elif len(new_layers) >= 2 and isinstance(new_layers[-2], MemBlock):
|
||||
C = new_layers[-2].conv[-1].out_channels
|
||||
if C is not None:
|
||||
for _ in range(how_many_each):
|
||||
new_layers.append(IdentityConv2d(C, kernel_size=k, bias=False))
|
||||
new_layers.append(nn.ReLU(inplace=True))
|
||||
return nn.Sequential(*new_layers)
|
||||
|
||||
def decode_video(self, x, parallel=False, show_progress_bar=False, cond=None):
|
||||
"""Decode a sequence of frames from latents.
|
||||
x: NTCHW latent tensor; returns NTCHW RGB in ~[0, 1].
|
||||
"""
|
||||
trim_flag = self.mem[-8] is None # keeps original relative check
|
||||
|
||||
if cond is not None:
|
||||
shuffled = self.pixel_shuffle(cond.to(x))
|
||||
x = torch.cat([shuffled[:, :x.shape[1]], x], dim=2)
|
||||
|
||||
x, self.mem = apply_model_with_memblocks(self.decoder, x, parallel, show_progress_bar, mem=self.mem)
|
||||
self.clean_mem()
|
||||
|
||||
if trim_flag:
|
||||
return x[:, self.frames_to_trim:]
|
||||
|
||||
return x
|
||||
|
||||
def clean_mem(self):
|
||||
self.mem = [None] * len(self.decoder)
|
||||
|
||||
|
||||
def build_tcdecoder(new_channels = [512, 256, 128, 128], device="cuda", dtype=torch.bfloat16, new_latent_channels=None):
|
||||
big = TAEHV(channels=new_channels, latent_channels=new_latent_channels, dtype=dtype).to(device).to(dtype)
|
||||
return big
|
||||
@@ -0,0 +1,71 @@
|
||||
import folder_paths
|
||||
import torch
|
||||
|
||||
from comfy.utils import load_torch_file
|
||||
import comfy.model_management as mm
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
|
||||
class WanVideoAddFlashVSRInput:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"embeds": ("WANVIDIMAGE_EMBEDS",),
|
||||
"images": ("IMAGE", {"tooltip": "Low-res video frames to enhance"}),
|
||||
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.01, "tooltip": "Strength to apply the FlashVSR latent"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVIDIMAGE_EMBEDS",)
|
||||
RETURN_NAMES = ("image_embeds",)
|
||||
FUNCTION = "add"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def add(self, embeds, images, strength):
|
||||
updated = dict(embeds)
|
||||
updated["flashvsr_LQ_images"] = images
|
||||
updated["flashvsr_strength"] = strength
|
||||
return (updated,)
|
||||
|
||||
|
||||
class WanVideoFlashVSRDecoderLoader:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model_name": (folder_paths.get_filename_list("vae"), {"tooltip": "These models are loaded from 'ComfyUI/models/vae'"}),
|
||||
},
|
||||
"optional": {
|
||||
"precision": (["fp16", "fp32", "bf16"],
|
||||
{"default": "bf16"}
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVAE",)
|
||||
RETURN_NAMES = ("vae", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
DESCRIPTION = "Loads Wan VAE model from 'ComfyUI/models/vae'"
|
||||
|
||||
def loadmodel(self, model_name, precision):
|
||||
from .TCDecoder import build_tcdecoder
|
||||
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[precision]
|
||||
model_path = folder_paths.get_full_path("vae", model_name)
|
||||
sd = load_torch_file(model_path, safe_load=True)
|
||||
|
||||
TCDecoder = build_tcdecoder(new_channels=[512, 256, 128, 128], new_latent_channels=16+768, dtype=dtype)
|
||||
TCDecoder.load_state_dict(sd, strict=True)
|
||||
TCDecoder.to(dtype)
|
||||
|
||||
return (TCDecoder,)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"WanVideoAddFlashVSRInput": WanVideoAddFlashVSRInput,
|
||||
"WanVideoFlashVSRDecoderLoader": WanVideoFlashVSRDecoderLoader,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"WanVideoAddFlashVSRInput": "WanVideo Add FlashVSR Input",
|
||||
"WanVideoFlashVSRDecoderLoader": "WanVideo FlashVSR Decoder Loader",
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import torch
|
||||
from einops import rearrange
|
||||
from torch import nn
|
||||
from einops import rearrange
|
||||
|
||||
class WanRMSNorm(nn.Module):
|
||||
|
||||
def __init__(self, dim, eps=1e-5):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(dim))
|
||||
|
||||
def forward(self, x):
|
||||
r"""
|
||||
Args:
|
||||
x(Tensor): Shape [B, L, C]
|
||||
"""
|
||||
return self._norm(x.to(self.weight.dtype)) * self.weight
|
||||
|
||||
def _norm(self, x):
|
||||
return x * (torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)).to(x.dtype)
|
||||
|
||||
|
||||
class DummyAdapterLayer(nn.Module):
|
||||
def __init__(self, layer):
|
||||
super().__init__()
|
||||
self.layer = layer
|
||||
|
||||
def forward(self, *args, **kwargs):
|
||||
return self.layer(*args, **kwargs)
|
||||
|
||||
|
||||
class AudioProjModel(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
seq_len=5,
|
||||
blocks=13, # add a new parameter blocks
|
||||
channels=768, # add a new parameter channels
|
||||
intermediate_dim=512,
|
||||
output_dim=1536,
|
||||
context_tokens=16,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.seq_len = seq_len
|
||||
self.blocks = blocks
|
||||
self.channels = channels
|
||||
self.input_dim = seq_len * blocks * channels # update input_dim to be the product of blocks and channels.
|
||||
self.intermediate_dim = intermediate_dim
|
||||
self.context_tokens = context_tokens
|
||||
self.output_dim = output_dim
|
||||
|
||||
# define multiple linear layers
|
||||
self.audio_proj_glob_1 = DummyAdapterLayer(nn.Linear(self.input_dim, intermediate_dim))
|
||||
self.audio_proj_glob_2 = DummyAdapterLayer(nn.Linear(intermediate_dim, intermediate_dim))
|
||||
self.audio_proj_glob_3 = DummyAdapterLayer(nn.Linear(intermediate_dim, context_tokens * output_dim))
|
||||
|
||||
self.audio_proj_glob_norm = DummyAdapterLayer(nn.LayerNorm(output_dim))
|
||||
|
||||
self.initialize_weights()
|
||||
|
||||
def initialize_weights(self):
|
||||
# Initialize transformer layers:
|
||||
def _basic_init(module):
|
||||
if isinstance(module, nn.Linear):
|
||||
torch.nn.init.xavier_uniform_(module.weight)
|
||||
if module.bias is not None:
|
||||
nn.init.constant_(module.bias, 0)
|
||||
|
||||
self.apply(_basic_init)
|
||||
|
||||
def forward(self, audio_embeds):
|
||||
video_length = audio_embeds.shape[1]
|
||||
audio_embeds = rearrange(audio_embeds, "bz f w b c -> (bz f) w b c")
|
||||
batch_size, window_size, blocks, channels = audio_embeds.shape
|
||||
audio_embeds = audio_embeds.view(batch_size, window_size * blocks * channels)
|
||||
|
||||
audio_embeds = torch.relu(self.audio_proj_glob_1(audio_embeds))
|
||||
audio_embeds = torch.relu(self.audio_proj_glob_2(audio_embeds))
|
||||
|
||||
context_tokens = self.audio_proj_glob_3(audio_embeds).reshape(batch_size, self.context_tokens, self.output_dim)
|
||||
|
||||
context_tokens = self.audio_proj_glob_norm(context_tokens.to(self.audio_proj_glob_norm.layer.weight.dtype)).to(audio_embeds.dtype)
|
||||
context_tokens = rearrange(context_tokens, "(bz f) m c -> bz f m c", f=video_length)
|
||||
|
||||
return context_tokens
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
import folder_paths
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import os
|
||||
import json
|
||||
import torchaudio
|
||||
|
||||
from comfy.utils import load_torch_file, common_upscale
|
||||
import comfy.model_management as mm
|
||||
|
||||
from accelerate import init_empty_weights
|
||||
from ..utils import set_module_tensor_to_device, log
|
||||
from ..nodes import WanVideoEncodeLatentBatch
|
||||
|
||||
script_directory = os.path.dirname(os.path.abspath(__file__))
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
|
||||
def linear_interpolation_fps(features, input_fps, output_fps, output_len=None):
|
||||
features = features.transpose(1, 2) # [1, C, T]
|
||||
seq_len = features.shape[2] / float(input_fps)
|
||||
if output_len is None:
|
||||
output_len = int(seq_len * output_fps)
|
||||
output_features = F.interpolate(features, size=output_len, align_corners=True, mode='linear')
|
||||
return output_features.transpose(1, 2)
|
||||
|
||||
def get_audio_emb_window(audio_emb, frame_num, frame0_idx, audio_shift=2):
|
||||
zero_audio_embed = torch.zeros((audio_emb.shape[1], audio_emb.shape[2]), dtype=audio_emb.dtype, device=audio_emb.device)
|
||||
zero_audio_embed_3 = torch.zeros((3, audio_emb.shape[1], audio_emb.shape[2]), dtype=audio_emb.dtype, device=audio_emb.device)
|
||||
iter_ = 1 + (frame_num - 1) // 4
|
||||
audio_emb_wind = []
|
||||
for lt_i in range(iter_):
|
||||
if lt_i == 0:
|
||||
st = frame0_idx + lt_i - 2
|
||||
ed = frame0_idx + lt_i + 3
|
||||
wind_feat = torch.stack([
|
||||
audio_emb[i] if (0 <= i < audio_emb.shape[0]) else zero_audio_embed
|
||||
for i in range(st, ed)
|
||||
], dim=0)
|
||||
wind_feat = torch.cat((zero_audio_embed_3, wind_feat), dim=0)
|
||||
else:
|
||||
st = frame0_idx + 1 + 4 * (lt_i - 1) - audio_shift
|
||||
ed = frame0_idx + 1 + 4 * lt_i + audio_shift
|
||||
wind_feat = torch.stack([
|
||||
audio_emb[i] if (0 <= i < audio_emb.shape[0]) else zero_audio_embed
|
||||
for i in range(st, ed)
|
||||
], dim=0)
|
||||
audio_emb_wind.append(wind_feat)
|
||||
audio_emb_wind = torch.stack(audio_emb_wind, dim=0)
|
||||
|
||||
return audio_emb_wind, ed - audio_shift
|
||||
|
||||
class WhisperModelLoader:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": (folder_paths.get_filename_list("audio_encoders"), {"tooltip": "These models are loaded from the 'ComfyUI/models/audio_encoders' folder",}),
|
||||
"base_precision": (["fp32", "bf16", "fp16"], {"default": "fp16"}),
|
||||
"load_device": (["main_device", "offload_device"], {"default": "main_device", "tooltip": "Initial device to load the model to, NOT recommended with the larger models unless you have 48GB+ VRAM"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WHISPERMODEL",)
|
||||
RETURN_NAMES = ("whisper_model", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def loadmodel(self, model, base_precision, load_device):
|
||||
from transformers import WhisperConfig, WhisperModel, WhisperFeatureExtractor
|
||||
|
||||
base_dtype = {"fp8_e4m3fn": torch.float8_e4m3fn, "fp8_e4m3fn_fast": torch.float8_e4m3fn, "bf16": torch.bfloat16, "fp16": torch.float16, "fp16_fast": torch.float16, "fp32": torch.float32}[base_precision]
|
||||
|
||||
if load_device == "offload_device":
|
||||
transformer_load_device = offload_device
|
||||
else:
|
||||
transformer_load_device = device
|
||||
|
||||
config_path = os.path.join(script_directory, "whisper_config.json")
|
||||
whisper_config = WhisperConfig(**json.load(open(config_path)))
|
||||
|
||||
with init_empty_weights():
|
||||
whisper = WhisperModel(whisper_config).eval()
|
||||
whisper.decoder = None # we only need the encoder
|
||||
|
||||
feature_extractor_config = {
|
||||
"chunk_length": 30,
|
||||
"feature_extractor_type": "WhisperFeatureExtractor",
|
||||
"feature_size": 128,
|
||||
"hop_length": 160,
|
||||
"n_fft": 400,
|
||||
"n_samples": 480000,
|
||||
"nb_max_frames": 3000,
|
||||
"padding_side": "right",
|
||||
"padding_value": 0.0,
|
||||
"processor_class": "WhisperProcessor",
|
||||
"return_attention_mask": False,
|
||||
"sampling_rate": 16000
|
||||
}
|
||||
|
||||
feature_extractor = WhisperFeatureExtractor(**feature_extractor_config)
|
||||
|
||||
model_path = folder_paths.get_full_path_or_raise("audio_encoders", model)
|
||||
sd = load_torch_file(model_path, device=transformer_load_device, safe_load=True)
|
||||
|
||||
for name, param in whisper.named_parameters():
|
||||
key = "model." + name
|
||||
value=sd[key]
|
||||
set_module_tensor_to_device(whisper, name, device=offload_device, dtype=base_dtype, value=value)
|
||||
|
||||
whisper_model = {
|
||||
"feature_extractor": feature_extractor,
|
||||
"model": whisper,
|
||||
"dtype": base_dtype,
|
||||
}
|
||||
|
||||
return (whisper_model,)
|
||||
|
||||
class HuMoEmbeds:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"num_frames": ("INT", {"default": 81, "min": -1, "max": 10000, "step": 1, "tooltip": "The total frame count to generate."}),
|
||||
"width": ("INT", {"default": 832, "min": 64, "max": 4096, "step": 16}),
|
||||
"height": ("INT", {"default": 480, "min": 64, "max": 4096, "step": 16}),
|
||||
"audio_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01, "tooltip": "Strength of the audio conditioning"}),
|
||||
"audio_cfg_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01, "tooltip": "When not 1.0, an extra model pass without audio conditioning is done: slower inference but more motion is allowed"}),
|
||||
"audio_start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The percent of the video to start applying audio conditioning"}),
|
||||
"audio_end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The percent of the video to stop applying audio conditioning"})
|
||||
},
|
||||
"optional" : {
|
||||
"whisper_model": ("WHISPERMODEL",),
|
||||
"vae": ("WANVAE", ),
|
||||
"reference_images": ("IMAGE", {"tooltip": "reference images for the humo model"}),
|
||||
"audio": ("AUDIO",),
|
||||
"tiled_vae": ("BOOLEAN", {"default": False, "tooltip": "Use tiled VAE encoding for reduced memory use"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVIDIMAGE_EMBEDS", )
|
||||
RETURN_NAMES = ("image_embeds", )
|
||||
FUNCTION = "process"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def process(self, num_frames, width, height, audio_scale, audio_cfg_scale, audio_start_percent, audio_end_percent, whisper_model=None, vae=None, reference_images=None, audio=None, tiled_vae=False):
|
||||
if reference_images is not None and vae is None:
|
||||
raise ValueError("VAE is required when reference images are provided")
|
||||
if whisper_model is None and audio is not None:
|
||||
raise ValueError("Whisper model is required when audio is provided")
|
||||
model = whisper_model["model"]
|
||||
feature_extractor = whisper_model["feature_extractor"]
|
||||
dtype = whisper_model["dtype"]
|
||||
|
||||
sampling_rate = 16000
|
||||
|
||||
if audio is not None:
|
||||
audio_input = audio["waveform"][0]
|
||||
sample_rate = audio["sample_rate"]
|
||||
|
||||
if sample_rate != sampling_rate:
|
||||
audio_input = torchaudio.functional.resample(audio_input, sample_rate, sampling_rate)
|
||||
if audio_input.shape[1] == 2:
|
||||
audio_input = audio_input.mean(dim=0, keepdim=False)
|
||||
else:
|
||||
audio_input = audio_input[0]
|
||||
|
||||
model.to(device)
|
||||
audio_len = len(audio_input) // 640
|
||||
|
||||
# feature extraction
|
||||
audio_features = []
|
||||
window = 750*640
|
||||
for i in range(0, len(audio_input), window):
|
||||
audio_feature = feature_extractor(audio_input[i:i+window], sampling_rate=sampling_rate, return_tensors="pt").input_features
|
||||
audio_features.append(audio_feature)
|
||||
audio_features = torch.cat(audio_features, dim=-1).to(device, dtype)
|
||||
|
||||
# preprocess
|
||||
window = 3000
|
||||
audio_prompts = []
|
||||
for i in range(0, audio_features.shape[-1], window):
|
||||
audio_prompt = model.encoder(audio_features[:,:,i:i+window], output_hidden_states=True).hidden_states
|
||||
audio_prompt = torch.stack(audio_prompt, dim=2)
|
||||
audio_prompts.append(audio_prompt)
|
||||
|
||||
model.to(offload_device)
|
||||
|
||||
audio_prompts = torch.cat(audio_prompts, dim=1)
|
||||
audio_prompts = audio_prompts[:,:audio_len*2]
|
||||
|
||||
feat0 = linear_interpolation_fps(audio_prompts[:, :, 0: 8].mean(dim=2), 50, 25)
|
||||
feat1 = linear_interpolation_fps(audio_prompts[:, :, 8: 16].mean(dim=2), 50, 25)
|
||||
feat2 = linear_interpolation_fps(audio_prompts[:, :, 16: 24].mean(dim=2), 50, 25)
|
||||
feat3 = linear_interpolation_fps(audio_prompts[:, :, 24: 32].mean(dim=2), 50, 25)
|
||||
feat4 = linear_interpolation_fps(audio_prompts[:, :, 32], 50, 25)
|
||||
audio_emb = torch.stack([feat0, feat1, feat2, feat3, feat4], dim=2)[0] # [T, 5, 1280]
|
||||
else:
|
||||
audio_emb = torch.zeros(num_frames, 5, 1280, device=device)
|
||||
audio_len = num_frames
|
||||
|
||||
pixel_frame_num = num_frames if num_frames != -1 else audio_len
|
||||
pixel_frame_num = 4 * ((pixel_frame_num - 1) // 4) + 1
|
||||
latent_frame_num = (pixel_frame_num - 1) // 4 + 1
|
||||
|
||||
log.info(f"HuMo set to generate {pixel_frame_num} frames")
|
||||
|
||||
#audio_emb, _ = get_audio_emb_window(audio_emb, pixel_frame_num, frame0_idx=0)
|
||||
|
||||
num_refs = 0
|
||||
if reference_images is not None:
|
||||
if reference_images.shape[1] != height or reference_images.shape[2] != width:
|
||||
reference_images_in = common_upscale(reference_images.movedim(-1, 1), width, height, "lanczos", "disabled").movedim(1, -1)
|
||||
else:
|
||||
reference_images_in = reference_images
|
||||
samples, = WanVideoEncodeLatentBatch.encode(self, vae, reference_images_in, tiled_vae, None, None, None, None)
|
||||
samples = samples["samples"].transpose(0, 2).squeeze(0)
|
||||
num_refs = samples.shape[1]
|
||||
|
||||
vae.to(device)
|
||||
zero_frames = torch.zeros(1, 3, pixel_frame_num + 4*num_refs, height, width, device=device, dtype=vae.dtype)
|
||||
zero_latents = vae.encode(zero_frames, device=device, tiled=tiled_vae)[0].to(offload_device)
|
||||
|
||||
vae.to(offload_device)
|
||||
mm.soft_empty_cache()
|
||||
|
||||
target_shape = (16, latent_frame_num + num_refs, height // 8, width // 8)
|
||||
|
||||
mask = torch.ones(4, target_shape[1], target_shape[2], target_shape[3], device=offload_device, dtype=vae.dtype)
|
||||
if reference_images is not None:
|
||||
mask[:,:-num_refs] = 0
|
||||
image_cond = torch.cat([zero_latents[:, :(target_shape[1]-num_refs)], samples], dim=1)
|
||||
#zero_audio_pad = torch.zeros(num_refs, *audio_emb.shape[1:]).to(audio_emb.device)
|
||||
#audio_emb = torch.cat([audio_emb, zero_audio_pad], dim=0)
|
||||
else:
|
||||
image_cond = zero_latents
|
||||
mask = torch.zeros_like(mask)
|
||||
image_cond = torch.cat([mask, image_cond], dim=0)
|
||||
image_cond_neg = torch.cat([mask, zero_latents], dim=0)
|
||||
|
||||
embeds = {
|
||||
"humo_audio_emb": audio_emb,
|
||||
"humo_audio_emb_neg": torch.zeros_like(audio_emb, dtype=audio_emb.dtype, device=audio_emb.device),
|
||||
"humo_image_cond": image_cond,
|
||||
"humo_image_cond_neg": image_cond_neg,
|
||||
"humo_reference_count": num_refs,
|
||||
"target_shape": target_shape,
|
||||
"num_frames": pixel_frame_num,
|
||||
"humo_audio_scale": audio_scale,
|
||||
"humo_audio_cfg_scale": audio_cfg_scale,
|
||||
"humo_start_percent": audio_start_percent,
|
||||
"humo_end_percent": audio_end_percent,
|
||||
}
|
||||
|
||||
return (embeds, )
|
||||
|
||||
class WanVideoCombineEmbeds:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"embeds_1": ("WANVIDIMAGE_EMBEDS",),
|
||||
"embeds_2": ("WANVIDIMAGE_EMBEDS",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVIDIMAGE_EMBEDS",)
|
||||
RETURN_NAMES = ("image_embeds",)
|
||||
FUNCTION = "add"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
EXPERIMENTAL = True
|
||||
|
||||
def add(self, embeds_1, embeds_2):
|
||||
# Combine the two sets of embeds
|
||||
combined = {**embeds_1, **embeds_2}
|
||||
return (combined,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"WhisperModelLoader": WhisperModelLoader,
|
||||
"HuMoEmbeds": HuMoEmbeds,
|
||||
"WanVideoCombineEmbeds": WanVideoCombineEmbeds,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"WhisperModelLoader": "Whisper Model Loader",
|
||||
"HuMoEmbeds": "HuMo Embeds",
|
||||
"WanVideoCombineEmbeds": "WanVideo Combine Embeds",
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"_name_or_path": "openai/whisper-large-v3",
|
||||
"activation_dropout": 0.0,
|
||||
"activation_function": "gelu",
|
||||
"apply_spec_augment": false,
|
||||
"architectures": [
|
||||
"WhisperForConditionalGeneration"
|
||||
],
|
||||
"attention_dropout": 0.0,
|
||||
"begin_suppress_tokens": [
|
||||
220,
|
||||
50257
|
||||
],
|
||||
"bos_token_id": 50257,
|
||||
"classifier_proj_size": 256,
|
||||
"d_model": 1280,
|
||||
"decoder_attention_heads": 20,
|
||||
"decoder_ffn_dim": 5120,
|
||||
"decoder_layerdrop": 0.0,
|
||||
"decoder_layers": 32,
|
||||
"decoder_start_token_id": 50258,
|
||||
"dropout": 0.0,
|
||||
"encoder_attention_heads": 20,
|
||||
"encoder_ffn_dim": 5120,
|
||||
"encoder_layerdrop": 0.0,
|
||||
"encoder_layers": 32,
|
||||
"eos_token_id": 50257,
|
||||
"init_std": 0.02,
|
||||
"is_encoder_decoder": true,
|
||||
"mask_feature_length": 10,
|
||||
"mask_feature_min_masks": 0,
|
||||
"mask_feature_prob": 0.0,
|
||||
"mask_time_length": 10,
|
||||
"mask_time_min_masks": 2,
|
||||
"mask_time_prob": 0.05,
|
||||
"max_length": 448,
|
||||
"max_source_positions": 1500,
|
||||
"max_target_positions": 448,
|
||||
"median_filter_width": 7,
|
||||
"model_type": "whisper",
|
||||
"num_hidden_layers": 32,
|
||||
"num_mel_bins": 128,
|
||||
"pad_token_id": 50256,
|
||||
"scale_embedding": false,
|
||||
"torch_dtype": "float16",
|
||||
"transformers_version": "4.36.0.dev0",
|
||||
"use_cache": true,
|
||||
"use_weighted_layer_sum": false,
|
||||
"vocab_size": 51866
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
import math
|
||||
|
||||
class FeedForwardSwiGLU(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
hidden_dim: int,
|
||||
multiple_of: int = 256,
|
||||
):
|
||||
super().__init__()
|
||||
hidden_dim = int(2 * hidden_dim / 3)
|
||||
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
|
||||
|
||||
self.dim = dim
|
||||
self.hidden_dim = hidden_dim
|
||||
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
|
||||
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
||||
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
||||
|
||||
def forward(self, x):
|
||||
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
||||
|
||||
class TimestepEmbedder(nn.Module):
|
||||
"""
|
||||
Embeds scalar timesteps into vector representations.
|
||||
"""
|
||||
|
||||
def __init__(self, t_embed_dim, frequency_embedding_size=256):
|
||||
super().__init__()
|
||||
self.t_embed_dim = t_embed_dim
|
||||
self.frequency_embedding_size = frequency_embedding_size
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(frequency_embedding_size, t_embed_dim, bias=True),
|
||||
nn.SiLU(),
|
||||
nn.Linear(t_embed_dim, t_embed_dim, bias=True),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def timestep_embedding(t, dim, max_period=10000):
|
||||
"""
|
||||
Create sinusoidal timestep embeddings.
|
||||
:param t: a 1-D Tensor of N indices, one per batch element.
|
||||
These may be fractional.
|
||||
:param dim: the dimension of the output.
|
||||
:param max_period: controls the minimum frequency of the embeddings.
|
||||
:return: an (N, D) Tensor of positional embeddings.
|
||||
"""
|
||||
half = dim // 2
|
||||
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half)
|
||||
freqs = freqs.to(device=t.device)
|
||||
args = t[:, None].float() * freqs[None]
|
||||
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
||||
if dim % 2:
|
||||
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
||||
return embedding
|
||||
|
||||
def forward(self, t, dtype):
|
||||
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
||||
if t_freq.dtype != dtype:
|
||||
t_freq = t_freq.to(dtype)
|
||||
t_emb = self.mlp(t_freq)
|
||||
return t_emb
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,142 @@
|
||||
import cv2
|
||||
import math
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
def intrinsic_matrix_from_field_of_view(imshape, fov_degrees:float =55 ): # nlf default fov_degrees 55
|
||||
imshape = np.array(imshape)
|
||||
fov_radians = fov_degrees * np.array(np.pi / 180)
|
||||
larger_side = np.max(imshape)
|
||||
focal_length = larger_side / (np.tan(fov_radians / 2) * 2)
|
||||
# intrinsic_matrix 3*3
|
||||
return np.array([
|
||||
[focal_length, 0, imshape[1] / 2],
|
||||
[0, focal_length, imshape[0] / 2],
|
||||
[0, 0, 1],
|
||||
])
|
||||
|
||||
|
||||
def p3d_to_p2d(point_3d, height, width): # point3d n*1024*3
|
||||
camera_matrix = intrinsic_matrix_from_field_of_view((height,width))
|
||||
camera_matrix = np.expand_dims(camera_matrix, axis=0)
|
||||
camera_matrix = np.expand_dims(camera_matrix, axis=0) # 1*1*3*3
|
||||
point_3d = np.expand_dims(point_3d,axis=-1) # n*1024*3*1
|
||||
point_2d = (camera_matrix@point_3d).squeeze(-1)
|
||||
point_2d[:,:,:2] = point_2d[:,:,:2]/point_2d[:,:,2:3]
|
||||
return point_2d[:,:,:] # n*1024*2
|
||||
|
||||
|
||||
def get_pose_images(smpl_data, offset):
|
||||
pose_images = []
|
||||
for data in smpl_data:
|
||||
if isinstance(data, np.ndarray):
|
||||
joints3d = data
|
||||
else:
|
||||
joints3d = data.numpy()
|
||||
canvas = np.zeros(shape=(offset[0], offset[1], 3), dtype=np.uint8)
|
||||
joints3d = p3d_to_p2d(joints3d, offset[0], offset[1])
|
||||
canvas = draw_3d_points(canvas, joints3d[0], stickwidth=int(offset[1]/350))
|
||||
pose_images.append(Image.fromarray(canvas))
|
||||
return pose_images
|
||||
|
||||
|
||||
def get_control_conditions(poses, h, w):
|
||||
video_transforms = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
||||
control_images = []
|
||||
for idx, pose in enumerate(poses):
|
||||
canvas = np.zeros(shape=(h, w, 3), dtype=np.uint8)
|
||||
try:
|
||||
joints3d = p3d_to_p2d(pose, h, w)
|
||||
canvas = draw_3d_points(
|
||||
canvas,
|
||||
joints3d[0],
|
||||
stickwidth=int(h / 350),
|
||||
)
|
||||
resized_canvas = cv2.resize(canvas, (w, h))
|
||||
# Image.fromarray(resized_canvas).save(f'tmp/{idx}_pose.jpg')
|
||||
control_images.append(resized_canvas)
|
||||
except Exception as e:
|
||||
print("wrong:", e)
|
||||
control_images.append(Image.fromarray(canvas))
|
||||
control_pixel_values = np.array(control_images)
|
||||
control_pixel_values = torch.from_numpy(control_pixel_values).contiguous() / 255.
|
||||
print("control_pixel_values.shape", control_pixel_values.shape)
|
||||
#control_pixel_values = video_transforms(control_pixel_values)
|
||||
return control_pixel_values
|
||||
|
||||
|
||||
def draw_3d_points(canvas, points, stickwidth=2, r=2, draw_line=True):
|
||||
colors = [
|
||||
[255, 0, 0], # 0
|
||||
[0, 255, 0], # 1
|
||||
[0, 0, 255], # 2
|
||||
[255, 0, 255], # 3
|
||||
[255, 255, 0], # 4
|
||||
[85, 255, 0], # 5
|
||||
[0, 75, 255], # 6
|
||||
[0, 255, 85], # 7
|
||||
[0, 255, 170], # 8
|
||||
[170, 0, 255], # 9
|
||||
[85, 0, 255], # 10
|
||||
[0, 85, 255], # 11
|
||||
[0, 255, 255], # 12
|
||||
[85, 0, 255], # 13
|
||||
[170, 0, 255], # 14
|
||||
[255, 0, 255], # 15
|
||||
[255, 0, 170], # 16
|
||||
[255, 0, 85], # 17
|
||||
]
|
||||
connetions = [
|
||||
[15,12],[12, 16],[16, 18],[18, 20],[20, 22],
|
||||
[12,17],[17,19],[19,21],
|
||||
[21,23],[12,9],[9,6],
|
||||
[6,3],[3,0],[0,1],
|
||||
[1,4],[4,7],[7,10],[0,2],[2,5],[5,8],[8,11]
|
||||
]
|
||||
connection_colors = [
|
||||
[255, 0, 0], # 0
|
||||
[0, 255, 0], # 1
|
||||
[0, 0, 255], # 2
|
||||
[255, 255, 0], # 3
|
||||
[255, 0, 255], # 4
|
||||
[0, 255, 0], # 5
|
||||
[0, 85, 255], # 6
|
||||
[255, 175, 0], # 7
|
||||
[0, 0, 255], # 8
|
||||
[255, 85, 0], # 9
|
||||
[0, 255, 85], # 10
|
||||
[255, 0, 255], # 11
|
||||
[255, 0, 0], # 12
|
||||
[0, 175, 255], # 13
|
||||
[255, 255, 0], # 14
|
||||
[0, 0, 255], # 15
|
||||
[0, 255, 0], # 16
|
||||
]
|
||||
|
||||
# draw point
|
||||
for i in range(len(points)):
|
||||
x,y = points[i][0:2]
|
||||
x,y = int(x),int(y)
|
||||
if i==13 or i == 14:
|
||||
continue
|
||||
cv2.circle(canvas, (x, y), r, colors[i%17], thickness=-1)
|
||||
|
||||
# draw line
|
||||
if draw_line:
|
||||
for i in range(len(connetions)):
|
||||
point1_idx,point2_idx = connetions[i][0:2]
|
||||
point1 = points[point1_idx]
|
||||
point2 = points[point2_idx]
|
||||
Y = [point2[0],point1[0]]
|
||||
X = [point2[1],point1[1]]
|
||||
mX = int(np.mean(X))
|
||||
mY = int(np.mean(Y))
|
||||
length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
|
||||
angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
|
||||
polygon = cv2.ellipse2Poly((mY, mX), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
|
||||
cv2.fillConvexPoly(canvas, polygon, connection_colors[i%17])
|
||||
|
||||
return canvas
|
||||
@@ -0,0 +1 @@
|
||||
from .vqvae import SMPL_VQVAE, VectorQuantizer, Encoder, Decoder
|
||||
@@ -0,0 +1,329 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
|
||||
class Encoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels=3,
|
||||
mid_channels=[128, 512],
|
||||
out_channels=3072,
|
||||
downsample_time=[1, 1],
|
||||
downsample_joint=[1, 1],
|
||||
num_attention_heads=8,
|
||||
attention_head_dim=64,
|
||||
dim=3072,
|
||||
):
|
||||
super(Encoder, self).__init__()
|
||||
|
||||
self.conv_in = nn.Conv2d(in_channels, mid_channels[0], kernel_size=3, stride=1, padding=1)
|
||||
self.resnet1 = nn.ModuleList([ResBlock(mid_channels[0], mid_channels[0]) for _ in range(3)])
|
||||
self.downsample1 = Downsample(mid_channels[0], mid_channels[0], downsample_time[0], downsample_joint[0])
|
||||
self.resnet2 = ResBlock(mid_channels[0], mid_channels[1])
|
||||
self.resnet3 = nn.ModuleList([ResBlock(mid_channels[1], mid_channels[1]) for _ in range(3)])
|
||||
self.downsample2 = Downsample(mid_channels[1], mid_channels[1], downsample_time[1], downsample_joint[1])
|
||||
self.conv_out = nn.Conv2d(mid_channels[-1], out_channels, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv_in(x)
|
||||
for resnet in self.resnet1:
|
||||
x = resnet(x)
|
||||
x = self.downsample1(x)
|
||||
|
||||
x = self.resnet2(x)
|
||||
for resnet in self.resnet3:
|
||||
x = resnet(x)
|
||||
x = self.downsample2(x)
|
||||
|
||||
x = self.conv_out(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
class VectorQuantizer(nn.Module):
|
||||
def __init__(self, nb_code, code_dim):
|
||||
super().__init__()
|
||||
self.nb_code = nb_code
|
||||
self.code_dim = code_dim
|
||||
self.mu = 0.99
|
||||
self.reset_codebook()
|
||||
self.reset_count = 0
|
||||
self.usage = torch.zeros((self.nb_code, 1))
|
||||
|
||||
def reset_codebook(self):
|
||||
self.init = False
|
||||
self.code_sum = None
|
||||
self.code_count = None
|
||||
self.register_buffer('codebook', torch.zeros(self.nb_code, self.code_dim).cuda())
|
||||
|
||||
def _tile(self, x):
|
||||
nb_code_x, code_dim = x.shape
|
||||
if nb_code_x < self.nb_code:
|
||||
n_repeats = (self.nb_code + nb_code_x - 1) // nb_code_x
|
||||
std = 0.01 / np.sqrt(code_dim)
|
||||
out = x.repeat(n_repeats, 1)
|
||||
out = out + torch.randn_like(out) * std
|
||||
else:
|
||||
out = x
|
||||
return out
|
||||
|
||||
def preprocess(self, x):
|
||||
# [bs, c, f, j] -> [bs * f * j, c]
|
||||
x = x.permute(0, 2, 3, 1).contiguous()
|
||||
x = x.view(-1, x.shape[-1])
|
||||
return x
|
||||
|
||||
def quantize(self, x):
|
||||
# [bs * f * j, dim=3072]
|
||||
# Calculate latent code x_l
|
||||
k_w = self.codebook.t()
|
||||
distance = torch.sum(x ** 2, dim=-1, keepdim=True) - 2 * torch.matmul(x, k_w) + torch.sum(k_w ** 2, dim=0, keepdim=True)
|
||||
_, code_idx = torch.min(distance, dim=-1)
|
||||
return code_idx
|
||||
|
||||
def dequantize(self, code_idx):
|
||||
x = F.embedding(code_idx, self.codebook) # indexing: [bs * f * j, 32]
|
||||
return x
|
||||
|
||||
def forward(self, x, return_vq=False):
|
||||
bs, c, f, j = x.shape # SMPL data frames: [bs, 3072, f, j]
|
||||
|
||||
# Preprocess
|
||||
x = self.preprocess(x)
|
||||
# return x.view(bs, f*j, c).contiguous(), None
|
||||
assert x.shape[-1] == self.code_dim
|
||||
|
||||
# quantize and dequantize through bottleneck
|
||||
code_idx = self.quantize(x)
|
||||
x_d = self.dequantize(code_idx)
|
||||
|
||||
# Loss
|
||||
commit_loss = F.mse_loss(x, x_d.detach())
|
||||
|
||||
# Passthrough
|
||||
x_d = x + (x_d - x).detach()
|
||||
|
||||
if return_vq:
|
||||
return x_d.view(bs, f*j, c).contiguous(), commit_loss
|
||||
# return (x_d, x_d.view(bs, f, j, c).permute(0, 3, 1, 2).contiguous()), commit_loss, perplexity
|
||||
|
||||
# Postprocess
|
||||
x_d = x_d.view(bs, f, j, c).permute(0, 3, 1, 2).contiguous()
|
||||
|
||||
return x_d, commit_loss
|
||||
|
||||
|
||||
|
||||
|
||||
class Decoder(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels=3072,
|
||||
mid_channels=[512, 128],
|
||||
out_channels=3,
|
||||
upsample_rate=None,
|
||||
frame_upsample_rate=[1.0, 1.0],
|
||||
joint_upsample_rate=[1.0, 1.0],
|
||||
dim=128,
|
||||
attention_head_dim=64,
|
||||
num_attention_heads=8,
|
||||
):
|
||||
super(Decoder, self).__init__()
|
||||
|
||||
self.conv_in = nn.Conv2d(in_channels, mid_channels[0], kernel_size=3, stride=1, padding=1)
|
||||
self.resnet1 = nn.ModuleList([ResBlock(mid_channels[0], mid_channels[0]) for _ in range(3)])
|
||||
self.upsample1 = Upsample(mid_channels[0], mid_channels[0], frame_upsample_rate=frame_upsample_rate[0], joint_upsample_rate=joint_upsample_rate[0])
|
||||
self.resnet2 = ResBlock(mid_channels[0], mid_channels[1])
|
||||
self.resnet3 = nn.ModuleList([ResBlock(mid_channels[1], mid_channels[1]) for _ in range(3)])
|
||||
self.upsample2 = Upsample(mid_channels[1], mid_channels[1], frame_upsample_rate=frame_upsample_rate[1], joint_upsample_rate=joint_upsample_rate[1])
|
||||
self.conv_out = nn.Conv2d(mid_channels[-1], out_channels, kernel_size=3, stride=1, padding=1)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv_in(x)
|
||||
for resnet in self.resnet1:
|
||||
x = resnet(x)
|
||||
x = self.upsample1(x)
|
||||
|
||||
x = self.resnet2(x)
|
||||
for resnet in self.resnet3:
|
||||
x = resnet(x)
|
||||
x = self.upsample2(x)
|
||||
|
||||
x = self.conv_out(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class Upsample(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
upsample_rate=None,
|
||||
frame_upsample_rate=None,
|
||||
joint_upsample_rate=None,
|
||||
):
|
||||
super(Upsample, self).__init__()
|
||||
|
||||
self.upsampler = nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
||||
self.upsample_rate = upsample_rate
|
||||
self.frame_upsample_rate = frame_upsample_rate
|
||||
self.joint_upsample_rate = joint_upsample_rate
|
||||
self.upsample_rate = upsample_rate
|
||||
|
||||
def forward(self, inputs):
|
||||
if inputs.shape[2] > 1 and inputs.shape[2] % 2 == 1:
|
||||
# split first frame
|
||||
x_first, x_rest = inputs[:, :, 0], inputs[:, :, 1:]
|
||||
|
||||
if self.upsample_rate is not None:
|
||||
# import pdb; pdb.set_trace()
|
||||
x_first = F.interpolate(x_first, scale_factor=self.upsample_rate)
|
||||
x_rest = F.interpolate(x_rest, scale_factor=self.upsample_rate)
|
||||
else:
|
||||
# import pdb; pdb.set_trace()
|
||||
# x_first = F.interpolate(x_first, scale_factor=(self.frame_upsample_rate, self.joint_upsample_rate), mode="bilinear", align_corners=True)
|
||||
x_rest = F.interpolate(x_rest, scale_factor=(self.frame_upsample_rate, self.joint_upsample_rate), mode="bilinear", align_corners=True)
|
||||
x_first = x_first[:, :, None, :]
|
||||
inputs = torch.cat([x_first, x_rest], dim=2)
|
||||
elif inputs.shape[2] > 1:
|
||||
if self.upsample_rate is not None:
|
||||
inputs = F.interpolate(inputs, scale_factor=self.upsample_rate)
|
||||
else:
|
||||
inputs = F.interpolate(inputs, scale_factor=(self.frame_upsample_rate, self.joint_upsample_rate), mode="bilinear", align_corners=True)
|
||||
else:
|
||||
inputs = inputs.squeeze(2)
|
||||
if self.upsample_rate is not None:
|
||||
inputs = F.interpolate(inputs, scale_factor=self.upsample_rate)
|
||||
else:
|
||||
inputs = F.interpolate(inputs, scale_factor=(self.frame_upsample_rate, self.joint_upsample_rate), mode="linear", align_corners=True)
|
||||
inputs = inputs[:, :, None, :, :]
|
||||
|
||||
b, c, t, j = inputs.shape
|
||||
inputs = inputs.permute(0, 2, 1, 3).reshape(b * t, c, j)
|
||||
inputs = self.upsampler(inputs)
|
||||
inputs = inputs.reshape(b, t, *inputs.shape[1:]).permute(0, 2, 1, 3)
|
||||
|
||||
return inputs
|
||||
|
||||
|
||||
class Downsample(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
frame_downsample_rate,
|
||||
joint_downsample_rate
|
||||
):
|
||||
super(Downsample, self).__init__()
|
||||
|
||||
self.frame_downsample_rate = frame_downsample_rate
|
||||
self.joint_downsample_rate = joint_downsample_rate
|
||||
self.joint_downsample = nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=self.joint_downsample_rate, padding=1)
|
||||
|
||||
def forward(self, x):
|
||||
# (batch_size, channels, frames, joints) -> (batch_size * joints, channels, frames)
|
||||
if self.frame_downsample_rate > 1:
|
||||
batch_size, channels, frames, joints = x.shape
|
||||
x = x.permute(0, 3, 1, 2).reshape(batch_size * joints, channels, frames)
|
||||
if x.shape[-1] % 2 == 1:
|
||||
x_first, x_rest = x[..., 0], x[..., 1:]
|
||||
if x_rest.shape[-1] > 0:
|
||||
# (batch_size * height * width, channels, frames - 1) -> (batch_size * height * width, channels, (frames - 1) // 2)
|
||||
x_rest = F.avg_pool1d(x_rest, kernel_size=self.frame_downsample_rate, stride=self.frame_downsample_rate)
|
||||
|
||||
x = torch.cat([x_first[..., None], x_rest], dim=-1)
|
||||
# (batch_size * joints, channels, (frames // 2) + 1) -> (batch_size, channels, (frames // 2) + 1, joints)
|
||||
x = x.reshape(batch_size, joints, channels, x.shape[-1]).permute(0, 2, 3, 1)
|
||||
else:
|
||||
# (batch_size * joints, channels, frames) -> (batch_size * joints, channels, frames // 2)
|
||||
x = F.avg_pool1d(x, kernel_size=2, stride=2)
|
||||
# (batch_size * joints, channels, frames // 2) -> (batch_size, height, width, channels, frames // 2) -> (batch_size, channels, frames // 2, height, width)
|
||||
x = x.reshape(batch_size, joints, channels, x.shape[-1]).permute(0, 2, 3, 1)
|
||||
|
||||
# Pad the tensor
|
||||
# pad = (0, 1)
|
||||
# x = F.pad(x, pad, mode="constant", value=0)
|
||||
batch_size, channels, frames, joints = x.shape
|
||||
# (batch_size, channels, frames, joints) -> (batch_size * frames, channels, joints)
|
||||
x = x.permute(0, 2, 1, 3).reshape(batch_size * frames, channels, joints)
|
||||
x = self.joint_downsample(x)
|
||||
# (batch_size * frames, channels, joints) -> (batch_size, channels, frames, joints)
|
||||
x = x.reshape(batch_size, frames, x.shape[1], x.shape[2]).permute(0, 2, 1, 3)
|
||||
return x
|
||||
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
def __init__(self,
|
||||
in_channels,
|
||||
out_channels,
|
||||
group_num=32,
|
||||
max_channels=512):
|
||||
super(ResBlock, self).__init__()
|
||||
skip = max(1, max_channels // out_channels - 1)
|
||||
self.block = nn.Sequential(
|
||||
nn.GroupNorm(group_num, in_channels, eps=1e-06, affine=True),
|
||||
nn.SiLU(),
|
||||
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=skip, dilation=skip),
|
||||
nn.GroupNorm(group_num, out_channels, eps=1e-06, affine=True),
|
||||
nn.SiLU(),
|
||||
nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, padding=0),
|
||||
)
|
||||
self.conv_short = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) if in_channels != out_channels else nn.Identity()
|
||||
|
||||
def forward(self, x):
|
||||
hidden_states = self.block(x)
|
||||
if hidden_states.shape != x.shape:
|
||||
x = self.conv_short(x)
|
||||
x = x + hidden_states
|
||||
return x
|
||||
|
||||
|
||||
|
||||
class SMPL_VQVAE(nn.Module):
|
||||
def __init__(self, encoder, decoder, vq):
|
||||
super(SMPL_VQVAE, self).__init__()
|
||||
|
||||
self.encoder = encoder
|
||||
self.decoder = decoder
|
||||
self.vq = vq
|
||||
|
||||
def to(self, device):
|
||||
self.encoder = self.encoder.to(device)
|
||||
self.decoder = self.decoder.to(device)
|
||||
self.vq = self.vq.to(device)
|
||||
self.device = device
|
||||
return self
|
||||
|
||||
def encdec_slice_frames(self, x, frame_batch_size, encdec, return_vq):
|
||||
num_frames = x.shape[2]
|
||||
remaining_frames = num_frames % frame_batch_size
|
||||
x_output = []
|
||||
|
||||
for i in range(num_frames // frame_batch_size):
|
||||
remaining_frames = num_frames % frame_batch_size
|
||||
start_frame = frame_batch_size * i + (0 if i == 0 else remaining_frames)
|
||||
end_frame = frame_batch_size * (i + 1) + remaining_frames
|
||||
x_intermediate = x[:, :, start_frame:end_frame]
|
||||
x_intermediate = encdec(x_intermediate)
|
||||
x_output.append(x_intermediate)
|
||||
if encdec == self.encoder and self.vq is not None:
|
||||
x_output, loss = self.vq(torch.cat(x_output, dim=2), return_vq=return_vq)
|
||||
return x_output, loss
|
||||
else:
|
||||
return torch.cat(x_output, dim=2), None, None
|
||||
|
||||
def forward(self, x, return_vq=False):
|
||||
x = x.permute(0, 3, 1, 2)
|
||||
x, loss = self.encdec_slice_frames(x, frame_batch_size=8, encdec=self.encoder, return_vq=return_vq)
|
||||
|
||||
if return_vq:
|
||||
return x, loss
|
||||
x, _, _ = self.encdec_slice_frames(x, frame_batch_size=2, encdec=self.decoder, return_vq=return_vq)
|
||||
x = x.permute(0, 2, 3, 1)
|
||||
|
||||
return x, loss
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
import torch
|
||||
import numpy as np
|
||||
from typing import Union, Tuple
|
||||
|
||||
|
||||
def get_1d_rotary_pos_embed(
|
||||
dim: int,
|
||||
pos: Union[np.ndarray, int],
|
||||
theta: float = 10000.0,
|
||||
use_real=False,
|
||||
linear_factor=1.0,
|
||||
ntk_factor=1.0,
|
||||
repeat_interleave_real=True,
|
||||
freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
|
||||
):
|
||||
"""
|
||||
Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
|
||||
|
||||
This function calculates a frequency tensor with complex exponentials using the given dimension 'dim' and the end
|
||||
index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64
|
||||
data type.
|
||||
|
||||
Args:
|
||||
dim (`int`): Dimension of the frequency tensor.
|
||||
pos (`np.ndarray` or `int`): Position indices for the frequency tensor. [S] or scalar
|
||||
theta (`float`, *optional*, defaults to 10000.0):
|
||||
Scaling factor for frequency computation. Defaults to 10000.0.
|
||||
use_real (`bool`, *optional*):
|
||||
If True, return real part and imaginary part separately. Otherwise, return complex numbers.
|
||||
linear_factor (`float`, *optional*, defaults to 1.0):
|
||||
Scaling factor for the context extrapolation. Defaults to 1.0.
|
||||
ntk_factor (`float`, *optional*, defaults to 1.0):
|
||||
Scaling factor for the NTK-Aware RoPE. Defaults to 1.0.
|
||||
repeat_interleave_real (`bool`, *optional*, defaults to `True`):
|
||||
If `True` and `use_real`, real part and imaginary part are each interleaved with themselves to reach `dim`.
|
||||
Otherwise, they are concateanted with themselves.
|
||||
freqs_dtype (`torch.float32` or `torch.float64`, *optional*, defaults to `torch.float32`):
|
||||
the dtype of the frequency tensor.
|
||||
Returns:
|
||||
`torch.Tensor`: Precomputed frequency tensor with complex exponentials. [S, D/2]
|
||||
"""
|
||||
assert dim % 2 == 0
|
||||
|
||||
if isinstance(pos, int):
|
||||
pos = torch.arange(pos)
|
||||
if isinstance(pos, np.ndarray):
|
||||
pos = torch.from_numpy(pos) # type: ignore # [S]
|
||||
|
||||
theta = theta * ntk_factor
|
||||
freqs = (
|
||||
1.0
|
||||
/ (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[: (dim // 2)] / dim))
|
||||
/ linear_factor
|
||||
) # [D/2]
|
||||
freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
|
||||
if use_real and repeat_interleave_real:
|
||||
freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
|
||||
freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
|
||||
return freqs_cos, freqs_sin
|
||||
elif use_real:
|
||||
freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float() # [S, D]
|
||||
freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float() # [S, D]
|
||||
return freqs_cos, freqs_sin
|
||||
else:
|
||||
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
|
||||
return freqs_cis
|
||||
|
||||
|
||||
def get_3d_rotary_pos_embed(
|
||||
embed_dim, crops_coords, grid_size, temporal_size, theta: int = 10000, use_real: bool = True
|
||||
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
||||
"""
|
||||
RoPE for video tokens with 3D structure.
|
||||
|
||||
Args:
|
||||
embed_dim: (`int`):
|
||||
The embedding dimension size, corresponding to hidden_size_head.
|
||||
crops_coords (`Tuple[int]`):
|
||||
The top-left and bottom-right coordinates of the crop.
|
||||
grid_size (`Tuple[int]`):
|
||||
The grid size of the spatial positional embedding (height, width).
|
||||
temporal_size (`int`):
|
||||
The size of the temporal dimension.
|
||||
theta (`float`):
|
||||
Scaling factor for frequency computation.
|
||||
|
||||
Returns:
|
||||
`torch.Tensor`: positional embedding with shape `(temporal_size * grid_size[0] * grid_size[1], embed_dim/2)`.
|
||||
"""
|
||||
if use_real is not True:
|
||||
raise ValueError(" `use_real = False` is not currently supported for get_3d_rotary_pos_embed")
|
||||
start, stop = crops_coords
|
||||
grid_size_h, grid_size_w = grid_size
|
||||
grid_h = np.linspace(start[0], stop[0], grid_size_h, endpoint=False, dtype=np.float32)
|
||||
grid_w = np.linspace(start[1], stop[1], grid_size_w, endpoint=False, dtype=np.float32)
|
||||
grid_t = np.linspace(0, temporal_size, temporal_size, endpoint=False, dtype=np.float32)
|
||||
|
||||
# Compute dimensions for each axis
|
||||
dim_t = embed_dim // 4
|
||||
dim_h = embed_dim // 8 * 3
|
||||
dim_w = embed_dim // 8 * 3
|
||||
|
||||
# Temporal frequencies
|
||||
freqs_t = get_1d_rotary_pos_embed(dim_t, grid_t, use_real=True)
|
||||
# Spatial frequencies for height and width
|
||||
freqs_h = get_1d_rotary_pos_embed(dim_h, grid_h, use_real=True)
|
||||
freqs_w = get_1d_rotary_pos_embed(dim_w, grid_w, use_real=True)
|
||||
|
||||
# BroadCast and concatenate temporal and spaial frequencie (height and width) into a 3d tensor
|
||||
def combine_time_height_width(freqs_t, freqs_h, freqs_w):
|
||||
freqs_t = freqs_t[:, None, None, :].expand(
|
||||
-1, grid_size_h, grid_size_w, -1
|
||||
) # temporal_size, grid_size_h, grid_size_w, dim_t
|
||||
freqs_h = freqs_h[None, :, None, :].expand(
|
||||
temporal_size, -1, grid_size_w, -1
|
||||
) # temporal_size, grid_size_h, grid_size_2, dim_h
|
||||
freqs_w = freqs_w[None, None, :, :].expand(
|
||||
temporal_size, grid_size_h, -1, -1
|
||||
) # temporal_size, grid_size_h, grid_size_2, dim_w
|
||||
|
||||
freqs = torch.cat(
|
||||
[freqs_t, freqs_h, freqs_w], dim=-1
|
||||
) # temporal_size, grid_size_h, grid_size_w, (dim_t + dim_h + dim_w)
|
||||
freqs = freqs.view(
|
||||
temporal_size * grid_size_h * grid_size_w, -1
|
||||
) # (temporal_size * grid_size_h * grid_size_w), (dim_t + dim_h + dim_w)
|
||||
return freqs
|
||||
|
||||
t_cos, t_sin = freqs_t # both t_cos and t_sin has shape: temporal_size, dim_t
|
||||
h_cos, h_sin = freqs_h # both h_cos and h_sin has shape: grid_size_h, dim_h
|
||||
w_cos, w_sin = freqs_w # both w_cos and w_sin has shape: grid_size_w, dim_w
|
||||
cos = combine_time_height_width(t_cos, h_cos, w_cos)
|
||||
sin = combine_time_height_width(t_sin, h_sin, w_sin)
|
||||
return cos, sin
|
||||
|
||||
|
||||
def get_3d_motion_spatial_embed(
|
||||
embed_dim: int, num_joints: int, joints_mean: np.ndarray, joints_std: np.ndarray, theta: float = 10000.0
|
||||
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
||||
assert embed_dim % 2 == 0 and embed_dim % 3 == 0
|
||||
|
||||
def create_rope_pe(dim, pos, freqs_dtype=torch.float32):
|
||||
if isinstance(pos, np.ndarray):
|
||||
pos = torch.from_numpy(pos)
|
||||
freqs = (
|
||||
1.0
|
||||
/ (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[: (dim // 2)] / dim))
|
||||
) # [D/2]
|
||||
freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
|
||||
freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
|
||||
freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
|
||||
return freqs_cos, freqs_sin
|
||||
|
||||
pos_x = joints_mean[:, 0]
|
||||
pos_y = joints_mean[:, 1]
|
||||
pos_z = joints_mean[:, 2]
|
||||
|
||||
normalized_pos_x = (pos_x - pos_x.mean())
|
||||
normalized_pos_y = (pos_y - pos_y.mean())
|
||||
normalized_pos_z = (pos_z - pos_z.mean())
|
||||
|
||||
freqs_cos_x, freqs_sin_x = create_rope_pe(embed_dim // 3, normalized_pos_x)
|
||||
freqs_cos_y, freqs_sin_y = create_rope_pe(embed_dim // 3, normalized_pos_y)
|
||||
freqs_cos_z, freqs_sin_z = create_rope_pe(embed_dim // 3, normalized_pos_z)
|
||||
|
||||
freqs_cos = torch.cat([freqs_cos_x, freqs_cos_y, freqs_cos_z], dim=-1)
|
||||
freqs_sin = torch.cat([freqs_sin_x, freqs_sin_y, freqs_sin_z], dim=-1)
|
||||
|
||||
return freqs_cos, freqs_sin
|
||||
|
||||
def prepare_motion_embeddings(num_frames, num_joints, joints_mean, joints_std, theta=10000, device='cuda'):
|
||||
time_embed = get_1d_rotary_pos_embed(44, num_frames, theta, use_real=True)
|
||||
time_embed_cos = time_embed[0][:, None, :].expand(-1, num_joints, -1).reshape(num_frames*num_joints, -1)
|
||||
time_embed_sin = time_embed[1][:, None, :].expand(-1, num_joints, -1).reshape(num_frames*num_joints, -1)
|
||||
spatial_motion_embed = get_3d_motion_spatial_embed(84, num_joints, joints_mean, joints_std, theta)
|
||||
spatial_embed_cos = spatial_motion_embed[0][None, :, :].expand(num_frames, -1, -1).reshape(num_frames*num_joints, -1)
|
||||
spatial_embed_sin = spatial_motion_embed[1][None, :, :].expand(num_frames, -1, -1).reshape(num_frames*num_joints, -1)
|
||||
motion_embed_cos = torch.cat([time_embed_cos, spatial_embed_cos], dim=-1).to(device=device)
|
||||
motion_embed_sin = torch.cat([time_embed_sin, spatial_embed_sin], dim=-1).to(device=device)
|
||||
return motion_embed_cos, motion_embed_sin
|
||||
|
||||
def apply_rotary_emb(x, freqs_cis):
|
||||
cos, sin = freqs_cis # [S, D]
|
||||
cos = cos[None, None]
|
||||
sin = sin[None, None]
|
||||
cos, sin = cos.to(x.device), sin.to(x.device)
|
||||
|
||||
x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
|
||||
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
|
||||
|
||||
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
|
||||
|
||||
return out
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
import os
|
||||
import torch
|
||||
import gc
|
||||
from ..utils import log, dict_to_device
|
||||
import numpy as np
|
||||
from accelerate import init_empty_weights
|
||||
from accelerate.utils import set_module_tensor_to_device
|
||||
|
||||
import comfy.model_management as mm
|
||||
from comfy.utils import load_torch_file
|
||||
import folder_paths
|
||||
|
||||
script_directory = os.path.dirname(os.path.abspath(__file__))
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
|
||||
local_model_path = os.path.join(folder_paths.models_dir, "nlf", "nlf_l_multi_0.3.2.torchscript")
|
||||
|
||||
from .motion4d import SMPL_VQVAE, VectorQuantizer, Encoder, Decoder
|
||||
from .mtv import prepare_motion_embeddings
|
||||
|
||||
class DownloadAndLoadNLFModel:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"url": (
|
||||
[
|
||||
"https://github.com/isarandi/nlf/releases/download/v0.3.2/nlf_l_multi_0.3.2.torchscript"
|
||||
],
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NLFMODEL",)
|
||||
RETURN_NAMES = ("nlf_model", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def loadmodel(self, url):
|
||||
|
||||
if not os.path.exists(local_model_path):
|
||||
log.info(f"Downloading NLF model to: {local_model_path}")
|
||||
import requests
|
||||
os.makedirs(os.path.dirname(local_model_path), exist_ok=True)
|
||||
response = requests.get(url)
|
||||
if response.status_code == 200:
|
||||
with open(local_model_path, "wb") as f:
|
||||
f.write(response.content)
|
||||
else:
|
||||
print("Failed to download file:", response.status_code)
|
||||
|
||||
model = torch.jit.load(local_model_path).eval()
|
||||
|
||||
return (model,)
|
||||
|
||||
class LoadNLFModel:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"path": ("STRING", {"default": local_model_path}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NLFMODEL",)
|
||||
RETURN_NAMES = ("nlf_model", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def loadmodel(self, path):
|
||||
model = torch.jit.load(path).eval()
|
||||
|
||||
return model,
|
||||
|
||||
class LoadVQVAE:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model_name": (folder_paths.get_filename_list("vae"), {"tooltip": "These models are loaded from 'ComfyUI/models/vae'"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("VQVAE",)
|
||||
RETURN_NAMES = ("vqvae", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def loadmodel(self, model_name):
|
||||
model_path = folder_paths.get_full_path("vae", model_name)
|
||||
vae_sd = load_torch_file(model_path, safe_load=True)
|
||||
|
||||
# Get motion tokenizer
|
||||
motion_encoder = Encoder(
|
||||
in_channels=3,
|
||||
mid_channels=[128, 512],
|
||||
out_channels=3072,
|
||||
downsample_time=[2, 2],
|
||||
downsample_joint=[1, 1]
|
||||
)
|
||||
motion_quant = VectorQuantizer(nb_code=8192, code_dim=3072)
|
||||
motion_decoder = Decoder(
|
||||
in_channels=3072,
|
||||
mid_channels=[512, 128],
|
||||
out_channels=3,
|
||||
upsample_rate=2.0,
|
||||
frame_upsample_rate=[2.0, 2.0],
|
||||
joint_upsample_rate=[1.0, 1.0]
|
||||
)
|
||||
|
||||
vqvae = SMPL_VQVAE(motion_encoder, motion_decoder, motion_quant).to(device)
|
||||
vqvae.load_state_dict(vae_sd, strict=True)
|
||||
|
||||
return vqvae,
|
||||
|
||||
class MTVCrafterEncodePoses:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"vqvae": ("VQVAE", {"tooltip": "VQVAE model"}),
|
||||
"poses": ("NLFPRED", {"tooltip": "Input poses for the model"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MTVCRAFTERMOTION", "NLFPRED")
|
||||
RETURN_NAMES = ("mtvcrafter_motion", "pose_results")
|
||||
FUNCTION = "encode"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def encode(self, vqvae, poses):
|
||||
|
||||
# import pickle
|
||||
# with open(os.path.join(script_directory, "data", "sampled_data.pkl"), 'rb') as f:
|
||||
# data_list = pickle.load(f)
|
||||
# if not isinstance(data_list, list):
|
||||
# data_list = [data_list]
|
||||
# print(data_list)
|
||||
|
||||
# smpl_poses = data_list[1]['pose']
|
||||
|
||||
global_mean = np.load(os.path.join(script_directory, "data", "mean.npy")) #global_mean.shape: (24, 3)
|
||||
global_std = np.load(os.path.join(script_directory, "data", "std.npy"))
|
||||
|
||||
smpl_poses = []
|
||||
for pose in poses['joints3d_nonparam'][0]:
|
||||
smpl_poses.append(pose[0].cpu().numpy())
|
||||
smpl_poses = np.array(smpl_poses)
|
||||
|
||||
norm_poses = torch.tensor((smpl_poses - global_mean) / global_std).unsqueeze(0)
|
||||
print(f"norm_poses shape: {norm_poses.shape}, dtype: {norm_poses.dtype}")
|
||||
|
||||
vqvae.to(device)
|
||||
motion_tokens, vq_loss = vqvae(norm_poses.to(device), return_vq=True)
|
||||
|
||||
recon_motion = vqvae(norm_poses.to(device))[0][0].to(dtype=torch.float32).cpu().detach() * global_std + global_mean
|
||||
vqvae.to(offload_device)
|
||||
|
||||
poses_dict = {
|
||||
'mtv_motion_tokens': motion_tokens,
|
||||
'global_mean': global_mean,
|
||||
'global_std': global_std
|
||||
}
|
||||
|
||||
return poses_dict, recon_motion
|
||||
|
||||
|
||||
class NLFPredict:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"model": ("NLFMODEL",),
|
||||
"images": ("IMAGE", {"tooltip": "Input images for the model"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NLFPRED", )
|
||||
RETURN_NAMES = ("pose_results",)
|
||||
FUNCTION = "predict"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def predict(self, model, images):
|
||||
|
||||
model.to(device)
|
||||
pred = model.detect_smpl_batched(images.permute(0, 3, 1, 2).to(device))
|
||||
model.to(offload_device)
|
||||
|
||||
pred = dict_to_device(pred, offload_device)
|
||||
|
||||
pose_results = {
|
||||
'joints3d_nonparam': [],
|
||||
}
|
||||
# Collect pose data
|
||||
for key in pose_results.keys():
|
||||
if key in pred:
|
||||
pose_results[key].append(pred[key])
|
||||
else:
|
||||
pose_results[key].append(None)
|
||||
|
||||
return (pose_results,)
|
||||
|
||||
class DrawNLFPoses:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"poses": ("NLFPRED", {"tooltip": "Input poses for the model"}),
|
||||
"width": ("INT", {"default": 512}),
|
||||
"height": ("INT", {"default": 512}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", )
|
||||
RETURN_NAMES = ("image",)
|
||||
FUNCTION = "predict"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def predict(self, poses, width, height):
|
||||
from .draw_pose import get_control_conditions
|
||||
print(type(poses))
|
||||
if isinstance(poses, dict):
|
||||
pose_input = poses['joints3d_nonparam'][0] if 'joints3d_nonparam' in poses else poses
|
||||
else:
|
||||
pose_input = poses
|
||||
control_conditions = get_control_conditions(pose_input, height, width)
|
||||
|
||||
return (control_conditions,)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"DownloadAndLoadNLFModel": DownloadAndLoadNLFModel,
|
||||
"NLFPredict": NLFPredict,
|
||||
"DrawNLFPoses": DrawNLFPoses,
|
||||
"LoadVQVAE": LoadVQVAE,
|
||||
"MTVCrafterEncodePoses": MTVCrafterEncodePoses
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"DownloadAndLoadNLFModel": "(Download)Load NLF Model",
|
||||
"NLFPredict": "NLF Predict",
|
||||
"DrawNLFPoses": "Draw NLF Poses",
|
||||
"LoadVQVAE": "Load VQVAE",
|
||||
"MTVCrafterEncodePoses": "MTV Crafter Encode Poses"
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
class ChannelLastConv1d(nn.Conv1d):
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = x.permute(0, 2, 1)
|
||||
x = super().forward(x)
|
||||
x = x.permute(0, 2, 1)
|
||||
return x
|
||||
|
||||
|
||||
class ConvMLP(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
hidden_dim: int,
|
||||
multiple_of: int = 256,
|
||||
kernel_size: int = 3,
|
||||
padding: int = 1,
|
||||
):
|
||||
"""
|
||||
Initialize the FeedForward module.
|
||||
|
||||
Args:
|
||||
dim (int): Input dimension.
|
||||
hidden_dim (int): Hidden dimension of the feedforward layer.
|
||||
multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
|
||||
|
||||
Attributes:
|
||||
w1 (ColumnParallelLinear): Linear transformation for the first layer.
|
||||
w2 (RowParallelLinear): Linear transformation for the second layer.
|
||||
w3 (ColumnParallelLinear): Linear transformation for the third layer.
|
||||
|
||||
"""
|
||||
super().__init__()
|
||||
hidden_dim = int(2 * hidden_dim / 3)
|
||||
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
|
||||
|
||||
self.w1 = ChannelLastConv1d(dim, hidden_dim, bias=False, kernel_size=kernel_size, padding=padding)
|
||||
self.w2 = ChannelLastConv1d(hidden_dim, dim, bias=False, kernel_size=kernel_size, padding=padding)
|
||||
self.w3 = ChannelLastConv1d(dim, hidden_dim, bias=False, kernel_size=kernel_size, padding=padding)
|
||||
|
||||
def forward(self, x):
|
||||
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 NVIDIA CORPORATION.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
from .bigvgan import BigVGAN
|
||||
@@ -0,0 +1,120 @@
|
||||
# Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import torch
|
||||
from torch import nn, sin, pow
|
||||
from torch.nn import Parameter
|
||||
|
||||
|
||||
class Snake(nn.Module):
|
||||
'''
|
||||
Implementation of a sine-based periodic activation function
|
||||
Shape:
|
||||
- Input: (B, C, T)
|
||||
- Output: (B, C, T), same shape as the input
|
||||
Parameters:
|
||||
- alpha - trainable parameter
|
||||
References:
|
||||
- This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
||||
https://arxiv.org/abs/2006.08195
|
||||
Examples:
|
||||
>>> a1 = snake(256)
|
||||
>>> x = torch.randn(256)
|
||||
>>> x = a1(x)
|
||||
'''
|
||||
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
||||
'''
|
||||
Initialization.
|
||||
INPUT:
|
||||
- in_features: shape of the input
|
||||
- alpha: trainable parameter
|
||||
alpha is initialized to 1 by default, higher values = higher-frequency.
|
||||
alpha will be trained along with the rest of your model.
|
||||
'''
|
||||
super(Snake, self).__init__()
|
||||
self.in_features = in_features
|
||||
|
||||
# initialize alpha
|
||||
self.alpha_logscale = alpha_logscale
|
||||
if self.alpha_logscale: # log scale alphas initialized to zeros
|
||||
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
||||
else: # linear scale alphas initialized to ones
|
||||
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
||||
|
||||
self.alpha.requires_grad = alpha_trainable
|
||||
|
||||
self.no_div_by_zero = 0.000000001
|
||||
|
||||
def forward(self, x):
|
||||
'''
|
||||
Forward pass of the function.
|
||||
Applies the function to the input elementwise.
|
||||
Snake ∶= x + 1/a * sin^2 (xa)
|
||||
'''
|
||||
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
||||
if self.alpha_logscale:
|
||||
alpha = torch.exp(alpha)
|
||||
x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class SnakeBeta(nn.Module):
|
||||
'''
|
||||
A modified Snake function which uses separate parameters for the magnitude of the periodic components
|
||||
Shape:
|
||||
- Input: (B, C, T)
|
||||
- Output: (B, C, T), same shape as the input
|
||||
Parameters:
|
||||
- alpha - trainable parameter that controls frequency
|
||||
- beta - trainable parameter that controls magnitude
|
||||
References:
|
||||
- This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
||||
https://arxiv.org/abs/2006.08195
|
||||
Examples:
|
||||
>>> a1 = snakebeta(256)
|
||||
>>> x = torch.randn(256)
|
||||
>>> x = a1(x)
|
||||
'''
|
||||
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
||||
'''
|
||||
Initialization.
|
||||
INPUT:
|
||||
- in_features: shape of the input
|
||||
- alpha - trainable parameter that controls frequency
|
||||
- beta - trainable parameter that controls magnitude
|
||||
alpha is initialized to 1 by default, higher values = higher-frequency.
|
||||
beta is initialized to 1 by default, higher values = higher-magnitude.
|
||||
alpha will be trained along with the rest of your model.
|
||||
'''
|
||||
super(SnakeBeta, self).__init__()
|
||||
self.in_features = in_features
|
||||
|
||||
# initialize alpha
|
||||
self.alpha_logscale = alpha_logscale
|
||||
if self.alpha_logscale: # log scale alphas initialized to zeros
|
||||
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
||||
self.beta = Parameter(torch.zeros(in_features) * alpha)
|
||||
else: # linear scale alphas initialized to ones
|
||||
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
||||
self.beta = Parameter(torch.ones(in_features) * alpha)
|
||||
|
||||
self.alpha.requires_grad = alpha_trainable
|
||||
self.beta.requires_grad = alpha_trainable
|
||||
|
||||
self.no_div_by_zero = 0.000000001
|
||||
|
||||
def forward(self, x):
|
||||
'''
|
||||
Forward pass of the function.
|
||||
Applies the function to the input elementwise.
|
||||
SnakeBeta ∶= x + 1/b * sin^2 (xa)
|
||||
'''
|
||||
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
||||
beta = self.beta.unsqueeze(0).unsqueeze(-1)
|
||||
if self.alpha_logscale:
|
||||
alpha = torch.exp(alpha)
|
||||
beta = torch.exp(beta)
|
||||
x = x + (1.0 / (beta + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
||||
|
||||
return x
|
||||
@@ -0,0 +1,6 @@
|
||||
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
from .filter import *
|
||||
from .resample import *
|
||||
from .act import *
|
||||
@@ -0,0 +1,28 @@
|
||||
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import torch.nn as nn
|
||||
from .resample import UpSample1d, DownSample1d
|
||||
|
||||
|
||||
class Activation1d(nn.Module):
|
||||
def __init__(self,
|
||||
activation,
|
||||
up_ratio: int = 2,
|
||||
down_ratio: int = 2,
|
||||
up_kernel_size: int = 12,
|
||||
down_kernel_size: int = 12):
|
||||
super().__init__()
|
||||
self.up_ratio = up_ratio
|
||||
self.down_ratio = down_ratio
|
||||
self.act = activation
|
||||
self.upsample = UpSample1d(up_ratio, up_kernel_size)
|
||||
self.downsample = DownSample1d(down_ratio, down_kernel_size)
|
||||
|
||||
# x: [B,C,T]
|
||||
def forward(self, x):
|
||||
x = self.upsample(x)
|
||||
x = self.act(x)
|
||||
x = self.downsample(x)
|
||||
|
||||
return x
|
||||
@@ -0,0 +1,95 @@
|
||||
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import math
|
||||
|
||||
if 'sinc' in dir(torch):
|
||||
sinc = torch.sinc
|
||||
else:
|
||||
# This code is adopted from adefossez's julius.core.sinc under the MIT License
|
||||
# https://adefossez.github.io/julius/julius/core.html
|
||||
# LICENSE is in incl_licenses directory.
|
||||
def sinc(x: torch.Tensor):
|
||||
"""
|
||||
Implementation of sinc, i.e. sin(pi * x) / (pi * x)
|
||||
__Warning__: Different to julius.sinc, the input is multiplied by `pi`!
|
||||
"""
|
||||
return torch.where(x == 0,
|
||||
torch.tensor(1., device=x.device, dtype=x.dtype),
|
||||
torch.sin(math.pi * x) / math.pi / x)
|
||||
|
||||
|
||||
# This code is adopted from adefossez's julius.lowpass.LowPassFilters under the MIT License
|
||||
# https://adefossez.github.io/julius/julius/lowpass.html
|
||||
# LICENSE is in incl_licenses directory.
|
||||
def kaiser_sinc_filter1d(cutoff, half_width, kernel_size): # return filter [1,1,kernel_size]
|
||||
even = (kernel_size % 2 == 0)
|
||||
half_size = kernel_size // 2
|
||||
|
||||
#For kaiser window
|
||||
delta_f = 4 * half_width
|
||||
A = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95
|
||||
if A > 50.:
|
||||
beta = 0.1102 * (A - 8.7)
|
||||
elif A >= 21.:
|
||||
beta = 0.5842 * (A - 21)**0.4 + 0.07886 * (A - 21.)
|
||||
else:
|
||||
beta = 0.
|
||||
window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
|
||||
|
||||
# ratio = 0.5/cutoff -> 2 * cutoff = 1 / ratio
|
||||
if even:
|
||||
time = (torch.arange(-half_size, half_size) + 0.5)
|
||||
else:
|
||||
time = torch.arange(kernel_size) - half_size
|
||||
if cutoff == 0:
|
||||
filter_ = torch.zeros_like(time)
|
||||
else:
|
||||
filter_ = 2 * cutoff * window * sinc(2 * cutoff * time)
|
||||
# Normalize filter to have sum = 1, otherwise we will have a small leakage
|
||||
# of the constant component in the input signal.
|
||||
filter_ /= filter_.sum()
|
||||
filter = filter_.view(1, 1, kernel_size)
|
||||
|
||||
return filter
|
||||
|
||||
|
||||
class LowPassFilter1d(nn.Module):
|
||||
def __init__(self,
|
||||
cutoff=0.5,
|
||||
half_width=0.6,
|
||||
stride: int = 1,
|
||||
padding: bool = True,
|
||||
padding_mode: str = 'replicate',
|
||||
kernel_size: int = 12):
|
||||
# kernel_size should be even number for stylegan3 setup,
|
||||
# in this implementation, odd number is also possible.
|
||||
super().__init__()
|
||||
if cutoff < -0.:
|
||||
raise ValueError("Minimum cutoff must be larger than zero.")
|
||||
if cutoff > 0.5:
|
||||
raise ValueError("A cutoff above 0.5 does not make sense.")
|
||||
self.kernel_size = kernel_size
|
||||
self.even = (kernel_size % 2 == 0)
|
||||
self.pad_left = kernel_size // 2 - int(self.even)
|
||||
self.pad_right = kernel_size // 2
|
||||
self.stride = stride
|
||||
self.padding = padding
|
||||
self.padding_mode = padding_mode
|
||||
filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size)
|
||||
self.register_buffer("filter", filter)
|
||||
|
||||
#input [B, C, T]
|
||||
def forward(self, x):
|
||||
_, C, _ = x.shape
|
||||
|
||||
if self.padding:
|
||||
x = F.pad(x, (self.pad_left, self.pad_right),
|
||||
mode=self.padding_mode)
|
||||
out = F.conv1d(x, self.filter.expand(C, -1, -1),
|
||||
stride=self.stride, groups=C)
|
||||
|
||||
return out
|
||||
@@ -0,0 +1,49 @@
|
||||
# Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import torch.nn as nn
|
||||
from torch.nn import functional as F
|
||||
from .filter import LowPassFilter1d
|
||||
from .filter import kaiser_sinc_filter1d
|
||||
|
||||
|
||||
class UpSample1d(nn.Module):
|
||||
def __init__(self, ratio=2, kernel_size=None):
|
||||
super().__init__()
|
||||
self.ratio = ratio
|
||||
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
|
||||
self.stride = ratio
|
||||
self.pad = self.kernel_size // ratio - 1
|
||||
self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
|
||||
self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
|
||||
filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio,
|
||||
half_width=0.6 / ratio,
|
||||
kernel_size=self.kernel_size)
|
||||
self.register_buffer("filter", filter)
|
||||
|
||||
# x: [B, C, T]
|
||||
def forward(self, x):
|
||||
_, C, _ = x.shape
|
||||
|
||||
x = F.pad(x, (self.pad, self.pad), mode='replicate')
|
||||
x = self.ratio * F.conv_transpose1d(
|
||||
x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
|
||||
x = x[..., self.pad_left:-self.pad_right]
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class DownSample1d(nn.Module):
|
||||
def __init__(self, ratio=2, kernel_size=None):
|
||||
super().__init__()
|
||||
self.ratio = ratio
|
||||
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
|
||||
self.lowpass = LowPassFilter1d(cutoff=0.5 / ratio,
|
||||
half_width=0.6 / ratio,
|
||||
stride=ratio,
|
||||
kernel_size=self.kernel_size)
|
||||
|
||||
def forward(self, x):
|
||||
xx = self.lowpass(x)
|
||||
|
||||
return xx
|
||||
@@ -0,0 +1,62 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from types import SimpleNamespace
|
||||
|
||||
from .models import BigVGANVocoder
|
||||
|
||||
from comfy.utils import load_torch_file
|
||||
|
||||
# BigVGAN vocoder configuration
|
||||
_bigvgan_vocoder_config = {
|
||||
'resblock': '1',
|
||||
'num_gpus': 0,
|
||||
'batch_size': 64,
|
||||
'num_mels': 80,
|
||||
'learning_rate': 0.0001,
|
||||
'adam_b1': 0.8,
|
||||
'adam_b2': 0.99,
|
||||
'lr_decay': 0.999,
|
||||
'seed': 1234,
|
||||
'upsample_rates': [4, 4, 2, 2, 2, 2],
|
||||
'upsample_kernel_sizes': [8, 8, 4, 4, 4, 4],
|
||||
'upsample_initial_channel': 1536,
|
||||
'resblock_kernel_sizes': [3, 7, 11],
|
||||
'resblock_dilation_sizes': [
|
||||
[1, 3, 5],
|
||||
[1, 3, 5],
|
||||
[1, 3, 5]
|
||||
],
|
||||
'activation': 'snakebeta',
|
||||
'snake_logscale': True,
|
||||
'resolutions': [
|
||||
[1024, 120, 600],
|
||||
[2048, 240, 1200],
|
||||
[512, 50, 240]
|
||||
],
|
||||
'mpd_reshapes': [2, 3, 5, 7, 11],
|
||||
'use_spectral_norm': False,
|
||||
'discriminator_channel_mult': 1,
|
||||
}
|
||||
|
||||
class BigVGAN(nn.Module):
|
||||
|
||||
def __init__(self, ckpt_path):
|
||||
super().__init__()
|
||||
# Convert dictionary to namespace object for attribute access
|
||||
vocoder_cfg = SimpleNamespace(**_bigvgan_vocoder_config)
|
||||
self.vocoder = BigVGANVocoder(vocoder_cfg).eval()
|
||||
vocoder_ckpt = load_torch_file(ckpt_path)
|
||||
self.vocoder.load_state_dict(vocoder_ckpt)
|
||||
|
||||
self.weight_norm_removed = False
|
||||
self.remove_weight_norm()
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, x):
|
||||
assert self.weight_norm_removed, 'call remove_weight_norm() before inference'
|
||||
return self.vocoder(x)
|
||||
|
||||
def remove_weight_norm(self):
|
||||
self.vocoder.remove_weight_norm()
|
||||
self.weight_norm_removed = True
|
||||
return self
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Jungil Kong
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Edward Dixon
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2019, Seungwon Park 박승원
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,16 @@
|
||||
Copyright 2020 Alexandre Défossez
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
||||
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or
|
||||
substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,255 @@
|
||||
# Copyright (c) 2022 NVIDIA CORPORATION.
|
||||
# Licensed under the MIT license.
|
||||
|
||||
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import Conv1d, ConvTranspose1d
|
||||
from torch.nn.utils.parametrizations import weight_norm
|
||||
from torch.nn.utils.parametrize import remove_parametrizations
|
||||
|
||||
from . import activations
|
||||
from .alias_free_torch import *
|
||||
from .utils import get_padding, init_weights
|
||||
|
||||
LRELU_SLOPE = 0.1
|
||||
|
||||
|
||||
class AMPBlock1(torch.nn.Module):
|
||||
|
||||
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5), activation=None):
|
||||
super(AMPBlock1, self).__init__()
|
||||
self.h = h
|
||||
|
||||
self.convs1 = nn.ModuleList([
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=dilation[0],
|
||||
padding=get_padding(kernel_size, dilation[0]))),
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=dilation[1],
|
||||
padding=get_padding(kernel_size, dilation[1]))),
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=dilation[2],
|
||||
padding=get_padding(kernel_size, dilation[2])))
|
||||
])
|
||||
self.convs1.apply(init_weights)
|
||||
|
||||
self.convs2 = nn.ModuleList([
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=1,
|
||||
padding=get_padding(kernel_size, 1))),
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=1,
|
||||
padding=get_padding(kernel_size, 1))),
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=1,
|
||||
padding=get_padding(kernel_size, 1)))
|
||||
])
|
||||
self.convs2.apply(init_weights)
|
||||
|
||||
self.num_layers = len(self.convs1) + len(self.convs2) # total number of conv layers
|
||||
|
||||
if activation == 'snake': # periodic nonlinearity with snake function and anti-aliasing
|
||||
self.activations = nn.ModuleList([
|
||||
Activation1d(
|
||||
activation=activations.Snake(channels, alpha_logscale=h.snake_logscale))
|
||||
for _ in range(self.num_layers)
|
||||
])
|
||||
elif activation == 'snakebeta': # periodic nonlinearity with snakebeta function and anti-aliasing
|
||||
self.activations = nn.ModuleList([
|
||||
Activation1d(
|
||||
activation=activations.SnakeBeta(channels, alpha_logscale=h.snake_logscale))
|
||||
for _ in range(self.num_layers)
|
||||
])
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"activation incorrectly specified. check the config file and look for 'activation'."
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
acts1, acts2 = self.activations[::2], self.activations[1::2]
|
||||
for c1, c2, a1, a2 in zip(self.convs1, self.convs2, acts1, acts2):
|
||||
xt = a1(x)
|
||||
xt = c1(xt)
|
||||
xt = a2(xt)
|
||||
xt = c2(xt)
|
||||
x = xt + x
|
||||
|
||||
return x
|
||||
|
||||
def remove_weight_norm(self):
|
||||
for l in self.convs1:
|
||||
remove_parametrizations(l, 'weight')
|
||||
for l in self.convs2:
|
||||
remove_parametrizations(l, 'weight')
|
||||
|
||||
|
||||
class AMPBlock2(torch.nn.Module):
|
||||
|
||||
def __init__(self, h, channels, kernel_size=3, dilation=(1, 3), activation=None):
|
||||
super(AMPBlock2, self).__init__()
|
||||
self.h = h
|
||||
|
||||
self.convs = nn.ModuleList([
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=dilation[0],
|
||||
padding=get_padding(kernel_size, dilation[0]))),
|
||||
weight_norm(
|
||||
Conv1d(channels,
|
||||
channels,
|
||||
kernel_size,
|
||||
1,
|
||||
dilation=dilation[1],
|
||||
padding=get_padding(kernel_size, dilation[1])))
|
||||
])
|
||||
self.convs.apply(init_weights)
|
||||
|
||||
self.num_layers = len(self.convs) # total number of conv layers
|
||||
|
||||
if activation == 'snake': # periodic nonlinearity with snake function and anti-aliasing
|
||||
self.activations = nn.ModuleList([
|
||||
Activation1d(
|
||||
activation=activations.Snake(channels, alpha_logscale=h.snake_logscale))
|
||||
for _ in range(self.num_layers)
|
||||
])
|
||||
elif activation == 'snakebeta': # periodic nonlinearity with snakebeta function and anti-aliasing
|
||||
self.activations = nn.ModuleList([
|
||||
Activation1d(
|
||||
activation=activations.SnakeBeta(channels, alpha_logscale=h.snake_logscale))
|
||||
for _ in range(self.num_layers)
|
||||
])
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"activation incorrectly specified. check the config file and look for 'activation'."
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
for c, a in zip(self.convs, self.activations):
|
||||
xt = a(x)
|
||||
xt = c(xt)
|
||||
x = xt + x
|
||||
|
||||
return x
|
||||
|
||||
def remove_weight_norm(self):
|
||||
for l in self.convs:
|
||||
remove_parametrizations(l, 'weight')
|
||||
|
||||
|
||||
class BigVGANVocoder(torch.nn.Module):
|
||||
# this is our main BigVGAN model. Applies anti-aliased periodic activation for resblocks.
|
||||
def __init__(self, h):
|
||||
super().__init__()
|
||||
self.h = h
|
||||
|
||||
self.num_kernels = len(h.resblock_kernel_sizes)
|
||||
self.num_upsamples = len(h.upsample_rates)
|
||||
|
||||
# pre conv
|
||||
self.conv_pre = weight_norm(Conv1d(h.num_mels, h.upsample_initial_channel, 7, 1, padding=3))
|
||||
|
||||
# define which AMPBlock to use. BigVGAN uses AMPBlock1 as default
|
||||
resblock = AMPBlock1 if h.resblock == '1' else AMPBlock2
|
||||
|
||||
# transposed conv-based upsamplers. does not apply anti-aliasing
|
||||
self.ups = nn.ModuleList()
|
||||
for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)):
|
||||
self.ups.append(
|
||||
nn.ModuleList([
|
||||
weight_norm(
|
||||
ConvTranspose1d(h.upsample_initial_channel // (2**i),
|
||||
h.upsample_initial_channel // (2**(i + 1)),
|
||||
k,
|
||||
u,
|
||||
padding=(k - u) // 2))
|
||||
]))
|
||||
|
||||
# residual blocks using anti-aliased multi-periodicity composition modules (AMP)
|
||||
self.resblocks = nn.ModuleList()
|
||||
for i in range(len(self.ups)):
|
||||
ch = h.upsample_initial_channel // (2**(i + 1))
|
||||
for j, (k, d) in enumerate(zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes)):
|
||||
self.resblocks.append(resblock(h, ch, k, d, activation=h.activation))
|
||||
|
||||
# post conv
|
||||
if h.activation == "snake": # periodic nonlinearity with snake function and anti-aliasing
|
||||
activation_post = activations.Snake(ch, alpha_logscale=h.snake_logscale)
|
||||
self.activation_post = Activation1d(activation=activation_post)
|
||||
elif h.activation == "snakebeta": # periodic nonlinearity with snakebeta function and anti-aliasing
|
||||
activation_post = activations.SnakeBeta(ch, alpha_logscale=h.snake_logscale)
|
||||
self.activation_post = Activation1d(activation=activation_post)
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"activation incorrectly specified. check the config file and look for 'activation'."
|
||||
)
|
||||
|
||||
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
|
||||
|
||||
# weight initialization
|
||||
for i in range(len(self.ups)):
|
||||
self.ups[i].apply(init_weights)
|
||||
self.conv_post.apply(init_weights)
|
||||
|
||||
def forward(self, x):
|
||||
# pre conv
|
||||
x = self.conv_pre(x)
|
||||
|
||||
for i in range(self.num_upsamples):
|
||||
# upsampling
|
||||
for i_up in range(len(self.ups[i])):
|
||||
x = self.ups[i][i_up](x)
|
||||
# AMP blocks
|
||||
xs = None
|
||||
for j in range(self.num_kernels):
|
||||
if xs is None:
|
||||
xs = self.resblocks[i * self.num_kernels + j](x)
|
||||
else:
|
||||
xs += self.resblocks[i * self.num_kernels + j](x)
|
||||
x = xs / self.num_kernels
|
||||
|
||||
# post conv
|
||||
x = self.activation_post(x)
|
||||
x = self.conv_post(x)
|
||||
x = torch.tanh(x)
|
||||
|
||||
return x
|
||||
|
||||
def remove_weight_norm(self):
|
||||
print('Removing weight norm...')
|
||||
for l in self.ups:
|
||||
for l_i in l:
|
||||
remove_parametrizations(l_i, 'weight')
|
||||
for l in self.resblocks:
|
||||
l.remove_weight_norm()
|
||||
remove_parametrizations(self.conv_pre, 'weight')
|
||||
remove_parametrizations(self.conv_post, 'weight')
|
||||
@@ -0,0 +1,20 @@
|
||||
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
|
||||
# LICENSE is in incl_licenses directory.
|
||||
|
||||
from torch.nn.utils.parametrizations import weight_norm
|
||||
|
||||
|
||||
def init_weights(m, mean=0.0, std=0.01):
|
||||
classname = m.__class__.__name__
|
||||
if classname.find("Conv") != -1:
|
||||
m.weight.data.normal_(mean, std)
|
||||
|
||||
|
||||
def apply_weight_norm(m):
|
||||
classname = m.__class__.__name__
|
||||
if classname.find("Conv") != -1:
|
||||
weight_norm(m)
|
||||
|
||||
|
||||
def get_padding(kernel_size, dilation=1):
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
@@ -0,0 +1,212 @@
|
||||
# Reference: # https://github.com/bytedance/Make-An-Audio-2
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
|
||||
# following is from librosa
|
||||
|
||||
def hz_to_mel(frequencies, *, htk = False):
|
||||
frequencies = np.asanyarray(frequencies)
|
||||
|
||||
if htk:
|
||||
mels: np.ndarray = 2595.0 * np.log10(1.0 + frequencies / 700.0)
|
||||
return mels
|
||||
|
||||
# Fill in the linear part
|
||||
f_min = 0.0
|
||||
f_sp = 200.0 / 3
|
||||
|
||||
mels = (frequencies - f_min) / f_sp
|
||||
|
||||
# Fill in the log-scale part
|
||||
|
||||
min_log_hz = 1000.0 # beginning of log region (Hz)
|
||||
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
|
||||
logstep = np.log(6.4) / 27.0 # step size for log region
|
||||
|
||||
if frequencies.ndim:
|
||||
# If we have array data, vectorize
|
||||
log_t = frequencies >= min_log_hz
|
||||
mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep
|
||||
elif frequencies >= min_log_hz:
|
||||
# If we have scalar data, heck directly
|
||||
mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep
|
||||
|
||||
return mels
|
||||
|
||||
def mel_to_hz(mels, *, htk = False):
|
||||
mels = np.asanyarray(mels)
|
||||
|
||||
if htk:
|
||||
return 700.0 * (10.0 ** (mels / 2595.0) - 1.0)
|
||||
|
||||
# Fill in the linear scale
|
||||
f_min = 0.0
|
||||
f_sp = 200.0 / 3
|
||||
freqs = f_min + f_sp * mels
|
||||
|
||||
# And now the nonlinear scale
|
||||
min_log_hz = 1000.0 # beginning of log region (Hz)
|
||||
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
|
||||
logstep = np.log(6.4) / 27.0 # step size for log region
|
||||
|
||||
if mels.ndim:
|
||||
# If we have vector data, vectorize
|
||||
log_t = mels >= min_log_mel
|
||||
freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel))
|
||||
elif mels >= min_log_mel:
|
||||
# If we have scalar data, check directly
|
||||
freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel))
|
||||
|
||||
return freqs
|
||||
|
||||
def mel_frequencies(n_mels = 128, *, fmin = 0.0, fmax = 11025.0, htk = False):
|
||||
min_mel = hz_to_mel(fmin, htk=htk)
|
||||
max_mel = hz_to_mel(fmax, htk=htk)
|
||||
mels = np.linspace(min_mel, max_mel, n_mels)
|
||||
hz: np.ndarray = mel_to_hz(mels, htk=htk)
|
||||
return hz
|
||||
|
||||
def librosa_mel_fn(
|
||||
*,
|
||||
sr: float,
|
||||
n_fft: int,
|
||||
n_mels: int = 128,
|
||||
fmin: float = 0.0,
|
||||
fmax = None,
|
||||
htk = False,
|
||||
norm = "slaney",
|
||||
dtype = np.float32,
|
||||
) -> np.ndarray:
|
||||
|
||||
if fmax is None:
|
||||
fmax = float(sr) / 2
|
||||
|
||||
# Initialize the weights
|
||||
n_mels = int(n_mels)
|
||||
weights = np.zeros((n_mels, int(1 + n_fft // 2)), dtype=dtype)
|
||||
|
||||
# Center freqs of each FFT bin
|
||||
fftfreqs = np.fft.rfftfreq(n=n_fft, d=1.0 / sr)
|
||||
|
||||
# 'Center freqs' of mel bands - uniformly spaced between limits
|
||||
mel_f = mel_frequencies(n_mels + 2, fmin=fmin, fmax=fmax, htk=htk)
|
||||
|
||||
fdiff = np.diff(mel_f)
|
||||
ramps = np.subtract.outer(mel_f, fftfreqs)
|
||||
|
||||
for i in range(n_mels):
|
||||
# lower and upper slopes for all bins
|
||||
lower = -ramps[i] / fdiff[i]
|
||||
upper = ramps[i + 2] / fdiff[i + 1]
|
||||
|
||||
# .. then intersect them with each other and zero
|
||||
weights[i] = np.maximum(0, np.minimum(lower, upper))
|
||||
|
||||
# Slaney-style mel is scaled to be approx constant energy per channel
|
||||
enorm = 2.0 / (mel_f[2 : n_mels + 2] - mel_f[:n_mels])
|
||||
weights *= enorm[:, np.newaxis]
|
||||
|
||||
return weights
|
||||
|
||||
|
||||
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5, *, norm_fn):
|
||||
return norm_fn(torch.clamp(x, min=clip_val) * C)
|
||||
|
||||
|
||||
def spectral_normalize_torch(magnitudes, norm_fn):
|
||||
output = dynamic_range_compression_torch(magnitudes, norm_fn=norm_fn)
|
||||
return output
|
||||
|
||||
|
||||
class MelConverter(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
sampling_rate: float,
|
||||
n_fft: int,
|
||||
num_mels: int,
|
||||
hop_size: int,
|
||||
win_size: int,
|
||||
fmin: float,
|
||||
fmax: float,
|
||||
norm_fn,
|
||||
):
|
||||
super().__init__()
|
||||
self.sampling_rate = sampling_rate
|
||||
self.n_fft = n_fft
|
||||
self.num_mels = num_mels
|
||||
self.hop_size = hop_size
|
||||
self.win_size = win_size
|
||||
self.fmin = fmin
|
||||
self.fmax = fmax
|
||||
self.norm_fn = norm_fn
|
||||
|
||||
mel = librosa_mel_fn(sr=self.sampling_rate,
|
||||
n_fft=self.n_fft,
|
||||
n_mels=self.num_mels,
|
||||
fmin=self.fmin,
|
||||
fmax=self.fmax)
|
||||
mel_basis = torch.from_numpy(mel).float()
|
||||
hann_window = torch.hann_window(self.win_size)
|
||||
|
||||
self.register_buffer('mel_basis', mel_basis)
|
||||
self.register_buffer('hann_window', hann_window)
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
return self.mel_basis.device
|
||||
|
||||
def forward(self, waveform: torch.Tensor, center: bool = False) -> torch.Tensor:
|
||||
waveform = waveform.clamp(min=-1., max=1.).to(self.device)
|
||||
|
||||
waveform = torch.nn.functional.pad(
|
||||
waveform.unsqueeze(1),
|
||||
[int((self.n_fft - self.hop_size) / 2),
|
||||
int((self.n_fft - self.hop_size) / 2)],
|
||||
mode='reflect')
|
||||
waveform = waveform.squeeze(1)
|
||||
|
||||
spec = torch.stft(waveform,
|
||||
self.n_fft,
|
||||
hop_length=self.hop_size,
|
||||
win_length=self.win_size,
|
||||
window=self.hann_window,
|
||||
center=center,
|
||||
pad_mode='reflect',
|
||||
normalized=False,
|
||||
onesided=True,
|
||||
return_complex=True)
|
||||
|
||||
spec = torch.view_as_real(spec)
|
||||
spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9)).float()
|
||||
spec = torch.matmul(self.mel_basis, spec)
|
||||
spec = spectral_normalize_torch(spec, self.norm_fn)
|
||||
|
||||
return spec
|
||||
|
||||
|
||||
def get_mel_converter(mode: Literal['16k', '44k']) -> MelConverter:
|
||||
if mode == '16k':
|
||||
return MelConverter(sampling_rate=16_000,
|
||||
n_fft=1024,
|
||||
num_mels=80,
|
||||
hop_size=256,
|
||||
win_size=1024,
|
||||
fmin=0,
|
||||
fmax=8_000,
|
||||
norm_fn=torch.log10)
|
||||
elif mode == '44k':
|
||||
return MelConverter(sampling_rate=44_100,
|
||||
n_fft=2048,
|
||||
num_mels=128,
|
||||
hop_size=512,
|
||||
win_size=2048,
|
||||
fmin=0,
|
||||
fmax=44100 / 2,
|
||||
norm_fn=torch.log)
|
||||
else:
|
||||
raise ValueError(f'Unknown mode: {mode}')
|
||||
@@ -0,0 +1,257 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import folder_paths
|
||||
import os
|
||||
|
||||
from .mel_converter import get_mel_converter
|
||||
from .vae.autoencoder import AutoEncoderModule
|
||||
from .vae.distributions import DiagonalGaussianDistribution
|
||||
import torchaudio
|
||||
|
||||
from comfy import model_management as mm
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
|
||||
class FeaturesUtils(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
tod_vae_ckpt: str,
|
||||
bigvgan_vocoder_ckpt = None,
|
||||
mode=['16k', '44k'],
|
||||
need_vae_encoder: bool = True,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.mel_converter = get_mel_converter(mode)
|
||||
self.tod = AutoEncoderModule(vae_ckpt_path=tod_vae_ckpt,
|
||||
vocoder_ckpt_path=bigvgan_vocoder_ckpt,
|
||||
mode=mode,
|
||||
need_vae_encoder=need_vae_encoder)
|
||||
|
||||
def encode_audio(self, x) -> DiagonalGaussianDistribution:
|
||||
assert self.tod is not None, 'VAE is not loaded'
|
||||
# x: (B * L)
|
||||
mel = self.mel_converter(x)
|
||||
dist = self.tod.encode(mel)
|
||||
|
||||
return dist
|
||||
|
||||
def vocode(self, mel: torch.Tensor) -> torch.Tensor:
|
||||
assert self.tod is not None, 'VAE is not loaded'
|
||||
return self.tod.vocode(mel)
|
||||
|
||||
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
assert self.tod is not None, 'VAE is not loaded'
|
||||
return self.tod.decode(z)
|
||||
|
||||
@property
|
||||
def device(self):
|
||||
return next(self.parameters()).device
|
||||
|
||||
@property
|
||||
def dtype(self):
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
def wrapped_decode(self, z):
|
||||
with torch.amp.autocast('cuda', dtype=self.dtype):
|
||||
mel_decoded = self.decode(z)
|
||||
audio = self.vocode(mel_decoded)
|
||||
|
||||
return audio
|
||||
|
||||
def wrapped_encode(self, audio):
|
||||
with torch.amp.autocast('cuda', dtype=self.dtype):
|
||||
dist = self.encode_audio(audio)
|
||||
|
||||
return dist.mean
|
||||
|
||||
if not "mmaudio" in folder_paths.folder_names_and_paths:
|
||||
folder_paths.add_model_folder_path("mmaudio", os.path.join(folder_paths.models_dir, "mmaudio"))
|
||||
|
||||
class OviMMAudioVAELoader:
|
||||
"""Loads MMAudio VAE for audio encoding/decoding in Ovi"""
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
s.vae_files = folder_paths.get_filename_list("vae")
|
||||
s.mmaudio_files = folder_paths.get_filename_list("mmaudio")
|
||||
s.all_files = s.vae_files + s.mmaudio_files
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"vae": (s.all_files, {"tooltip": "MMAudio VAE 16k (v1-16.pth) model from models/vae or models/mmaudio"}),
|
||||
"vocoder": (s.all_files, {"tooltip": "BigVGAN vocoder (best_netG.pt) from models/vae or models/mmaudio"}),
|
||||
"precision": (["bf16", "fp16", "fp32"], {"default": "bf16"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MMAUDIOVAE",)
|
||||
RETURN_NAMES = ("mmaudio_vae",)
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
DESCRIPTION = "Loads MMAudio VAE for Ovi audio generation"
|
||||
|
||||
def loadmodel(self, vae, vocoder, precision):
|
||||
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[precision]
|
||||
|
||||
vae_path = folder_paths.get_full_path("vae", vae) if vae in self.vae_files else folder_paths.get_full_path("mmaudio", vae)
|
||||
vocoder_path = folder_paths.get_full_path("vae", vocoder) if vocoder in self.vae_files else folder_paths.get_full_path("mmaudio", vocoder)
|
||||
|
||||
vae = FeaturesUtils(
|
||||
tod_vae_ckpt=vae_path,
|
||||
bigvgan_vocoder_ckpt=vocoder_path,
|
||||
mode='16k',
|
||||
need_vae_encoder=True
|
||||
)
|
||||
|
||||
vae.to(device=offload_device, dtype=dtype)
|
||||
vae.eval()
|
||||
|
||||
return (vae,)
|
||||
|
||||
class WanVideoDecodeOviAudio:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"mmaudio_vae": ("MMAUDIOVAE",),
|
||||
"samples": ("LATENT",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("audio",)
|
||||
FUNCTION = "decode"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
|
||||
def decode(self, mmaudio_vae, samples):
|
||||
mm.soft_empty_cache()
|
||||
audio_latents = samples.get("latent_ovi_audio", None)
|
||||
if audio_latents is None:
|
||||
raise ValueError("No Ovi audio latents found in input samples")
|
||||
|
||||
mmaudio_vae.to(device)
|
||||
|
||||
waveform = mmaudio_vae.wrapped_decode(audio_latents.to(device=device, dtype=mmaudio_vae.dtype))
|
||||
audio = {"waveform": waveform.cpu().float(), "sample_rate": 16000}
|
||||
|
||||
mmaudio_vae.to(offload_device)
|
||||
mm.soft_empty_cache()
|
||||
|
||||
return (audio,)
|
||||
|
||||
class WanVideoEncodeOviAudio:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"mmaudio_vae": ("MMAUDIOVAE",),
|
||||
"audio": ("AUDIO",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
RETURN_NAMES = ("samples",)
|
||||
FUNCTION = "decode"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
|
||||
def decode(self, mmaudio_vae, audio):
|
||||
|
||||
mmaudio_vae.to(device)
|
||||
|
||||
waveform = audio.get("waveform", None)
|
||||
sample_rate = audio.get("sample_rate", None)
|
||||
if sample_rate != 16000:
|
||||
waveform = torchaudio.functional.resample(waveform, sample_rate, 16000)
|
||||
waveform = waveform.to(device=device, dtype=mmaudio_vae.dtype)[0][0].unsqueeze(0)
|
||||
|
||||
samples = mmaudio_vae.wrapped_encode(waveform)
|
||||
|
||||
mmaudio_vae.to(offload_device)
|
||||
mm.soft_empty_cache()
|
||||
|
||||
return ({"latent_ovi_audio": samples},)
|
||||
|
||||
|
||||
class WanVideoAddOviAudioToLatents:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"original_samples": ("LATENT",),
|
||||
"audio_samples": ("LATENT",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
RETURN_NAMES = ("samples",)
|
||||
FUNCTION = "decode"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
|
||||
def decode(self, original_samples, audio_samples):
|
||||
samples = original_samples.copy()
|
||||
samples.update(audio_samples)
|
||||
|
||||
return (samples,)
|
||||
|
||||
class WanVideoEmptyMMAudioLatents:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"length": ("INT", {"default": 157, "min": 1, "max": 10000, "step": 1, "tooltip": "Length of the audio latent sequence"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
RETURN_NAMES = ("samples",)
|
||||
FUNCTION = "decode"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
|
||||
def decode(self, length):
|
||||
audio_latents = torch.zeros((length, 20), device=torch.device("cpu"), dtype=torch.float32) # 1, l c -> l, c
|
||||
|
||||
return ({"latent_ovi_audio": audio_latents},)
|
||||
|
||||
|
||||
class WanVideoOviCFG:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"original_text_embeds": ("WANVIDEOTEXTEMBEDS",),
|
||||
"ovi_negative_text_embeds": ("WANVIDEOTEXTEMBEDS",),
|
||||
"ovi_audio_cfg": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 100.0, "step": 0.01}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVIDEOTEXTEMBEDS", )
|
||||
RETURN_NAMES = ("text_embeds",)
|
||||
FUNCTION = "process"
|
||||
CATEGORY = "WanVideoWrapper/Ovi"
|
||||
DESCRIPTION = "Adds Ovi negative text embeddings and audio CFG scale to the text embeddings dictionary"
|
||||
|
||||
def process(self, original_text_embeds, ovi_negative_text_embeds, ovi_audio_cfg):
|
||||
negative_text_embeds = ovi_negative_text_embeds.get("negative_prompt_embeds", None)
|
||||
if negative_text_embeds is None:
|
||||
negative_text_embeds = original_text_embeds["prompt_embeds"]
|
||||
|
||||
prompt_embeds_dict_copy = original_text_embeds.copy()
|
||||
prompt_embeds_dict_copy.update({
|
||||
"ovi_negative_prompt_embeds": negative_text_embeds,
|
||||
"ovi_audio_cfg": ovi_audio_cfg,
|
||||
})
|
||||
return (prompt_embeds_dict_copy,)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"OviMMAudioVAELoader": OviMMAudioVAELoader,
|
||||
"WanVideoDecodeOviAudio": WanVideoDecodeOviAudio,
|
||||
"WanVideoEncodeOviAudio": WanVideoEncodeOviAudio,
|
||||
"WanVideoOviCFG": WanVideoOviCFG,
|
||||
"WanVideoAddOviAudioToLatents": WanVideoAddOviAudioToLatents,
|
||||
"WanVideoEmptyMMAudioLatents": WanVideoEmptyMMAudioLatents,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"OviMMAudioVAELoader": "Ovi MMAudio VAE Loader",
|
||||
"WanVideoDecodeOviAudio": "WanVideo Decode Ovi Audio",
|
||||
"WanVideoEncodeOviAudio": "WanVideo Encode Ovi Audio",
|
||||
"WanVideoOviCFG": "WanVideo Ovi CFG",
|
||||
"WanVideoAddOviAudioToLatents": "WanVideo Add MMAudio To Latents",
|
||||
"WanVideoEmptyMMAudioLatents": "WanVideo Empty MMAudio Latents",
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
from typing import Literal, Optional
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from .vae import VAE, get_my_vae
|
||||
from .distributions import DiagonalGaussianDistribution
|
||||
from ..bigvgan import BigVGAN
|
||||
|
||||
from comfy.utils import load_torch_file
|
||||
|
||||
class AutoEncoderModule(nn.Module):
|
||||
|
||||
def __init__(self,
|
||||
*,
|
||||
vae_ckpt_path,
|
||||
vocoder_ckpt_path: Optional[str] = None,
|
||||
mode: Literal['16k', '44k'],
|
||||
need_vae_encoder: bool = True):
|
||||
super().__init__()
|
||||
self.vae: VAE = get_my_vae(mode).eval()
|
||||
#vae_state_dict = torch.load(vae_ckpt_path, weights_only=True, map_location='cpu')'
|
||||
vae_state_dict = load_torch_file(vae_ckpt_path)
|
||||
self.vae.load_state_dict(vae_state_dict)
|
||||
self.vae.remove_weight_norm()
|
||||
|
||||
if mode == '16k':
|
||||
assert vocoder_ckpt_path is not None
|
||||
self.vocoder = BigVGAN(vocoder_ckpt_path).eval()
|
||||
elif mode == '44k':
|
||||
raise NotImplementedError("44k mode requires BigVGANv2 which is not currently supported in this environment.")
|
||||
self.vocoder = BigVGANv2.from_pretrained('nvidia/bigvgan_v2_44khz_128band_512x',
|
||||
use_cuda_kernel=False)
|
||||
self.vocoder.remove_weight_norm()
|
||||
else:
|
||||
raise ValueError(f'Unknown mode: {mode}')
|
||||
|
||||
for param in self.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
if not need_vae_encoder:
|
||||
del self.vae.encoder
|
||||
|
||||
@torch.inference_mode()
|
||||
def encode(self, x: torch.Tensor) -> DiagonalGaussianDistribution:
|
||||
return self.vae.encode(x)
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
return self.vae.decode(z)
|
||||
|
||||
@torch.inference_mode()
|
||||
def vocode(self, spec: torch.Tensor) -> torch.Tensor:
|
||||
return self.vocoder(spec)
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import Optional
|
||||
import torch
|
||||
import numpy as np
|
||||
|
||||
|
||||
class DiagonalGaussianDistribution:
|
||||
|
||||
def __init__(self, parameters, deterministic=False):
|
||||
self.parameters = parameters
|
||||
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
|
||||
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
|
||||
self.deterministic = deterministic
|
||||
self.std = torch.exp(0.5 * self.logvar)
|
||||
self.var = torch.exp(self.logvar)
|
||||
if self.deterministic:
|
||||
self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
|
||||
|
||||
def sample(self, rng: Optional[torch.Generator] = None):
|
||||
# x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
|
||||
|
||||
r = torch.empty_like(self.mean).normal_(generator=rng)
|
||||
x = self.mean + self.std * r
|
||||
|
||||
return x
|
||||
|
||||
def kl(self, other=None):
|
||||
if self.deterministic:
|
||||
return torch.Tensor([0.])
|
||||
else:
|
||||
if other is None:
|
||||
|
||||
return 0.5 * torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar
|
||||
else:
|
||||
return 0.5 * (torch.pow(self.mean - other.mean, 2) / other.var +
|
||||
self.var / other.var - 1.0 - self.logvar + other.logvar)
|
||||
|
||||
def nll(self, sample, dims=[1, 2, 3]):
|
||||
if self.deterministic:
|
||||
return torch.Tensor([0.])
|
||||
logtwopi = np.log(2.0 * np.pi)
|
||||
return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
|
||||
dim=dims)
|
||||
|
||||
def mode(self):
|
||||
return self.mean
|
||||
@@ -0,0 +1,168 @@
|
||||
# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
#
|
||||
# This work is licensed under a Creative Commons
|
||||
# Attribution-NonCommercial-ShareAlike 4.0 International License.
|
||||
# You should have received a copy of the license along with this
|
||||
# work. If not, see http://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
"""Improved diffusion model architecture proposed in the paper
|
||||
"Analyzing and Improving the Training Dynamics of Diffusion Models"."""
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Variant of constant() that inherits dtype and device from the given
|
||||
# reference tensor by default.
|
||||
|
||||
_constant_cache = dict()
|
||||
|
||||
|
||||
def constant(value, shape=None, dtype=None, device=None, memory_format=None):
|
||||
value = np.asarray(value)
|
||||
if shape is not None:
|
||||
shape = tuple(shape)
|
||||
if dtype is None:
|
||||
dtype = torch.get_default_dtype()
|
||||
if device is None:
|
||||
device = torch.device('cpu')
|
||||
if memory_format is None:
|
||||
memory_format = torch.contiguous_format
|
||||
|
||||
key = (value.shape, value.dtype, value.tobytes(), shape, dtype, device, memory_format)
|
||||
tensor = _constant_cache.get(key, None)
|
||||
if tensor is None:
|
||||
tensor = torch.as_tensor(value.copy(), dtype=dtype, device=device)
|
||||
if shape is not None:
|
||||
tensor, _ = torch.broadcast_tensors(tensor, torch.empty(shape))
|
||||
tensor = tensor.contiguous(memory_format=memory_format)
|
||||
_constant_cache[key] = tensor
|
||||
return tensor
|
||||
|
||||
|
||||
def const_like(ref, value, shape=None, dtype=None, device=None, memory_format=None):
|
||||
if dtype is None:
|
||||
dtype = ref.dtype
|
||||
if device is None:
|
||||
device = ref.device
|
||||
return constant(value, shape=shape, dtype=dtype, device=device, memory_format=memory_format)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Normalize given tensor to unit magnitude with respect to the given
|
||||
# dimensions. Default = all dimensions except the first.
|
||||
|
||||
|
||||
def normalize(x, dim=None, eps=1e-4):
|
||||
if dim is None:
|
||||
dim = list(range(1, x.ndim))
|
||||
norm = torch.linalg.vector_norm(x, dim=dim, keepdim=True, dtype=torch.float32)
|
||||
norm = torch.add(eps, norm, alpha=np.sqrt(norm.numel() / x.numel()))
|
||||
return x / norm.to(x.dtype)
|
||||
|
||||
|
||||
class Normalize(torch.nn.Module):
|
||||
|
||||
def __init__(self, dim=None, eps=1e-4):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, x):
|
||||
return normalize(x, dim=self.dim, eps=self.eps)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Upsample or downsample the given tensor with the given filter,
|
||||
# or keep it as is.
|
||||
|
||||
|
||||
def resample(x, f=[1, 1], mode='keep'):
|
||||
if mode == 'keep':
|
||||
return x
|
||||
f = np.float32(f)
|
||||
assert f.ndim == 1 and len(f) % 2 == 0
|
||||
pad = (len(f) - 1) // 2
|
||||
f = f / f.sum()
|
||||
f = np.outer(f, f)[np.newaxis, np.newaxis, :, :]
|
||||
f = const_like(x, f)
|
||||
c = x.shape[1]
|
||||
if mode == 'down':
|
||||
return torch.nn.functional.conv2d(x,
|
||||
f.tile([c, 1, 1, 1]),
|
||||
groups=c,
|
||||
stride=2,
|
||||
padding=(pad, ))
|
||||
assert mode == 'up'
|
||||
return torch.nn.functional.conv_transpose2d(x, (f * 4).tile([c, 1, 1, 1]),
|
||||
groups=c,
|
||||
stride=2,
|
||||
padding=(pad, ))
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Magnitude-preserving SiLU (Equation 81).
|
||||
|
||||
|
||||
def mp_silu(x):
|
||||
return torch.nn.functional.silu(x) / 0.596
|
||||
|
||||
|
||||
class MPSiLU(torch.nn.Module):
|
||||
|
||||
def forward(self, x):
|
||||
return mp_silu(x)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Magnitude-preserving sum (Equation 88).
|
||||
|
||||
|
||||
def mp_sum(a, b, t=0.5):
|
||||
return a.lerp(b, t) / np.sqrt((1 - t)**2 + t**2)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Magnitude-preserving concatenation (Equation 103).
|
||||
|
||||
|
||||
def mp_cat(a, b, dim=1, t=0.5):
|
||||
Na = a.shape[dim]
|
||||
Nb = b.shape[dim]
|
||||
C = np.sqrt((Na + Nb) / ((1 - t)**2 + t**2))
|
||||
wa = C / np.sqrt(Na) * (1 - t)
|
||||
wb = C / np.sqrt(Nb) * t
|
||||
return torch.cat([wa * a, wb * b], dim=dim)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Magnitude-preserving convolution or fully-connected layer (Equation 47)
|
||||
# with force weight normalization (Equation 66).
|
||||
|
||||
|
||||
class MPConv1D(torch.nn.Module):
|
||||
|
||||
def __init__(self, in_channels, out_channels, kernel_size):
|
||||
super().__init__()
|
||||
self.out_channels = out_channels
|
||||
self.weight = torch.nn.Parameter(torch.randn(out_channels, in_channels, kernel_size))
|
||||
|
||||
self.weight_norm_removed = False
|
||||
|
||||
def forward(self, x, gain=1):
|
||||
assert self.weight_norm_removed, 'call remove_weight_norm() before inference'
|
||||
|
||||
w = self.weight * gain
|
||||
if w.ndim == 2:
|
||||
return x @ w.t()
|
||||
assert w.ndim == 3
|
||||
return torch.nn.functional.conv1d(x, w, padding=(w.shape[-1] // 2, ))
|
||||
|
||||
def remove_weight_norm(self):
|
||||
w = self.weight.to(torch.float32)
|
||||
w = normalize(w) # traditional weight normalization
|
||||
w = w / np.sqrt(w[0].numel())
|
||||
w = w.to(self.weight.dtype)
|
||||
self.weight.data.copy_(w)
|
||||
|
||||
self.weight_norm_removed = True
|
||||
return self
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from .edm2_utils import MPConv1D
|
||||
from .vae_modules import (AttnBlock1D, Downsample1D, ResnetBlock1D,
|
||||
Upsample1D, nonlinearity)
|
||||
from .distributions import DiagonalGaussianDistribution
|
||||
|
||||
log = logging.getLogger()
|
||||
|
||||
DATA_MEAN_80D = [
|
||||
-1.6058, -1.3676, -1.2520, -1.2453, -1.2078, -1.2224, -1.2419, -1.2439, -1.2922, -1.2927,
|
||||
-1.3170, -1.3543, -1.3401, -1.3836, -1.3907, -1.3912, -1.4313, -1.4152, -1.4527, -1.4728,
|
||||
-1.4568, -1.5101, -1.5051, -1.5172, -1.5623, -1.5373, -1.5746, -1.5687, -1.6032, -1.6131,
|
||||
-1.6081, -1.6331, -1.6489, -1.6489, -1.6700, -1.6738, -1.6953, -1.6969, -1.7048, -1.7280,
|
||||
-1.7361, -1.7495, -1.7658, -1.7814, -1.7889, -1.8064, -1.8221, -1.8377, -1.8417, -1.8643,
|
||||
-1.8857, -1.8929, -1.9173, -1.9379, -1.9531, -1.9673, -1.9824, -2.0042, -2.0215, -2.0436,
|
||||
-2.0766, -2.1064, -2.1418, -2.1855, -2.2319, -2.2767, -2.3161, -2.3572, -2.3954, -2.4282,
|
||||
-2.4659, -2.5072, -2.5552, -2.6074, -2.6584, -2.7107, -2.7634, -2.8266, -2.8981, -2.9673
|
||||
]
|
||||
|
||||
DATA_STD_80D = [
|
||||
1.0291, 1.0411, 1.0043, 0.9820, 0.9677, 0.9543, 0.9450, 0.9392, 0.9343, 0.9297, 0.9276, 0.9263,
|
||||
0.9242, 0.9254, 0.9232, 0.9281, 0.9263, 0.9315, 0.9274, 0.9247, 0.9277, 0.9199, 0.9188, 0.9194,
|
||||
0.9160, 0.9161, 0.9146, 0.9161, 0.9100, 0.9095, 0.9145, 0.9076, 0.9066, 0.9095, 0.9032, 0.9043,
|
||||
0.9038, 0.9011, 0.9019, 0.9010, 0.8984, 0.8983, 0.8986, 0.8961, 0.8962, 0.8978, 0.8962, 0.8973,
|
||||
0.8993, 0.8976, 0.8995, 0.9016, 0.8982, 0.8972, 0.8974, 0.8949, 0.8940, 0.8947, 0.8936, 0.8939,
|
||||
0.8951, 0.8956, 0.9017, 0.9167, 0.9436, 0.9690, 1.0003, 1.0225, 1.0381, 1.0491, 1.0545, 1.0604,
|
||||
1.0761, 1.0929, 1.1089, 1.1196, 1.1176, 1.1156, 1.1117, 1.1070
|
||||
]
|
||||
|
||||
DATA_MEAN_128D = [
|
||||
-3.3462, -2.6723, -2.4893, -2.3143, -2.2664, -2.3317, -2.1802, -2.4006, -2.2357, -2.4597,
|
||||
-2.3717, -2.4690, -2.5142, -2.4919, -2.6610, -2.5047, -2.7483, -2.5926, -2.7462, -2.7033,
|
||||
-2.7386, -2.8112, -2.7502, -2.9594, -2.7473, -3.0035, -2.8891, -2.9922, -2.9856, -3.0157,
|
||||
-3.1191, -2.9893, -3.1718, -3.0745, -3.1879, -3.2310, -3.1424, -3.2296, -3.2791, -3.2782,
|
||||
-3.2756, -3.3134, -3.3509, -3.3750, -3.3951, -3.3698, -3.4505, -3.4509, -3.5089, -3.4647,
|
||||
-3.5536, -3.5788, -3.5867, -3.6036, -3.6400, -3.6747, -3.7072, -3.7279, -3.7283, -3.7795,
|
||||
-3.8259, -3.8447, -3.8663, -3.9182, -3.9605, -3.9861, -4.0105, -4.0373, -4.0762, -4.1121,
|
||||
-4.1488, -4.1874, -4.2461, -4.3170, -4.3639, -4.4452, -4.5282, -4.6297, -4.7019, -4.7960,
|
||||
-4.8700, -4.9507, -5.0303, -5.0866, -5.1634, -5.2342, -5.3242, -5.4053, -5.4927, -5.5712,
|
||||
-5.6464, -5.7052, -5.7619, -5.8410, -5.9188, -6.0103, -6.0955, -6.1673, -6.2362, -6.3120,
|
||||
-6.3926, -6.4797, -6.5565, -6.6511, -6.8130, -6.9961, -7.1275, -7.2457, -7.3576, -7.4663,
|
||||
-7.6136, -7.7469, -7.8815, -8.0132, -8.1515, -8.3071, -8.4722, -8.7418, -9.3975, -9.6628,
|
||||
-9.7671, -9.8863, -9.9992, -10.0860, -10.1709, -10.5418, -11.2795, -11.3861
|
||||
]
|
||||
|
||||
DATA_STD_128D = [
|
||||
2.3804, 2.4368, 2.3772, 2.3145, 2.2803, 2.2510, 2.2316, 2.2083, 2.1996, 2.1835, 2.1769, 2.1659,
|
||||
2.1631, 2.1618, 2.1540, 2.1606, 2.1571, 2.1567, 2.1612, 2.1579, 2.1679, 2.1683, 2.1634, 2.1557,
|
||||
2.1668, 2.1518, 2.1415, 2.1449, 2.1406, 2.1350, 2.1313, 2.1415, 2.1281, 2.1352, 2.1219, 2.1182,
|
||||
2.1327, 2.1195, 2.1137, 2.1080, 2.1179, 2.1036, 2.1087, 2.1036, 2.1015, 2.1068, 2.0975, 2.0991,
|
||||
2.0902, 2.1015, 2.0857, 2.0920, 2.0893, 2.0897, 2.0910, 2.0881, 2.0925, 2.0873, 2.0960, 2.0900,
|
||||
2.0957, 2.0958, 2.0978, 2.0936, 2.0886, 2.0905, 2.0845, 2.0855, 2.0796, 2.0840, 2.0813, 2.0817,
|
||||
2.0838, 2.0840, 2.0917, 2.1061, 2.1431, 2.1976, 2.2482, 2.3055, 2.3700, 2.4088, 2.4372, 2.4609,
|
||||
2.4731, 2.4847, 2.5072, 2.5451, 2.5772, 2.6147, 2.6529, 2.6596, 2.6645, 2.6726, 2.6803, 2.6812,
|
||||
2.6899, 2.6916, 2.6931, 2.6998, 2.7062, 2.7262, 2.7222, 2.7158, 2.7041, 2.7485, 2.7491, 2.7451,
|
||||
2.7485, 2.7233, 2.7297, 2.7233, 2.7145, 2.6958, 2.6788, 2.6439, 2.6007, 2.4786, 2.2469, 2.1877,
|
||||
2.1392, 2.0717, 2.0107, 1.9676, 1.9140, 1.7102, 0.9101, 0.7164
|
||||
]
|
||||
|
||||
|
||||
class VAE(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
data_dim: int,
|
||||
embed_dim: int,
|
||||
hidden_dim: int,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
if data_dim == 80:
|
||||
self.data_mean = nn.Buffer(torch.tensor(DATA_MEAN_80D, dtype=torch.float32))
|
||||
self.data_std = nn.Buffer(torch.tensor(DATA_STD_80D, dtype=torch.float32))
|
||||
elif data_dim == 128:
|
||||
self.data_mean = nn.Buffer(torch.tensor(DATA_MEAN_128D, dtype=torch.float32))
|
||||
self.data_std = nn.Buffer(torch.tensor(DATA_STD_128D, dtype=torch.float32))
|
||||
|
||||
self.data_mean = self.data_mean.view(1, -1, 1)
|
||||
self.data_std = self.data_std.view(1, -1, 1)
|
||||
|
||||
self.encoder = Encoder1D(
|
||||
dim=hidden_dim,
|
||||
ch_mult=(1, 2, 4),
|
||||
num_res_blocks=2,
|
||||
attn_layers=[3],
|
||||
down_layers=[0],
|
||||
in_dim=data_dim,
|
||||
embed_dim=embed_dim,
|
||||
)
|
||||
self.decoder = Decoder1D(
|
||||
dim=hidden_dim,
|
||||
ch_mult=(1, 2, 4),
|
||||
num_res_blocks=2,
|
||||
attn_layers=[3],
|
||||
down_layers=[0],
|
||||
in_dim=data_dim,
|
||||
out_dim=data_dim,
|
||||
embed_dim=embed_dim,
|
||||
)
|
||||
|
||||
self.embed_dim = embed_dim
|
||||
# self.quant_conv = nn.Conv1d(2 * embed_dim, 2 * embed_dim, 1)
|
||||
# self.post_quant_conv = nn.Conv1d(embed_dim, embed_dim, 1)
|
||||
|
||||
self.initialize_weights()
|
||||
|
||||
def initialize_weights(self):
|
||||
pass
|
||||
|
||||
def encode(self, x: torch.Tensor, normalize: bool = True) -> DiagonalGaussianDistribution:
|
||||
if normalize:
|
||||
x = self.normalize(x)
|
||||
moments = self.encoder(x)
|
||||
posterior = DiagonalGaussianDistribution(moments)
|
||||
return posterior
|
||||
|
||||
def decode(self, z: torch.Tensor, unnormalize: bool = True) -> torch.Tensor:
|
||||
dec = self.decoder(z)
|
||||
if unnormalize:
|
||||
dec = self.unnormalize(dec)
|
||||
return dec
|
||||
|
||||
def normalize(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return (x - self.data_mean) / self.data_std
|
||||
|
||||
def unnormalize(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return x * self.data_std + self.data_mean
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
sample_posterior: bool = True,
|
||||
rng: Optional[torch.Generator] = None,
|
||||
normalize: bool = True,
|
||||
unnormalize: bool = True,
|
||||
) -> tuple[torch.Tensor, DiagonalGaussianDistribution]:
|
||||
|
||||
posterior = self.encode(x, normalize=normalize)
|
||||
if sample_posterior:
|
||||
z = posterior.sample(rng)
|
||||
else:
|
||||
z = posterior.mode()
|
||||
dec = self.decode(z, unnormalize=unnormalize)
|
||||
return dec, posterior
|
||||
|
||||
def load_weights(self, src_dict) -> None:
|
||||
self.load_state_dict(src_dict, strict=True)
|
||||
|
||||
@property
|
||||
def device(self) -> torch.device:
|
||||
return next(self.parameters()).device
|
||||
|
||||
def get_last_layer(self):
|
||||
return self.decoder.conv_out.weight
|
||||
|
||||
def remove_weight_norm(self):
|
||||
for name, m in self.named_modules():
|
||||
if isinstance(m, MPConv1D):
|
||||
m.remove_weight_norm()
|
||||
log.debug(f"Removed weight norm from {name}")
|
||||
return self
|
||||
|
||||
|
||||
class Encoder1D(nn.Module):
|
||||
|
||||
def __init__(self,
|
||||
*,
|
||||
dim: int,
|
||||
ch_mult: tuple[int] = (1, 2, 4, 8),
|
||||
num_res_blocks: int,
|
||||
attn_layers: list[int] = [],
|
||||
down_layers: list[int] = [],
|
||||
resamp_with_conv: bool = True,
|
||||
in_dim: int,
|
||||
embed_dim: int,
|
||||
double_z: bool = True,
|
||||
kernel_size: int = 3,
|
||||
clip_act: float = 256.0):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.num_layers = len(ch_mult)
|
||||
self.num_res_blocks = num_res_blocks
|
||||
self.in_channels = in_dim
|
||||
self.clip_act = clip_act
|
||||
self.down_layers = down_layers
|
||||
self.attn_layers = attn_layers
|
||||
self.conv_in = MPConv1D(in_dim, self.dim, kernel_size=kernel_size)
|
||||
|
||||
in_ch_mult = (1, ) + tuple(ch_mult)
|
||||
self.in_ch_mult = in_ch_mult
|
||||
# downsampling
|
||||
self.down = nn.ModuleList()
|
||||
for i_level in range(self.num_layers):
|
||||
block = nn.ModuleList()
|
||||
attn = nn.ModuleList()
|
||||
block_in = dim * in_ch_mult[i_level]
|
||||
block_out = dim * ch_mult[i_level]
|
||||
for i_block in range(self.num_res_blocks):
|
||||
block.append(
|
||||
ResnetBlock1D(in_dim=block_in,
|
||||
out_dim=block_out,
|
||||
kernel_size=kernel_size,
|
||||
use_norm=True))
|
||||
block_in = block_out
|
||||
if i_level in attn_layers:
|
||||
attn.append(AttnBlock1D(block_in))
|
||||
down = nn.Module()
|
||||
down.block = block
|
||||
down.attn = attn
|
||||
if i_level in down_layers:
|
||||
down.downsample = Downsample1D(block_in, resamp_with_conv)
|
||||
self.down.append(down)
|
||||
|
||||
# middle
|
||||
self.mid = nn.Module()
|
||||
self.mid.block_1 = ResnetBlock1D(in_dim=block_in,
|
||||
out_dim=block_in,
|
||||
kernel_size=kernel_size,
|
||||
use_norm=True)
|
||||
self.mid.attn_1 = AttnBlock1D(block_in)
|
||||
self.mid.block_2 = ResnetBlock1D(in_dim=block_in,
|
||||
out_dim=block_in,
|
||||
kernel_size=kernel_size,
|
||||
use_norm=True)
|
||||
|
||||
# end
|
||||
self.conv_out = MPConv1D(block_in,
|
||||
2 * embed_dim if double_z else embed_dim,
|
||||
kernel_size=kernel_size)
|
||||
|
||||
self.learnable_gain = nn.Parameter(torch.zeros([]))
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
# downsampling
|
||||
hs = [self.conv_in(x)]
|
||||
for i_level in range(self.num_layers):
|
||||
for i_block in range(self.num_res_blocks):
|
||||
h = self.down[i_level].block[i_block](hs[-1])
|
||||
if len(self.down[i_level].attn) > 0:
|
||||
h = self.down[i_level].attn[i_block](h)
|
||||
h = h.clamp(-self.clip_act, self.clip_act)
|
||||
hs.append(h)
|
||||
if i_level in self.down_layers:
|
||||
hs.append(self.down[i_level].downsample(hs[-1]))
|
||||
|
||||
# middle
|
||||
h = hs[-1]
|
||||
h = self.mid.block_1(h)
|
||||
h = self.mid.attn_1(h)
|
||||
h = self.mid.block_2(h)
|
||||
h = h.clamp(-self.clip_act, self.clip_act)
|
||||
|
||||
# end
|
||||
h = nonlinearity(h)
|
||||
h = self.conv_out(h, gain=(self.learnable_gain + 1))
|
||||
return h
|
||||
|
||||
|
||||
class Decoder1D(nn.Module):
|
||||
|
||||
def __init__(self,
|
||||
*,
|
||||
dim: int,
|
||||
out_dim: int,
|
||||
ch_mult: tuple[int] = (1, 2, 4, 8),
|
||||
num_res_blocks: int,
|
||||
attn_layers: list[int] = [],
|
||||
down_layers: list[int] = [],
|
||||
kernel_size: int = 3,
|
||||
resamp_with_conv: bool = True,
|
||||
in_dim: int,
|
||||
embed_dim: int,
|
||||
clip_act: float = 256.0):
|
||||
super().__init__()
|
||||
self.ch = dim
|
||||
self.num_layers = len(ch_mult)
|
||||
self.num_res_blocks = num_res_blocks
|
||||
self.in_channels = in_dim
|
||||
self.clip_act = clip_act
|
||||
self.down_layers = [i + 1 for i in down_layers] # each downlayer add one
|
||||
|
||||
# compute in_ch_mult, block_in and curr_res at lowest res
|
||||
block_in = dim * ch_mult[self.num_layers - 1]
|
||||
|
||||
# z to block_in
|
||||
self.conv_in = MPConv1D(embed_dim, block_in, kernel_size=kernel_size)
|
||||
|
||||
# middle
|
||||
self.mid = nn.Module()
|
||||
self.mid.block_1 = ResnetBlock1D(in_dim=block_in, out_dim=block_in, use_norm=True)
|
||||
self.mid.attn_1 = AttnBlock1D(block_in)
|
||||
self.mid.block_2 = ResnetBlock1D(in_dim=block_in, out_dim=block_in, use_norm=True)
|
||||
|
||||
# upsampling
|
||||
self.up = nn.ModuleList()
|
||||
for i_level in reversed(range(self.num_layers)):
|
||||
block = nn.ModuleList()
|
||||
attn = nn.ModuleList()
|
||||
block_out = dim * ch_mult[i_level]
|
||||
for i_block in range(self.num_res_blocks + 1):
|
||||
block.append(ResnetBlock1D(in_dim=block_in, out_dim=block_out, use_norm=True))
|
||||
block_in = block_out
|
||||
if i_level in attn_layers:
|
||||
attn.append(AttnBlock1D(block_in))
|
||||
up = nn.Module()
|
||||
up.block = block
|
||||
up.attn = attn
|
||||
if i_level in self.down_layers:
|
||||
up.upsample = Upsample1D(block_in, resamp_with_conv)
|
||||
self.up.insert(0, up) # prepend to get consistent order
|
||||
|
||||
# end
|
||||
self.conv_out = MPConv1D(block_in, out_dim, kernel_size=kernel_size)
|
||||
self.learnable_gain = nn.Parameter(torch.zeros([]))
|
||||
|
||||
def forward(self, z):
|
||||
# z to block_in
|
||||
h = self.conv_in(z)
|
||||
|
||||
# middle
|
||||
h = self.mid.block_1(h)
|
||||
h = self.mid.attn_1(h)
|
||||
h = self.mid.block_2(h)
|
||||
h = h.clamp(-self.clip_act, self.clip_act)
|
||||
|
||||
# upsampling
|
||||
for i_level in reversed(range(self.num_layers)):
|
||||
for i_block in range(self.num_res_blocks + 1):
|
||||
h = self.up[i_level].block[i_block](h)
|
||||
if len(self.up[i_level].attn) > 0:
|
||||
h = self.up[i_level].attn[i_block](h)
|
||||
h = h.clamp(-self.clip_act, self.clip_act)
|
||||
if i_level in self.down_layers:
|
||||
h = self.up[i_level].upsample(h)
|
||||
|
||||
h = nonlinearity(h)
|
||||
h = self.conv_out(h, gain=(self.learnable_gain + 1))
|
||||
return h
|
||||
|
||||
|
||||
def VAE_16k(**kwargs) -> VAE:
|
||||
return VAE(data_dim=80, embed_dim=20, hidden_dim=384, **kwargs)
|
||||
|
||||
|
||||
def VAE_44k(**kwargs) -> VAE:
|
||||
return VAE(data_dim=128, embed_dim=40, hidden_dim=512, **kwargs)
|
||||
|
||||
|
||||
def get_my_vae(name: str, **kwargs) -> VAE:
|
||||
if name == '16k':
|
||||
return VAE_16k(**kwargs)
|
||||
if name == '44k':
|
||||
return VAE_44k(**kwargs)
|
||||
raise ValueError(f'Unknown model: {name}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
network = get_my_vae('standard')
|
||||
|
||||
# print the number of parameters in terms of millions
|
||||
num_params = sum(p.numel() for p in network.parameters()) / 1e6
|
||||
print(f'Number of parameters: {num_params:.2f}M')
|
||||
@@ -0,0 +1,117 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from einops import rearrange
|
||||
|
||||
from .edm2_utils import (MPConv1D, mp_silu, mp_sum, normalize)
|
||||
|
||||
|
||||
def nonlinearity(x):
|
||||
# swish
|
||||
return mp_silu(x)
|
||||
|
||||
|
||||
class ResnetBlock1D(nn.Module):
|
||||
|
||||
def __init__(self, *, in_dim, out_dim=None, conv_shortcut=False, kernel_size=3, use_norm=True):
|
||||
super().__init__()
|
||||
self.in_dim = in_dim
|
||||
out_dim = in_dim if out_dim is None else out_dim
|
||||
self.out_dim = out_dim
|
||||
self.use_conv_shortcut = conv_shortcut
|
||||
self.use_norm = use_norm
|
||||
|
||||
self.conv1 = MPConv1D(in_dim, out_dim, kernel_size=kernel_size)
|
||||
self.conv2 = MPConv1D(out_dim, out_dim, kernel_size=kernel_size)
|
||||
if self.in_dim != self.out_dim:
|
||||
if self.use_conv_shortcut:
|
||||
self.conv_shortcut = MPConv1D(in_dim, out_dim, kernel_size=kernel_size)
|
||||
else:
|
||||
self.nin_shortcut = MPConv1D(in_dim, out_dim, kernel_size=1)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
# pixel norm
|
||||
if self.use_norm:
|
||||
x = normalize(x, dim=1)
|
||||
|
||||
h = x
|
||||
h = nonlinearity(h)
|
||||
h = self.conv1(h)
|
||||
|
||||
h = nonlinearity(h)
|
||||
h = self.conv2(h)
|
||||
|
||||
if self.in_dim != self.out_dim:
|
||||
if self.use_conv_shortcut:
|
||||
x = self.conv_shortcut(x)
|
||||
else:
|
||||
x = self.nin_shortcut(x)
|
||||
|
||||
return mp_sum(x, h, t=0.3)
|
||||
|
||||
|
||||
class AttnBlock1D(nn.Module):
|
||||
|
||||
def __init__(self, in_channels, num_heads=1):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
|
||||
self.num_heads = num_heads
|
||||
self.qkv = MPConv1D(in_channels, in_channels * 3, kernel_size=1)
|
||||
self.proj_out = MPConv1D(in_channels, in_channels, kernel_size=1)
|
||||
|
||||
def forward(self, x):
|
||||
h = x
|
||||
y = self.qkv(h)
|
||||
y = y.reshape(y.shape[0], self.num_heads, -1, 3, y.shape[-1])
|
||||
q, k, v = normalize(y, dim=2).unbind(3)
|
||||
|
||||
q = rearrange(q, 'b h c l -> b h l c')
|
||||
k = rearrange(k, 'b h c l -> b h l c')
|
||||
v = rearrange(v, 'b h c l -> b h l c')
|
||||
|
||||
h = F.scaled_dot_product_attention(q, k, v)
|
||||
h = rearrange(h, 'b h l c -> b (h c) l')
|
||||
|
||||
h = self.proj_out(h)
|
||||
|
||||
return mp_sum(x, h, t=0.3)
|
||||
|
||||
|
||||
class Upsample1D(nn.Module):
|
||||
|
||||
def __init__(self, in_channels, with_conv):
|
||||
super().__init__()
|
||||
self.with_conv = with_conv
|
||||
if self.with_conv:
|
||||
self.conv = MPConv1D(in_channels, in_channels, kernel_size=3)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.interpolate(x, scale_factor=2.0, mode='nearest-exact') # support 3D tensor(B,C,T)
|
||||
if self.with_conv:
|
||||
x = self.conv(x)
|
||||
return x
|
||||
|
||||
|
||||
class Downsample1D(nn.Module):
|
||||
|
||||
def __init__(self, in_channels, with_conv):
|
||||
super().__init__()
|
||||
self.with_conv = with_conv
|
||||
if self.with_conv:
|
||||
# no asymmetric padding in torch conv, must do it ourselves
|
||||
self.conv1 = MPConv1D(in_channels, in_channels, kernel_size=1)
|
||||
self.conv2 = MPConv1D(in_channels, in_channels, kernel_size=1)
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
if self.with_conv:
|
||||
x = self.conv1(x)
|
||||
|
||||
x = F.avg_pool1d(x, kernel_size=2, stride=2)
|
||||
|
||||
if self.with_conv:
|
||||
x = self.conv2(x)
|
||||
|
||||
return x
|
||||
+99
-6
@@ -1,35 +1,128 @@
|
||||
try:
|
||||
from .utils import check_duplicate_nodes, log
|
||||
duplicate_dirs = check_duplicate_nodes()
|
||||
if duplicate_dirs:
|
||||
warning_msg = f"WARNING: Found {len(duplicate_dirs)} other WanVideoWrapper directories:\n"
|
||||
for dir_path in duplicate_dirs:
|
||||
warning_msg += f" - {dir_path}\n"
|
||||
log.warning(warning_msg + "Please remove duplicates to avoid possible conflicts.")
|
||||
except:
|
||||
pass
|
||||
|
||||
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .recammaster.nodes import NODE_CLASS_MAPPINGS as RECAM_MASTER_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as RECAM_MASTER_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .unianimate.nodes import NODE_CLASS_MAPPINGS as UNIANIMATE_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as UNIANIMATE_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .skyreels.nodes import NODE_CLASS_MAPPINGS as SKYREELS_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as SKYREELS_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .fantasytalking.nodes import NODE_CLASS_MAPPINGS as FANTASYTALKING_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as FANTASYTALKING_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .nodes_sampler import NODE_CLASS_MAPPINGS as SAMPLER_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as SAMPLER_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .fun_camera.nodes import NODE_CLASS_MAPPINGS as FUN_CAMERA_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as FUN_CAMERA_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .uni3c.nodes import NODE_CLASS_MAPPINGS as UNI3C_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as UNI3C_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .controlnet.nodes import NODE_CLASS_MAPPINGS as CONTROLNET_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as CONTROLNET_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .ATI.nodes import NODE_CLASS_MAPPINGS as ATI_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as ATI_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .multitalk.nodes import NODE_CLASS_MAPPINGS as MULTITALK_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as MULTITALK_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .nodes_model_loading import NODE_CLASS_MAPPINGS as MODEL_LOADING_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as MODEL_LOADING_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .nodes_utility import NODE_CLASS_MAPPINGS as UTILITY_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as UTILITY_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .cache_methods.nodes_cache import NODE_CLASS_MAPPINGS as NODE_CACHE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as NODE_CACHE_DISPLAY_NAME_MAPPINGS
|
||||
from .nodes_deprecated import NODE_CLASS_MAPPINGS as DEPRECATED_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as DEPRECATED_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .s2v.nodes import NODE_CLASS_MAPPINGS as S2V_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as S2V_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .FlashVSR.flashvsr_nodes import NODE_CLASS_MAPPINGS as FLASHVSR_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as FLASHVSR_NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .mocha.nodes import NODE_CLASS_MAPPINGS as MOCHA_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as MOCHA_NODE_DISPLAY_NAME_MAPPINGS
|
||||
|
||||
#from .causvid.nodes import NODE_CLASS_MAPPINGS as CAUSVID_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as CAUSVID_NODE_DISPLAY_NAME_MAPPINGS
|
||||
try:
|
||||
from .qwen.qwen import NODE_CLASS_MAPPINGS as QWEN_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as QWEN_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: Qwen nodes not available due to error in importing them: {e}")
|
||||
QWEN_NODE_CLASS_MAPPINGS = {}
|
||||
QWEN_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
|
||||
try:
|
||||
from .fantasyportrait.nodes import NODE_CLASS_MAPPINGS as FANTASYPORTRAIT_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as FANTASYPORTRAIT_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: FantasyPortrait nodes not available due to error in importing them: {e}")
|
||||
FANTASYPORTRAIT_NODE_CLASS_MAPPINGS = {}
|
||||
FANTASYPORTRAIT_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
try:
|
||||
from .unianimate.nodes import NODE_CLASS_MAPPINGS as UNIANIMATE_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as UNIANIMATE_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: UniAnimate nodes not available due to error in importing them: {e}")
|
||||
UNIANIMATE_NODE_CLASS_MAPPINGS = {}
|
||||
UNIANIMATE_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
try:
|
||||
from .MTV.nodes import NODE_CLASS_MAPPINGS as MTV_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as MTV_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: MTV nodes not available due to error in importing them: {e}")
|
||||
MTV_NODE_CLASS_MAPPINGS = {}
|
||||
MTV_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
try:
|
||||
from .HuMo.nodes import NODE_CLASS_MAPPINGS as HUMO_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as HUMO_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: HuMo nodes not available due to error in importing them: {e}")
|
||||
HUMO_NODE_CLASS_MAPPINGS = {}
|
||||
HUMO_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
try:
|
||||
from .lynx.nodes import NODE_CLASS_MAPPINGS as LYNX_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as LYNX_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: Lynx nodes not available due to error in importing them: {e}")
|
||||
LYNX_NODE_CLASS_MAPPINGS = {}
|
||||
LYNX_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
try:
|
||||
from .Ovi.nodes_ovi import NODE_CLASS_MAPPINGS as OVI_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as OVI_NODE_DISPLAY_NAME_MAPPINGS
|
||||
except Exception as e:
|
||||
log.warning(f"WanVideoWrapper WARNING: Ovi nodes not available due to error in importing them: {e}")
|
||||
OVI_NODE_CLASS_MAPPINGS = {}
|
||||
OVI_NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
NODE_CLASS_MAPPINGS.update(RECAM_MASTER_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(UNIANIMATE_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(SKYREELS_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(FANTASYTALKING_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(FANTASYPORTRAIT_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(FUN_CAMERA_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(UNI3C_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(CONTROLNET_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(ATI_NODE_CLASS_MAPPINGS)
|
||||
|
||||
#NODE_CLASS_MAPPINGS.update(CAUSVID_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(MULTITALK_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(MODEL_LOADING_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(UTILITY_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(NODE_CACHE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(DEPRECATED_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(QWEN_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(MTV_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(S2V_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(HUMO_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(SAMPLER_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(LYNX_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(OVI_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(FLASHVSR_NODE_CLASS_MAPPINGS)
|
||||
NODE_CLASS_MAPPINGS.update(MOCHA_NODE_CLASS_MAPPINGS)
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(RECAM_MASTER_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(UNIANIMATE_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(SKYREELS_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(FANTASYTALKING_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(FANTASYPORTRAIT_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(FUN_CAMERA_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(UNI3C_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(CONTROLNET_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(ATI_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
|
||||
#NODE_DISPLAY_NAME_MAPPINGS.update(CAUSVID_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(MULTITALK_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(MODEL_LOADING_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(UTILITY_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(NODE_CACHE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(DEPRECATED_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(QWEN_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(MTV_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(S2V_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(HUMO_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(SAMPLER_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(LYNX_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(OVI_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(FLASHVSR_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(MOCHA_NODE_DISPLAY_NAME_MAPPINGS)
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -0,0 +1,159 @@
|
||||
from ..utils import log
|
||||
import torch
|
||||
|
||||
def set_transformer_cache_method(transformer, timesteps, cache_args=None):
|
||||
transformer.cache_device = cache_args["cache_device"]
|
||||
if cache_args["cache_type"] == "TeaCache":
|
||||
log.info(f"TeaCache: Using cache device: {transformer.cache_device}")
|
||||
transformer.teacache_state.clear_all()
|
||||
transformer.enable_teacache = True
|
||||
transformer.rel_l1_thresh = cache_args["rel_l1_thresh"]
|
||||
transformer.teacache_start_step = cache_args["start_step"]
|
||||
transformer.teacache_end_step = len(timesteps)-1 if cache_args["end_step"] == -1 else cache_args["end_step"]
|
||||
transformer.teacache_use_coefficients = cache_args["use_coefficients"]
|
||||
transformer.teacache_mode = cache_args["mode"]
|
||||
elif cache_args["cache_type"] == "MagCache":
|
||||
log.info(f"MagCache: Using cache device: {transformer.cache_device}")
|
||||
transformer.magcache_state.clear_all()
|
||||
transformer.enable_magcache = True
|
||||
transformer.magcache_start_step = cache_args["start_step"]
|
||||
transformer.magcache_end_step = len(timesteps)-1 if cache_args["end_step"] == -1 else cache_args["end_step"]
|
||||
transformer.magcache_thresh = cache_args["magcache_thresh"]
|
||||
transformer.magcache_K = cache_args["magcache_K"]
|
||||
elif cache_args["cache_type"] == "EasyCache":
|
||||
log.info(f"EasyCache: Using cache device: {transformer.cache_device}")
|
||||
transformer.easycache_state.clear_all()
|
||||
transformer.enable_easycache = True
|
||||
transformer.easycache_start_step = cache_args["start_step"]
|
||||
transformer.easycache_end_step = len(timesteps)-1 if cache_args["end_step"] == -1 else cache_args["end_step"]
|
||||
transformer.easycache_thresh = cache_args["easycache_thresh"]
|
||||
return transformer
|
||||
|
||||
class TeaCacheState:
|
||||
def __init__(self, cache_device='cpu'):
|
||||
self.cache_device = cache_device
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
def new_prediction(self, cache_device='cpu'):
|
||||
"""Create new prediction state and return its ID"""
|
||||
self.cache_device = cache_device
|
||||
pred_id = self._next_pred_id
|
||||
self._next_pred_id += 1
|
||||
self.states[pred_id] = {
|
||||
'previous_residual': None,
|
||||
'accumulated_rel_l1_distance': 0,
|
||||
'previous_modulated_input': None,
|
||||
'skipped_steps': [],
|
||||
}
|
||||
return pred_id
|
||||
|
||||
def update(self, pred_id, **kwargs):
|
||||
"""Update state for specific prediction"""
|
||||
if pred_id not in self.states:
|
||||
return None
|
||||
for key, value in kwargs.items():
|
||||
self.states[pred_id][key] = value
|
||||
|
||||
def get(self, pred_id):
|
||||
return self.states.get(pred_id, {})
|
||||
|
||||
def clear_all(self):
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
class MagCacheState:
|
||||
def __init__(self, cache_device='cpu'):
|
||||
self.cache_device = cache_device
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
def new_prediction(self, cache_device='cpu'):
|
||||
"""Create new prediction state and return its ID"""
|
||||
self.cache_device = cache_device
|
||||
pred_id = self._next_pred_id
|
||||
self._next_pred_id += 1
|
||||
self.states[pred_id] = {
|
||||
'residual_cache': None,
|
||||
'accumulated_ratio': 1.0,
|
||||
'accumulated_steps': 0,
|
||||
'accumulated_err': 0,
|
||||
'skipped_steps': [],
|
||||
}
|
||||
return pred_id
|
||||
|
||||
def update(self, pred_id, **kwargs):
|
||||
"""Update state for specific prediction"""
|
||||
if pred_id not in self.states:
|
||||
return None
|
||||
for key, value in kwargs.items():
|
||||
self.states[pred_id][key] = value
|
||||
|
||||
def get(self, pred_id):
|
||||
return self.states.get(pred_id, {})
|
||||
|
||||
def clear_all(self):
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
class EasyCacheState:
|
||||
def __init__(self, cache_device='cpu'):
|
||||
self.cache_device = cache_device
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
def new_prediction(self, cache_device='cpu'):
|
||||
"""Create a new prediction state and return its ID."""
|
||||
self.cache_device = cache_device
|
||||
pred_id = self._next_pred_id
|
||||
self._next_pred_id += 1
|
||||
self.states[pred_id] = {
|
||||
'previous_raw_input': None,
|
||||
'previous_raw_output': None,
|
||||
'cache': None,
|
||||
'accumulated_error': 0.0,
|
||||
'skipped_steps': [],
|
||||
'cache_ovi': None,
|
||||
}
|
||||
return pred_id
|
||||
|
||||
def update(self, pred_id, **kwargs):
|
||||
"""Update state for a specific prediction."""
|
||||
if pred_id not in self.states:
|
||||
return None
|
||||
for key, value in kwargs.items():
|
||||
self.states[pred_id][key] = value
|
||||
|
||||
def get(self, pred_id):
|
||||
return self.states.get(pred_id, {})
|
||||
|
||||
def clear_all(self):
|
||||
self.states = {}
|
||||
self._next_pred_id = 0
|
||||
|
||||
def relative_l1_distance(last_tensor, current_tensor):
|
||||
l1_distance = torch.abs(last_tensor.to(current_tensor.device) - current_tensor).mean()
|
||||
norm = torch.abs(last_tensor).mean()
|
||||
relative_l1_distance = l1_distance / norm
|
||||
return relative_l1_distance.to(torch.float32).to(current_tensor.device)
|
||||
|
||||
def cache_report(transformer, cache_args):
|
||||
cache_type = cache_args["cache_type"]
|
||||
states = (
|
||||
transformer.teacache_state.states if cache_type == "TeaCache" else
|
||||
transformer.magcache_state.states if cache_type == "MagCache" else
|
||||
transformer.easycache_state.states if cache_type == "EasyCache" else
|
||||
None
|
||||
)
|
||||
state_names = {
|
||||
0: "conditional",
|
||||
1: "unconditional"
|
||||
}
|
||||
for pred_id, state in states.items():
|
||||
name = state_names.get(pred_id, f"prediction_{pred_id}")
|
||||
if 'skipped_steps' in state:
|
||||
log.info(f"{cache_type} skipped: {len(state['skipped_steps'])} {name} steps: {state['skipped_steps']}")
|
||||
transformer.teacache_state.clear_all()
|
||||
transformer.magcache_state.clear_all()
|
||||
transformer.easycache_state.clear_all()
|
||||
del states
|
||||
@@ -0,0 +1,140 @@
|
||||
from comfy import model_management as mm
|
||||
|
||||
class WanVideoTeaCache:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"rel_l1_thresh": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.001,
|
||||
"tooltip": "Higher values will make TeaCache more aggressive, faster, but may cause artifacts. Good value range for 1.3B: 0.05 - 0.08, for other models 0.15-0.30"}),
|
||||
"start_step": ("INT", {"default": 1, "min": 0, "max": 9999, "step": 1, "tooltip": "Start percentage of the steps to apply TeaCache"}),
|
||||
"end_step": ("INT", {"default": -1, "min": -1, "max": 9999, "step": 1, "tooltip": "End steps to apply TeaCache"}),
|
||||
"cache_device": (["main_device", "offload_device"], {"default": "offload_device", "tooltip": "Device to cache to"}),
|
||||
"use_coefficients": ("BOOLEAN", {"default": True, "tooltip": "Use calculated coefficients for more accuracy. When enabled therel_l1_thresh should be about 10 times higher than without"}),
|
||||
},
|
||||
"optional": {
|
||||
"mode": (["e", "e0"], {"default": "e", "tooltip": "Choice between using e (time embeds, default) or e0 (modulated time embeds)"}),
|
||||
},
|
||||
}
|
||||
RETURN_TYPES = ("CACHEARGS",)
|
||||
RETURN_NAMES = ("cache_args",)
|
||||
FUNCTION = "process"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
DESCRIPTION = """
|
||||
Patch WanVideo model to use TeaCache. Speeds up inference by caching the output and
|
||||
applying it instead of doing the step. Best results are achieved by choosing the
|
||||
appropriate coefficients for the model. Early steps should never be skipped, with too
|
||||
aggressive values this can happen and the motion suffers. Starting later can help with that too.
|
||||
When NOT using coefficients, the threshold value should be
|
||||
about 10 times smaller than the value used with coefficients.
|
||||
|
||||
Official recommended values https://github.com/ali-vilab/TeaCache/tree/main/TeaCache4Wan2.1:
|
||||
|
||||
|
||||
<pre style='font-family:monospace'>
|
||||
+-------------------+--------+---------+--------+
|
||||
| Model | Low | Medium | High |
|
||||
+-------------------+--------+---------+--------+
|
||||
| Wan2.1 t2v 1.3B | 0.05 | 0.07 | 0.08 |
|
||||
| Wan2.1 t2v 14B | 0.14 | 0.15 | 0.20 |
|
||||
| Wan2.1 i2v 480P | 0.13 | 0.19 | 0.26 |
|
||||
| Wan2.1 i2v 720P | 0.18 | 0.20 | 0.30 |
|
||||
+-------------------+--------+---------+--------+
|
||||
</pre>
|
||||
"""
|
||||
|
||||
def process(self, rel_l1_thresh, start_step, end_step, cache_device, use_coefficients, mode="e"):
|
||||
if cache_device == "main_device":
|
||||
cache_device = mm.get_torch_device()
|
||||
else:
|
||||
cache_device = mm.unet_offload_device()
|
||||
cache_args = {
|
||||
"cache_type": "TeaCache",
|
||||
"rel_l1_thresh": rel_l1_thresh,
|
||||
"start_step": start_step,
|
||||
"end_step": end_step,
|
||||
"cache_device": cache_device,
|
||||
"use_coefficients": use_coefficients,
|
||||
"mode": mode,
|
||||
}
|
||||
return (cache_args,)
|
||||
|
||||
class WanVideoMagCache:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"magcache_thresh": ("FLOAT", {"default": 0.02, "min": 0.0, "max": 0.3, "step": 0.001, "tooltip": "How strongly to cache the output of diffusion model. This value must be non-negative."}),
|
||||
"magcache_K": ("INT", {"default": 4, "min": 0, "max": 6, "step": 1, "tooltip": "The maxium skip steps of MagCache."}),
|
||||
"start_step": ("INT", {"default": 1, "min": 0, "max": 9999, "step": 1, "tooltip": "Step to start applying MagCache"}),
|
||||
"end_step": ("INT", {"default": -1, "min": -1, "max": 9999, "step": 1, "tooltip": "Step to end applying MagCache"}),
|
||||
"cache_device": (["main_device", "offload_device"], {"default": "offload_device", "tooltip": "Device to cache to"}),
|
||||
},
|
||||
}
|
||||
RETURN_TYPES = ("CACHEARGS",)
|
||||
RETURN_NAMES = ("cache_args",)
|
||||
FUNCTION = "setargs"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
EXPERIMENTAL = True
|
||||
DESCRIPTION = "MagCache for WanVideoWrapper, source https://github.com/Zehong-Ma/MagCache"
|
||||
|
||||
def setargs(self, magcache_thresh, magcache_K, start_step, end_step, cache_device):
|
||||
if cache_device == "main_device":
|
||||
cache_device = mm.get_torch_device()
|
||||
else:
|
||||
cache_device = mm.unet_offload_device()
|
||||
|
||||
cache_args = {
|
||||
"cache_type": "MagCache",
|
||||
"magcache_thresh": magcache_thresh,
|
||||
"magcache_K": magcache_K,
|
||||
"start_step": start_step,
|
||||
"end_step": end_step,
|
||||
"cache_device": cache_device,
|
||||
}
|
||||
return (cache_args,)
|
||||
|
||||
class WanVideoEasyCache:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"easycache_thresh": ("FLOAT", {"default": 0.015, "min": 0.0, "max": 1.0, "step": 0.001, "tooltip": "How strongly to cache the output of diffusion model. This value must be non-negative."}),
|
||||
"start_step": ("INT", {"default": 10, "min": 0, "max": 9999, "step": 1, "tooltip": "Step to start applying EasyCache"}),
|
||||
"end_step": ("INT", {"default": -1, "min": -1, "max": 9999, "step": 1, "tooltip": "Step to end applying EasyCache"}),
|
||||
"cache_device": (["main_device", "offload_device"], {"default": "offload_device", "tooltip": "Device to cache to"}),
|
||||
},
|
||||
}
|
||||
RETURN_TYPES = ("CACHEARGS",)
|
||||
RETURN_NAMES = ("cache_args",)
|
||||
FUNCTION = "setargs"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
EXPERIMENTAL = True
|
||||
DESCRIPTION = "EasyCache for WanVideoWrapper, source https://github.com/H-EmbodVis/EasyCache"
|
||||
|
||||
def setargs(self, easycache_thresh, start_step, end_step, cache_device):
|
||||
if cache_device == "main_device":
|
||||
cache_device = mm.get_torch_device()
|
||||
else:
|
||||
cache_device = mm.unet_offload_device()
|
||||
|
||||
cache_args = {
|
||||
"cache_type": "EasyCache",
|
||||
"easycache_thresh": easycache_thresh,
|
||||
"start_step": start_step,
|
||||
"end_step": end_step,
|
||||
"cache_device": cache_device,
|
||||
}
|
||||
return (cache_args,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"WanVideoTeaCache": WanVideoTeaCache,
|
||||
"WanVideoMagCache": WanVideoMagCache,
|
||||
"WanVideoEasyCache": WanVideoEasyCache,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"WanVideoTeaCache": "WanVideo TeaCache",
|
||||
"WanVideoMagCache": "WanVideo MagCache",
|
||||
"WanVideoEasyCache": "WanVideo EasyCache"
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import numpy as np
|
||||
from typing import Callable, Optional, List
|
||||
|
||||
import torch
|
||||
from ..utils import log
|
||||
|
||||
def ordered_halving(val):
|
||||
bin_str = f"{val:064b}"
|
||||
@@ -182,3 +183,76 @@ def get_total_steps(
|
||||
)
|
||||
for i in range(len(timesteps))
|
||||
)
|
||||
|
||||
def create_window_mask(noise_pred_context, c, latent_video_length, context_overlap, looped=False, window_type="linear"):
|
||||
window_mask = torch.ones_like(noise_pred_context)
|
||||
|
||||
if window_type == "pyramid":
|
||||
# Create pyramid weights that peak in the middle
|
||||
length = noise_pred_context.shape[1]
|
||||
if length % 2 == 0:
|
||||
max_weight = length // 2
|
||||
weight_sequence = list(range(1, max_weight + 1, 1)) + list(range(max_weight, 0, -1))
|
||||
else:
|
||||
max_weight = (length + 1) // 2
|
||||
weight_sequence = list(range(1, max_weight, 1)) + [max_weight] + list(range(max_weight - 1, 0, -1))
|
||||
|
||||
# Normalize weights to range from 0 to 1
|
||||
max_val = max(weight_sequence)
|
||||
weight_sequence = [w / max_val for w in weight_sequence]
|
||||
|
||||
# Apply the weights to create the mask
|
||||
weights_tensor = torch.tensor(weight_sequence, device=noise_pred_context.device)
|
||||
weights_tensor = weights_tensor.view(1, -1, 1, 1)
|
||||
window_mask = weights_tensor.expand_as(window_mask).clone()
|
||||
|
||||
# Adjust for position in sequence if needed
|
||||
if not looped:
|
||||
if min(c) == 0: # First chunk
|
||||
left_ramp = torch.linspace(0, 1, context_overlap, device=noise_pred_context.device).view(1, -1, 1, 1)
|
||||
# Clone to avoid in-place memory conflict
|
||||
left_section = window_mask[:, :context_overlap].clone()
|
||||
window_mask[:, :context_overlap] = torch.maximum(left_section, left_ramp)
|
||||
|
||||
if max(c) == latent_video_length - 1: # Last chunk
|
||||
right_ramp = torch.linspace(1, 0, context_overlap, device=noise_pred_context.device).view(1, -1, 1, 1)
|
||||
# Clone to avoid in-place memory conflict
|
||||
right_section = window_mask[:, -context_overlap:].clone()
|
||||
window_mask[:, -context_overlap:] = torch.maximum(right_section, right_ramp)
|
||||
else: # Original "linear" window masking
|
||||
# Apply left-side blending for all except first chunk (or always in loop mode)
|
||||
if min(c) > 0 or (looped and max(c) == latent_video_length - 1):
|
||||
ramp_up = torch.linspace(0, 1, context_overlap, device=noise_pred_context.device)
|
||||
ramp_up = ramp_up.view(1, -1, 1, 1)
|
||||
window_mask[:, :context_overlap] = ramp_up
|
||||
|
||||
# Apply right-side blending for all except last chunk (or always in loop mode)
|
||||
if max(c) < latent_video_length - 1 or (looped and min(c) == 0):
|
||||
ramp_down = torch.linspace(1, 0, context_overlap, device=noise_pred_context.device)
|
||||
ramp_down = ramp_down.view(1, -1, 1, 1)
|
||||
window_mask[:, -context_overlap:] = ramp_down
|
||||
|
||||
return window_mask
|
||||
|
||||
class WindowTracker:
|
||||
def __init__(self, verbose=False):
|
||||
self.window_map = {} # Maps frame sequence to persistent ID
|
||||
self.next_id = 0
|
||||
self.cache_states = {} # Maps persistent ID to teacache state
|
||||
self.verbose = verbose
|
||||
|
||||
def get_window_id(self, frames):
|
||||
key = tuple(sorted(frames)) # Order-independent frame sequence
|
||||
if key not in self.window_map:
|
||||
self.window_map[key] = self.next_id
|
||||
if self.verbose:
|
||||
log.info(f"New window pattern {key} -> ID {self.next_id}")
|
||||
self.next_id += 1
|
||||
return self.window_map[key]
|
||||
|
||||
def get_teacache(self, window_id, base_state):
|
||||
if window_id not in self.cache_states:
|
||||
if self.verbose:
|
||||
log.info(f"Initializing persistent teacache for window {window_id}")
|
||||
self.cache_states[window_id] = base_state.copy()
|
||||
return self.cache_states[window_id]
|
||||
+7
-4
@@ -41,9 +41,11 @@ class WanVideoControlnetLoader:
|
||||
model_path = folder_paths.get_full_path_or_raise("controlnet", model)
|
||||
|
||||
sd = load_torch_file(model_path, device=transformer_load_device, safe_load=True)
|
||||
|
||||
|
||||
num_layers = 8 if "blocks.7.scale_shift_table" in sd else 6
|
||||
out_proj_dim = 5120 if num_layers == 6 else 1536
|
||||
out_proj_dim = sd["controlnet_blocks.0.bias"].shape[0]
|
||||
downscale_coef = 16 if out_proj_dim == 3072 else 8
|
||||
vae_channels = 48 if out_proj_dim == 3072 else 16
|
||||
|
||||
if not "control_encoder.0.0.weight" in sd:
|
||||
raise ValueError("Invalid ControlNet model")
|
||||
@@ -52,7 +54,7 @@ class WanVideoControlnetLoader:
|
||||
"added_kv_proj_dim": None,
|
||||
"attention_head_dim": 128,
|
||||
"cross_attn_norm": None,
|
||||
"downscale_coef": 8,
|
||||
"downscale_coef": downscale_coef,
|
||||
"eps": 1e-06,
|
||||
"ffn_dim": 8960,
|
||||
"freq_dim": 256,
|
||||
@@ -69,8 +71,9 @@ class WanVideoControlnetLoader:
|
||||
"qk_norm": "rms_norm_across_heads",
|
||||
"rope_max_seq_len": 1024,
|
||||
"text_dim": 4096,
|
||||
"vae_channels": 16
|
||||
"vae_channels": vae_channels
|
||||
}
|
||||
print(f"Loading WanControlnet with config: {controlnet_cfg}")
|
||||
|
||||
from .wan_controlnet import WanControlnet
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from diffusers.models.transformers.transformer_wan import (
|
||||
WanTransformerBlock
|
||||
)
|
||||
|
||||
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
||||
|
||||
def zero_module(module):
|
||||
for p in module.parameters():
|
||||
@@ -22,8 +23,6 @@ def zero_module(module):
|
||||
return module
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
||||
|
||||
class WanControlnet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
|
||||
r"""
|
||||
A Controlnet Transformer model for video-like data used in the Wan model.
|
||||
@@ -110,7 +109,7 @@ class WanControlnet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModel
|
||||
nn.GELU(approximate="tanh"),
|
||||
nn.GroupNorm(2, input_channels[0]),
|
||||
),
|
||||
## Temporal compression with spatial awareness
|
||||
## Spatio-Temporal compression with spatial awareness
|
||||
nn.Sequential(
|
||||
nn.Conv3d(input_channels[0], input_channels[1], kernel_size=3, stride=(2, 1, 1), padding=1),
|
||||
nn.GELU(approximate="tanh"),
|
||||
@@ -183,7 +182,6 @@ class WanControlnet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModel
|
||||
logger.warning(
|
||||
"Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
|
||||
)
|
||||
|
||||
rotary_emb = self.rope(hidden_states)
|
||||
|
||||
# 0. Controlnet encoder
|
||||
@@ -196,15 +194,30 @@ class WanControlnet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModel
|
||||
hidden_states = self.patch_embedding(hidden_states)
|
||||
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
||||
|
||||
# timestep shape: batch_size, or batch_size, seq_len (wan 2.2 ti2v)
|
||||
if timestep.ndim == 2:
|
||||
## for ComfyUI workflow
|
||||
if hidden_states.shape[1] != timestep.shape[1]:
|
||||
timestep = timestep.repeat_interleave(hidden_states.shape[1] // timestep.shape[1], dim=1)
|
||||
ts_seq_len = timestep.shape[1]
|
||||
timestep = timestep.flatten() # batch_size * seq_len
|
||||
else:
|
||||
ts_seq_len = None
|
||||
|
||||
temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
|
||||
timestep, encoder_hidden_states, encoder_hidden_states_image
|
||||
timestep, encoder_hidden_states, encoder_hidden_states_image, timestep_seq_len=ts_seq_len
|
||||
)
|
||||
timestep_proj = timestep_proj.unflatten(1, (6, -1))
|
||||
if ts_seq_len is not None:
|
||||
# batch_size, seq_len, 6, inner_dim
|
||||
timestep_proj = timestep_proj.unflatten(2, (6, -1))
|
||||
else:
|
||||
# batch_size, 6, inner_dim
|
||||
timestep_proj = timestep_proj.unflatten(1, (6, -1))
|
||||
|
||||
if encoder_hidden_states_image is not None:
|
||||
encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
|
||||
|
||||
# 2. Transformer blocks
|
||||
# 4. Transformer blocks
|
||||
controlnet_hidden_states = ()
|
||||
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
||||
for block, controlnet_block in zip(self.blocks, self.controlnet_blocks):
|
||||
@@ -246,13 +259,14 @@ if __name__ == "__main__":
|
||||
"text_dim": 4096,
|
||||
"downscale_coef": 8,
|
||||
"out_proj_dim": 12 * 128,
|
||||
"vae_channels": 16
|
||||
}
|
||||
controlnet = WanControlnet(**parameters)
|
||||
|
||||
hidden_states = torch.rand(1, 16, 21, 60, 90)
|
||||
timestep = torch.randint(low=0, high=1000, size=(1,), dtype=torch.long)
|
||||
hidden_states = torch.rand(1, 16, 13, 60, 90)
|
||||
timestep = torch.tensor([1000]).repeat(17550).unsqueeze(0) #torch.randint(low=0, high=1000, size=(1,), dtype=torch.long)
|
||||
encoder_hidden_states = torch.rand(1, 512, 4096)
|
||||
controlnet_states = torch.rand(1, 3, 81, 480, 720)
|
||||
controlnet_states = torch.rand(1, 3, 49, 480, 720)
|
||||
|
||||
controlnet_hidden_states = controlnet(
|
||||
hidden_states=hidden_states,
|
||||
@@ -264,4 +278,4 @@ if __name__ == "__main__":
|
||||
print("Output states count", len(controlnet_hidden_states[0]))
|
||||
for out_hidden_states in controlnet_hidden_states[0]:
|
||||
print(out_hidden_states.shape)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from accelerate import init_empty_weights
|
||||
|
||||
#based on https://github.com/huggingface/diffusers/blob/main/src/diffusers/quantizers/gguf/utils.py
|
||||
def _replace_linear(model, compute_dtype, state_dict, prefix="", patches=None, scale_weights=None, compile_args=None):
|
||||
|
||||
has_children = list(model.children())
|
||||
if not has_children:
|
||||
return
|
||||
|
||||
allow_compile = False
|
||||
|
||||
for name, module in model.named_children():
|
||||
if compile_args is not None:
|
||||
allow_compile = compile_args.get("allow_unmerged_lora_compile", False)
|
||||
module_prefix = prefix + name + "."
|
||||
module_prefix = module_prefix.replace("_orig_mod.", "")
|
||||
_replace_linear(module, compute_dtype, state_dict, module_prefix, patches, scale_weights, compile_args)
|
||||
|
||||
if isinstance(module, nn.Linear) and "loras" not in module_prefix:
|
||||
in_features = state_dict[module_prefix + "weight"].shape[1]
|
||||
out_features = state_dict[module_prefix + "weight"].shape[0]
|
||||
if scale_weights is not None:
|
||||
scale_key = f"{module_prefix}scale_weight"
|
||||
|
||||
with init_empty_weights():
|
||||
model._modules[name] = CustomLinear(
|
||||
in_features,
|
||||
out_features,
|
||||
module.bias is not None,
|
||||
compute_dtype=compute_dtype,
|
||||
scale_weight=scale_weights.get(scale_key) if scale_weights else None,
|
||||
allow_compile=allow_compile
|
||||
)
|
||||
model._modules[name].source_cls = type(module)
|
||||
model._modules[name].requires_grad_(False)
|
||||
|
||||
return model
|
||||
|
||||
def set_lora_params(module, patches, module_prefix="", device=torch.device("cpu")):
|
||||
remove_lora_from_module(module)
|
||||
# Recursively set lora_diffs and lora_strengths for all CustomLinear layers
|
||||
for name, child in module.named_children():
|
||||
params = list(child.parameters())
|
||||
if params:
|
||||
device = params[0].device
|
||||
else:
|
||||
device = torch.device("cpu")
|
||||
child_prefix = (f"{module_prefix}{name}.")
|
||||
set_lora_params(child, patches, child_prefix, device)
|
||||
if isinstance(module, CustomLinear):
|
||||
key = f"diffusion_model.{module_prefix}weight"
|
||||
patch = patches.get(key, [])
|
||||
#print(f"Processing LoRA patches for {key}: {len(patch)} patches found")
|
||||
if len(patch) == 0:
|
||||
key = key.replace("_orig_mod.", "")
|
||||
patch = patches.get(key, [])
|
||||
#print(f"Processing LoRA patches for {key}: {len(patch)} patches found")
|
||||
if len(patch) != 0:
|
||||
lora_diffs = []
|
||||
for p in patch:
|
||||
lora_obj = p[1]
|
||||
if "head" in key:
|
||||
continue # For now skip LoRA for head layers
|
||||
elif hasattr(lora_obj, "weights"):
|
||||
lora_diffs.append(lora_obj.weights)
|
||||
elif isinstance(lora_obj, tuple) and lora_obj[0] == "diff":
|
||||
lora_diffs.append(lora_obj[1])
|
||||
else:
|
||||
continue
|
||||
lora_strengths = [p[0] for p in patch]
|
||||
module.set_lora_diffs(lora_diffs, device=device)
|
||||
module.lora_strengths = lora_strengths
|
||||
module.step = 0 # Initialize step for LoRA scheduling
|
||||
|
||||
|
||||
class CustomLinear(nn.Linear):
|
||||
def __init__(
|
||||
self,
|
||||
in_features,
|
||||
out_features,
|
||||
bias=False,
|
||||
compute_dtype=None,
|
||||
device=None,
|
||||
scale_weight=None,
|
||||
allow_compile=False
|
||||
) -> None:
|
||||
super().__init__(in_features, out_features, bias, device)
|
||||
self.compute_dtype = compute_dtype
|
||||
self.lora_diffs = []
|
||||
self.step = 0
|
||||
self.scale_weight = scale_weight
|
||||
self.lora_strengths = []
|
||||
self.allow_compile = allow_compile
|
||||
|
||||
if not allow_compile:
|
||||
self._get_weight_with_lora = torch.compiler.disable()(self._get_weight_with_lora)
|
||||
|
||||
def set_lora_diffs(self, lora_diffs, device=torch.device("cpu")):
|
||||
self.lora_diffs = []
|
||||
for i, diff in enumerate(lora_diffs):
|
||||
if len(diff) > 1:
|
||||
self.register_buffer(f"lora_diff_{i}_0", diff[0].to(device, self.compute_dtype))
|
||||
self.register_buffer(f"lora_diff_{i}_1", diff[1].to(device, self.compute_dtype))
|
||||
setattr(self, f"lora_diff_{i}_2", diff[2])
|
||||
self.lora_diffs.append((f"lora_diff_{i}_0", f"lora_diff_{i}_1", f"lora_diff_{i}_2"))
|
||||
else:
|
||||
self.register_buffer(f"lora_diff_{i}_0", diff[0].to(device, self.compute_dtype))
|
||||
self.lora_diffs.append(f"lora_diff_{i}_0")
|
||||
|
||||
def _get_weight_with_lora(self, weight):
|
||||
"""Apply LoRA outside compiled region"""
|
||||
if not hasattr(self, "lora_diff_0_0"):
|
||||
return weight
|
||||
|
||||
for lora_diff_names, lora_strength in zip(self.lora_diffs, self.lora_strengths):
|
||||
if isinstance(lora_strength, list):
|
||||
lora_strength = lora_strength[self.step]
|
||||
if lora_strength == 0.0:
|
||||
continue
|
||||
elif lora_strength == 0.0:
|
||||
continue
|
||||
if isinstance(lora_diff_names, tuple):
|
||||
lora_diff_0 = getattr(self, lora_diff_names[0])
|
||||
lora_diff_1 = getattr(self, lora_diff_names[1])
|
||||
lora_diff_2 = getattr(self, lora_diff_names[2])
|
||||
patch_diff = torch.mm(
|
||||
lora_diff_0.flatten(start_dim=1),
|
||||
lora_diff_1.flatten(start_dim=1)
|
||||
).reshape(weight.shape) + 0
|
||||
alpha = lora_diff_2 / lora_diff_1.shape[0] if lora_diff_2 is not None else 1.0
|
||||
scale = lora_strength * alpha
|
||||
weight = weight.add(patch_diff, alpha=scale)
|
||||
else:
|
||||
lora_diff = getattr(self, lora_diff_names)
|
||||
weight = weight.add(lora_diff, alpha=lora_strength)
|
||||
return weight
|
||||
|
||||
def forward(self, input):
|
||||
if self.bias is not None:
|
||||
bias = self.bias.to(input)
|
||||
else:
|
||||
bias = None
|
||||
weight = self.weight.to(input)
|
||||
|
||||
if self.scale_weight is not None:
|
||||
if weight.numel() < input.numel():
|
||||
weight = weight * self.scale_weight
|
||||
else:
|
||||
input = input * self.scale_weight
|
||||
|
||||
weight = self._get_weight_with_lora(weight)
|
||||
|
||||
return torch.nn.functional.linear(input, weight, bias)
|
||||
|
||||
def remove_lora_from_module(module):
|
||||
for name, submodule in module.named_modules():
|
||||
if hasattr(submodule, "lora_diffs"):
|
||||
for i in range(len(submodule.lora_diffs)):
|
||||
if hasattr(submodule, f"lora_diff_{i}_0"):
|
||||
delattr(submodule, f"lora_diff_{i}_0")
|
||||
if hasattr(submodule, f"lora_diff_{i}_1"):
|
||||
delattr(submodule, f"lora_diff_{i}_1")
|
||||
if hasattr(submodule, f"lora_diff_{i}_2"):
|
||||
delattr(submodule, f"lora_diff_{i}_2")
|
||||
@@ -0,0 +1,104 @@
|
||||
import torch
|
||||
from comfy.model_management import get_autocast_device, get_torch_device
|
||||
|
||||
@torch.autocast(device_type=get_autocast_device(get_torch_device()), enabled=False)
|
||||
@torch.compiler.disable()
|
||||
def rope_apply_z(x, grid_sizes, freqs, inner_t, shift=6):
|
||||
n, c = x.size(2), x.size(3) // 2
|
||||
|
||||
# loop over samples
|
||||
output = []
|
||||
for i, (f, h, w) in enumerate(grid_sizes.tolist()):
|
||||
seq_len = f * h * w
|
||||
|
||||
# precompute multipliers
|
||||
x_i = torch.view_as_complex(
|
||||
x[i, :seq_len].to(torch.float64).reshape(seq_len, n, -1, 2)
|
||||
)
|
||||
start_ind = [sum(inner_t[i][:_]) for _ in range(len(inner_t[i]))]
|
||||
end_ind = [sum(inner_t[i][:_+1]) for _ in range(len(inner_t[i]))]
|
||||
|
||||
freq_select = []
|
||||
for shot_ind, (s, e) in enumerate(zip(start_ind, end_ind)):
|
||||
freq_select += [shot_ind * shift] * (e - s)
|
||||
shot_freqs = freqs[freq_select]
|
||||
|
||||
freqs_i = shot_freqs.view(f, 1, 1, -1).expand(f, h, w, -1).reshape(seq_len, 1, -1)
|
||||
|
||||
# apply rotary embedding
|
||||
x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
|
||||
x_i = torch.cat([x_i, x[i, seq_len:]])
|
||||
|
||||
# append to collection
|
||||
output.append(x_i)
|
||||
return torch.stack(output).float()
|
||||
|
||||
|
||||
@torch.autocast(device_type=get_autocast_device(get_torch_device()), enabled=False)
|
||||
@torch.compiler.disable()
|
||||
def rope_apply_c(x, freqs, inner_c, shift=6):
|
||||
|
||||
b, s, n, c = x.size(0), x.size(1), x.size(2), x.size(3) // 2
|
||||
|
||||
# loop over samples
|
||||
output = []
|
||||
for i in range(b):
|
||||
|
||||
# precompute multipliers
|
||||
x_i = torch.view_as_complex(
|
||||
x[i].to(torch.float64).reshape(s, n, -1, 2)
|
||||
)
|
||||
|
||||
freq_select = []
|
||||
for shot_ind, c_len in enumerate(inner_c[i]):
|
||||
freq_select += [shot_ind * shift] * c_len
|
||||
freq_select += [shot_ind+10] * (s-len(freq_select)) # extra suppression for the empty token
|
||||
shot_freqs = freqs[freq_select]
|
||||
|
||||
freqs_i = shot_freqs.view(s, 1, -1)
|
||||
|
||||
# apply rotary embedding
|
||||
x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
|
||||
|
||||
# append to collection
|
||||
output.append(x_i)
|
||||
return torch.stack(output).float()
|
||||
|
||||
@torch.autocast(device_type=get_autocast_device(get_torch_device()), enabled=False)
|
||||
@torch.compiler.disable()
|
||||
def rope_apply_echoshot(x, grid_sizes, freqs, inner_t, shift=4):
|
||||
n, c = x.size(2), x.size(3) // 2
|
||||
|
||||
# split freqs
|
||||
freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
|
||||
|
||||
# loop over samples
|
||||
output = []
|
||||
for i, (f, h, w) in enumerate(grid_sizes.tolist()):
|
||||
seq_len = f * h * w
|
||||
|
||||
# precompute multipliers
|
||||
x_i = torch.view_as_complex(
|
||||
x[i, :seq_len].to(torch.float64).reshape(seq_len, n, -1, 2)
|
||||
)
|
||||
start_ind = [sum(inner_t[i][:_]) for _ in range(len(inner_t[i]))]
|
||||
end_ind = [sum(inner_t[i][:_+1]) for _ in range(len(inner_t[i]))]
|
||||
freq_select = []
|
||||
for shot_ind, (s, e) in enumerate(zip(start_ind, end_ind)):
|
||||
freq_select += list(range(shot_ind * shift + s, shot_ind * shift + e))
|
||||
t_freqs = freqs[0][freq_select]
|
||||
|
||||
freqs_i = torch.cat([
|
||||
# freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
||||
t_freqs.view(f, 1, 1, -1).expand(f, h, w, -1), ###
|
||||
freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
||||
freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
|
||||
], dim=-1).reshape(seq_len, 1, -1)
|
||||
|
||||
# apply rotary embedding
|
||||
x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
|
||||
x_i = torch.cat([x_i, x[i, seq_len:]])
|
||||
|
||||
# append to collection
|
||||
output.append(x_i)
|
||||
return torch.stack(output).float()
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1587,9 +1587,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 335
|
||||
},
|
||||
{
|
||||
@@ -1668,8 +1668,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
335
|
||||
]
|
||||
|
||||
@@ -1751,8 +1751,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
334
|
||||
]
|
||||
@@ -1789,8 +1789,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
335
|
||||
]
|
||||
@@ -2252,8 +2252,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
350
|
||||
]
|
||||
@@ -2840,9 +2840,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 350
|
||||
},
|
||||
{
|
||||
@@ -2966,9 +2966,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 335
|
||||
},
|
||||
{
|
||||
@@ -5220,9 +5220,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 334
|
||||
},
|
||||
{
|
||||
|
||||
@@ -176,8 +176,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
103
|
||||
]
|
||||
@@ -826,9 +826,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 103
|
||||
},
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+811
-783
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+784
-744
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -747,8 +747,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
56
|
||||
]
|
||||
@@ -1263,9 +1263,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 56
|
||||
},
|
||||
{
|
||||
|
||||
@@ -794,8 +794,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
56
|
||||
]
|
||||
@@ -1719,9 +1719,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 56
|
||||
},
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -485,9 +485,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 89
|
||||
},
|
||||
{
|
||||
@@ -1699,8 +1699,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
89
|
||||
]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+1973
-1672
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+643
-423
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -1246,8 +1246,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
91
|
||||
]
|
||||
@@ -1313,9 +1313,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 91
|
||||
},
|
||||
{
|
||||
|
||||
@@ -402,8 +402,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
58
|
||||
]
|
||||
@@ -515,9 +515,9 @@
|
||||
"link": 57
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 58
|
||||
},
|
||||
{
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+1403
-1331
File diff suppressed because it is too large
Load Diff
@@ -587,8 +587,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
56
|
||||
]
|
||||
@@ -3788,9 +3788,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 56
|
||||
},
|
||||
{
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "206247b6-9fec-4ed2-8927-e4f388c674d4",
|
||||
"revision": 0,
|
||||
"last_node_id": 196,
|
||||
"last_link_id": 303,
|
||||
"last_link_id": 306,
|
||||
"nodes": [
|
||||
{
|
||||
"id": 42,
|
||||
@@ -1012,8 +1012,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
195
|
||||
]
|
||||
@@ -1051,8 +1051,8 @@
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "TEACACHEARGS",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "CACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 195
|
||||
}
|
||||
],
|
||||
@@ -1109,38 +1109,6 @@
|
||||
"ExpArgs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 140,
|
||||
"type": "GetNode",
|
||||
"pos": [
|
||||
724.8881225585938,
|
||||
-579.0637817382812
|
||||
],
|
||||
"size": [
|
||||
210,
|
||||
34
|
||||
],
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 18,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "TEACACHEARGS",
|
||||
"type": "TEACACHEARGS",
|
||||
"links": [
|
||||
235
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Get_TeaCache",
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"TeaCache"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 141,
|
||||
"type": "GetNode",
|
||||
@@ -1155,7 +1123,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 19,
|
||||
"order": 18,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1185,7 +1153,7 @@
|
||||
226
|
||||
],
|
||||
"flags": {},
|
||||
"order": 20,
|
||||
"order": 19,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1225,7 +1193,7 @@
|
||||
106
|
||||
],
|
||||
"flags": {},
|
||||
"order": 21,
|
||||
"order": 20,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1300,7 +1268,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 22,
|
||||
"order": 21,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1332,15 +1300,16 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 23,
|
||||
"order": 22,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "TEACACHEARGS",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "CACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
196
|
||||
196,
|
||||
305
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -1364,7 +1333,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 24,
|
||||
"order": 23,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1396,7 +1365,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 25,
|
||||
"order": 24,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1423,7 +1392,7 @@
|
||||
],
|
||||
"size": [
|
||||
428.4000244140625,
|
||||
860.4000244140625
|
||||
880.4000244140625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 88,
|
||||
@@ -1457,10 +1426,10 @@
|
||||
"link": 183
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"link": 235
|
||||
"type": "CACHEARGS",
|
||||
"link": 304
|
||||
},
|
||||
{
|
||||
"name": "slg_args",
|
||||
@@ -1506,7 +1475,8 @@
|
||||
true,
|
||||
"unipc",
|
||||
1,
|
||||
"comfy"
|
||||
"comfy",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1521,7 +1491,7 @@
|
||||
154
|
||||
],
|
||||
"flags": {},
|
||||
"order": 26,
|
||||
"order": 25,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1559,7 +1529,7 @@
|
||||
58
|
||||
],
|
||||
"flags": {},
|
||||
"order": 27,
|
||||
"order": 26,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1594,7 +1564,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 28,
|
||||
"order": 27,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1686,7 +1656,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 29,
|
||||
"order": 28,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1771,7 +1741,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 30,
|
||||
"order": 29,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1805,7 +1775,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 31,
|
||||
"order": 30,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1839,7 +1809,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 32,
|
||||
"order": 31,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1873,15 +1843,16 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 33,
|
||||
"order": 32,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "TEACACHEARGS",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "CACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
260
|
||||
260,
|
||||
306
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -1905,7 +1876,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 34,
|
||||
"order": 33,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1937,7 +1908,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 35,
|
||||
"order": 34,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -1955,101 +1926,6 @@
|
||||
"ExpArgs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 165,
|
||||
"type": "WanVideoDiffusionForcingSampler",
|
||||
"pos": [
|
||||
5483.89599609375,
|
||||
-510.88037109375
|
||||
],
|
||||
"size": [
|
||||
428.4000244140625,
|
||||
860.4000244140625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 103,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "model",
|
||||
"type": "WANVIDEOMODEL",
|
||||
"link": 256
|
||||
},
|
||||
{
|
||||
"name": "text_embeds",
|
||||
"type": "WANVIDEOTEXTEMBEDS",
|
||||
"link": 296
|
||||
},
|
||||
{
|
||||
"name": "image_embeds",
|
||||
"type": "WANVIDIMAGE_EMBEDS",
|
||||
"link": 258
|
||||
},
|
||||
{
|
||||
"name": "samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "prefix_samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": 259
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"link": 260
|
||||
},
|
||||
{
|
||||
"name": "slg_args",
|
||||
"shape": 7,
|
||||
"type": "SLGARGS",
|
||||
"link": 261
|
||||
},
|
||||
{
|
||||
"name": "experimental_args",
|
||||
"shape": 7,
|
||||
"type": "EXPERIMENTALARGS",
|
||||
"link": 262
|
||||
},
|
||||
{
|
||||
"name": "unianimate_poses",
|
||||
"shape": 7,
|
||||
"type": "UNIANIMATE_POSE",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
252
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"cnr_id": "ComfyUI-WanVideoWrapper",
|
||||
"ver": "e5a326c9811514f2c08c89bccea9a7c731d9a503",
|
||||
"Node name for S&R": "WanVideoDiffusionForcingSampler"
|
||||
},
|
||||
"widgets_values": [
|
||||
10,
|
||||
24.000000000000004,
|
||||
30,
|
||||
4.000000000000001,
|
||||
5.000000000000001,
|
||||
0,
|
||||
"fixed",
|
||||
true,
|
||||
"unipc",
|
||||
1,
|
||||
"comfy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 153,
|
||||
"type": "WanVideoEncode",
|
||||
@@ -2130,6 +2006,7 @@
|
||||
},
|
||||
{
|
||||
"name": "negative",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": 55
|
||||
}
|
||||
@@ -2207,7 +2084,7 @@
|
||||
60
|
||||
],
|
||||
"flags": {},
|
||||
"order": 36,
|
||||
"order": 35,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -2343,7 +2220,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 37,
|
||||
"order": 36,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -2654,101 +2531,6 @@
|
||||
80
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 104,
|
||||
"type": "WanVideoDiffusionForcingSampler",
|
||||
"pos": [
|
||||
3010,
|
||||
-400
|
||||
],
|
||||
"size": [
|
||||
428.4000244140625,
|
||||
860.4000244140625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 97,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "model",
|
||||
"type": "WANVIDEOMODEL",
|
||||
"link": 190
|
||||
},
|
||||
{
|
||||
"name": "text_embeds",
|
||||
"type": "WANVIDEOTEXTEMBEDS",
|
||||
"link": 192
|
||||
},
|
||||
{
|
||||
"name": "image_embeds",
|
||||
"type": "WANVIDIMAGE_EMBEDS",
|
||||
"link": 207
|
||||
},
|
||||
{
|
||||
"name": "samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "prefix_samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": 180
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"link": 196
|
||||
},
|
||||
{
|
||||
"name": "slg_args",
|
||||
"shape": 7,
|
||||
"type": "SLGARGS",
|
||||
"link": 240
|
||||
},
|
||||
{
|
||||
"name": "experimental_args",
|
||||
"shape": 7,
|
||||
"type": "EXPERIMENTALARGS",
|
||||
"link": 198
|
||||
},
|
||||
{
|
||||
"name": "unianimate_poses",
|
||||
"shape": 7,
|
||||
"type": "UNIANIMATE_POSE",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
178
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"cnr_id": "ComfyUI-WanVideoWrapper",
|
||||
"ver": "e5a326c9811514f2c08c89bccea9a7c731d9a503",
|
||||
"Node name for S&R": "WanVideoDiffusionForcingSampler"
|
||||
},
|
||||
"widgets_values": [
|
||||
24,
|
||||
24.000000000000004,
|
||||
30,
|
||||
4.000000000000001,
|
||||
5.000000000000001,
|
||||
0,
|
||||
"fixed",
|
||||
true,
|
||||
"unipc",
|
||||
1,
|
||||
"comfy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 90,
|
||||
"type": "VHS_VideoCombine",
|
||||
@@ -3137,7 +2919,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 38,
|
||||
"order": 37,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -3434,7 +3216,7 @@
|
||||
203.9819793701172
|
||||
],
|
||||
"flags": {},
|
||||
"order": 39,
|
||||
"order": 38,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -3474,7 +3256,7 @@
|
||||
139.27662658691406
|
||||
],
|
||||
"flags": {},
|
||||
"order": 40,
|
||||
"order": 39,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -3621,7 +3403,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 41,
|
||||
"order": 40,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -3663,6 +3445,7 @@
|
||||
},
|
||||
{
|
||||
"name": "negative",
|
||||
"shape": 7,
|
||||
"type": "CONDITIONING",
|
||||
"link": 265
|
||||
}
|
||||
@@ -3695,7 +3478,7 @@
|
||||
95.97175598144531
|
||||
],
|
||||
"flags": {},
|
||||
"order": 42,
|
||||
"order": 41,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -3718,7 +3501,7 @@
|
||||
106
|
||||
],
|
||||
"flags": {},
|
||||
"order": 43,
|
||||
"order": 42,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -3753,10 +3536,10 @@
|
||||
],
|
||||
"size": [
|
||||
528.6734619140625,
|
||||
234
|
||||
254
|
||||
],
|
||||
"flags": {},
|
||||
"order": 44,
|
||||
"order": 43,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
@@ -3788,6 +3571,12 @@
|
||||
"shape": 7,
|
||||
"type": "VACEPATH",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "fantasytalking_model",
|
||||
"shape": 7,
|
||||
"type": "FANTASYTALKINGMODEL",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
@@ -3829,7 +3618,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 45,
|
||||
"order": 44,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -3977,7 +3766,7 @@
|
||||
88
|
||||
],
|
||||
"flags": {},
|
||||
"order": 46,
|
||||
"order": 45,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -4000,7 +3789,7 @@
|
||||
451.9747314453125
|
||||
],
|
||||
"flags": {},
|
||||
"order": 47,
|
||||
"order": 46,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
@@ -4090,6 +3879,12 @@
|
||||
"type": "IMAGE",
|
||||
"link": 298
|
||||
},
|
||||
{
|
||||
"name": "get_image_size",
|
||||
"shape": 7,
|
||||
"type": "IMAGE",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "width_input",
|
||||
"shape": 7,
|
||||
@@ -4101,12 +3896,6 @@
|
||||
"shape": 7,
|
||||
"type": "INT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "get_image_size",
|
||||
"shape": 7,
|
||||
"type": "IMAGE",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
@@ -4158,7 +3947,7 @@
|
||||
85.25131225585938
|
||||
],
|
||||
"flags": {},
|
||||
"order": 48,
|
||||
"order": 47,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4233,7 +4022,7 @@
|
||||
88
|
||||
],
|
||||
"flags": {},
|
||||
"order": 49,
|
||||
"order": 48,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -4371,7 +4160,7 @@
|
||||
314
|
||||
],
|
||||
"flags": {},
|
||||
"order": 50,
|
||||
"order": 49,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4452,7 +4241,7 @@
|
||||
209.54696655273438
|
||||
],
|
||||
"flags": {},
|
||||
"order": 51,
|
||||
"order": 50,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -4524,7 +4313,7 @@
|
||||
130
|
||||
],
|
||||
"flags": {},
|
||||
"order": 52,
|
||||
"order": 51,
|
||||
"mode": 4,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4564,7 +4353,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 53,
|
||||
"order": 52,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4658,7 +4447,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 54,
|
||||
"order": 53,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4692,7 +4481,7 @@
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 55,
|
||||
"order": 54,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
@@ -4724,7 +4513,7 @@
|
||||
166.29330444335938
|
||||
],
|
||||
"flags": {},
|
||||
"order": 56,
|
||||
"order": 55,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [],
|
||||
@@ -4734,6 +4523,229 @@
|
||||
],
|
||||
"color": "#432",
|
||||
"bgcolor": "#653"
|
||||
},
|
||||
{
|
||||
"id": 140,
|
||||
"type": "GetNode",
|
||||
"pos": [
|
||||
724.8883666992188,
|
||||
-591.3699340820312
|
||||
],
|
||||
"size": [
|
||||
210,
|
||||
50
|
||||
],
|
||||
"flags": {
|
||||
"collapsed": true
|
||||
},
|
||||
"order": 56,
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "CACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"links": [
|
||||
235,
|
||||
304
|
||||
]
|
||||
}
|
||||
],
|
||||
"title": "Get_TeaCache",
|
||||
"properties": {},
|
||||
"widgets_values": [
|
||||
"TeaCache"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 104,
|
||||
"type": "WanVideoDiffusionForcingSampler",
|
||||
"pos": [
|
||||
3010,
|
||||
-400
|
||||
],
|
||||
"size": [
|
||||
428.4000244140625,
|
||||
860.4000244140625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 97,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "model",
|
||||
"type": "WANVIDEOMODEL",
|
||||
"link": 190
|
||||
},
|
||||
{
|
||||
"name": "text_embeds",
|
||||
"type": "WANVIDEOTEXTEMBEDS",
|
||||
"link": 192
|
||||
},
|
||||
{
|
||||
"name": "image_embeds",
|
||||
"type": "WANVIDIMAGE_EMBEDS",
|
||||
"link": 207
|
||||
},
|
||||
{
|
||||
"name": "samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "prefix_samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": 180
|
||||
},
|
||||
{
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "CACHEARGS",
|
||||
"link": 305
|
||||
},
|
||||
{
|
||||
"name": "slg_args",
|
||||
"shape": 7,
|
||||
"type": "SLGARGS",
|
||||
"link": 240
|
||||
},
|
||||
{
|
||||
"name": "experimental_args",
|
||||
"shape": 7,
|
||||
"type": "EXPERIMENTALARGS",
|
||||
"link": 198
|
||||
},
|
||||
{
|
||||
"name": "unianimate_poses",
|
||||
"shape": 7,
|
||||
"type": "UNIANIMATE_POSE",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
178
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"cnr_id": "ComfyUI-WanVideoWrapper",
|
||||
"ver": "e5a326c9811514f2c08c89bccea9a7c731d9a503",
|
||||
"Node name for S&R": "WanVideoDiffusionForcingSampler"
|
||||
},
|
||||
"widgets_values": [
|
||||
24,
|
||||
24.000000000000004,
|
||||
30,
|
||||
4.000000000000001,
|
||||
5.000000000000001,
|
||||
0,
|
||||
"fixed",
|
||||
true,
|
||||
"unipc",
|
||||
1,
|
||||
"comfy"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 165,
|
||||
"type": "WanVideoDiffusionForcingSampler",
|
||||
"pos": [
|
||||
5483.89599609375,
|
||||
-510.88037109375
|
||||
],
|
||||
"size": [
|
||||
428.4000244140625,
|
||||
860.4000244140625
|
||||
],
|
||||
"flags": {},
|
||||
"order": 103,
|
||||
"mode": 0,
|
||||
"inputs": [
|
||||
{
|
||||
"name": "model",
|
||||
"type": "WANVIDEOMODEL",
|
||||
"link": 256
|
||||
},
|
||||
{
|
||||
"name": "text_embeds",
|
||||
"type": "WANVIDEOTEXTEMBEDS",
|
||||
"link": 296
|
||||
},
|
||||
{
|
||||
"name": "image_embeds",
|
||||
"type": "WANVIDIMAGE_EMBEDS",
|
||||
"link": 258
|
||||
},
|
||||
{
|
||||
"name": "samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "prefix_samples",
|
||||
"shape": 7,
|
||||
"type": "LATENT",
|
||||
"link": 259
|
||||
},
|
||||
{
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "CACHEARGS",
|
||||
"link": 306
|
||||
},
|
||||
{
|
||||
"name": "slg_args",
|
||||
"shape": 7,
|
||||
"type": "SLGARGS",
|
||||
"link": 261
|
||||
},
|
||||
{
|
||||
"name": "experimental_args",
|
||||
"shape": 7,
|
||||
"type": "EXPERIMENTALARGS",
|
||||
"link": 262
|
||||
},
|
||||
{
|
||||
"name": "unianimate_poses",
|
||||
"shape": 7,
|
||||
"type": "UNIANIMATE_POSE",
|
||||
"link": null
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "samples",
|
||||
"type": "LATENT",
|
||||
"links": [
|
||||
252
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"cnr_id": "ComfyUI-WanVideoWrapper",
|
||||
"ver": "e5a326c9811514f2c08c89bccea9a7c731d9a503",
|
||||
"Node name for S&R": "WanVideoDiffusionForcingSampler"
|
||||
},
|
||||
"widgets_values": [
|
||||
10,
|
||||
24.000000000000004,
|
||||
30,
|
||||
4.000000000000001,
|
||||
5.000000000000001,
|
||||
0,
|
||||
"fixed",
|
||||
true,
|
||||
"unipc",
|
||||
1,
|
||||
"comfy"
|
||||
]
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
@@ -4889,14 +4901,6 @@
|
||||
0,
|
||||
"*"
|
||||
],
|
||||
[
|
||||
196,
|
||||
115,
|
||||
0,
|
||||
104,
|
||||
5,
|
||||
"TEACACHEARGS"
|
||||
],
|
||||
[
|
||||
197,
|
||||
87,
|
||||
@@ -5089,14 +5093,6 @@
|
||||
0,
|
||||
"IMAGE"
|
||||
],
|
||||
[
|
||||
235,
|
||||
140,
|
||||
0,
|
||||
103,
|
||||
5,
|
||||
"TEACACHEARGS"
|
||||
],
|
||||
[
|
||||
236,
|
||||
141,
|
||||
@@ -5217,14 +5213,6 @@
|
||||
4,
|
||||
"LATENT"
|
||||
],
|
||||
[
|
||||
260,
|
||||
162,
|
||||
0,
|
||||
165,
|
||||
5,
|
||||
"TEACACHEARGS"
|
||||
],
|
||||
[
|
||||
261,
|
||||
163,
|
||||
@@ -5456,6 +5444,30 @@
|
||||
156,
|
||||
2,
|
||||
"INT"
|
||||
],
|
||||
[
|
||||
304,
|
||||
140,
|
||||
0,
|
||||
103,
|
||||
5,
|
||||
"CACHEARGS"
|
||||
],
|
||||
[
|
||||
305,
|
||||
115,
|
||||
0,
|
||||
104,
|
||||
5,
|
||||
"CACHEARGS"
|
||||
],
|
||||
[
|
||||
306,
|
||||
162,
|
||||
0,
|
||||
165,
|
||||
5,
|
||||
"CACHEARGS"
|
||||
]
|
||||
],
|
||||
"groups": [
|
||||
@@ -5528,13 +5540,13 @@
|
||||
"config": {},
|
||||
"extra": {
|
||||
"ds": {
|
||||
"scale": 1.191817653772724,
|
||||
"scale": 0.611590904484147,
|
||||
"offset": [
|
||||
1695.7620823297345,
|
||||
1138.5391291690546
|
||||
426.87167769967925,
|
||||
1142.3743330459465
|
||||
]
|
||||
},
|
||||
"frontendVersion": "1.17.3",
|
||||
"frontendVersion": "1.22.0",
|
||||
"node_versions": {
|
||||
"ComfyUI-WanVideoWrapper": "5a2383621a05825d0d0437781afcb8552d9590fd",
|
||||
"comfy-core": "0.3.26",
|
||||
|
||||
@@ -668,8 +668,8 @@
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"type": "TEACACHEARGS",
|
||||
"name": "cache_args",
|
||||
"type": "CACHEARGS",
|
||||
"slot_index": 0,
|
||||
"links": [
|
||||
62
|
||||
@@ -736,9 +736,9 @@
|
||||
"link": null
|
||||
},
|
||||
{
|
||||
"name": "teacache_args",
|
||||
"name": "cache_args",
|
||||
"shape": 7,
|
||||
"type": "TEACACHEARGS",
|
||||
"type": "CACHEARGS",
|
||||
"link": 62
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,266 @@
|
||||
import math
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
def FeedForward(dim, mult=4):
|
||||
inner_dim = int(dim * mult)
|
||||
return nn.Sequential(
|
||||
nn.LayerNorm(dim),
|
||||
nn.Linear(dim, inner_dim, bias=False),
|
||||
nn.GELU(),
|
||||
nn.Linear(inner_dim, dim, bias=False),
|
||||
)
|
||||
|
||||
|
||||
def reshape_tensor(x, heads):
|
||||
bs, length, width = x.shape
|
||||
x = x.view(bs, length, heads, -1)
|
||||
x = x.transpose(1, 2)
|
||||
x = x.reshape(bs, heads, length, -1)
|
||||
return x
|
||||
|
||||
|
||||
class MultiProjModel(nn.Module):
|
||||
def __init__(self, adapter_in_dim=1024, cross_attention_dim=1024):
|
||||
super().__init__()
|
||||
|
||||
self.generator = None
|
||||
self.cross_attention_dim = cross_attention_dim
|
||||
self.eye_proj = torch.nn.Linear(6, cross_attention_dim, bias=False)
|
||||
self.emo_proj = torch.nn.Linear(30, cross_attention_dim, bias=False)
|
||||
self.mouth_proj = torch.nn.Linear(512, cross_attention_dim, bias=False)
|
||||
self.headpose_proj = torch.nn.Linear(6, cross_attention_dim, bias=False)
|
||||
|
||||
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
||||
|
||||
def forward(self, adapter_embeds):
|
||||
B, num_frames, C = adapter_embeds.shape
|
||||
embeds = adapter_embeds
|
||||
split_sizes = [6, 6, 30, 512]
|
||||
headpose, eye, emo, mouth = torch.split(embeds, split_sizes, dim=-1)
|
||||
headpose = self.norm(self.headpose_proj(headpose))
|
||||
eye = self.norm(self.eye_proj(eye))
|
||||
emo = self.norm(self.emo_proj(emo))
|
||||
mouth = self.norm(self.mouth_proj(mouth))
|
||||
|
||||
all_features = torch.stack([headpose, eye, emo, mouth], dim=2)
|
||||
result_final = all_features.view(B, num_frames * 4, self.cross_attention_dim)
|
||||
|
||||
return result_final
|
||||
|
||||
class PerceiverAttention(nn.Module):
|
||||
def __init__(self, *, dim, dim_head=64, heads=8):
|
||||
super().__init__()
|
||||
self.scale = dim_head**-0.5
|
||||
self.dim_head = dim_head
|
||||
self.heads = heads
|
||||
inner_dim = dim_head * heads
|
||||
|
||||
self.norm1 = nn.LayerNorm(dim)
|
||||
self.norm2 = nn.LayerNorm(dim)
|
||||
|
||||
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
||||
self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
|
||||
self.to_out = nn.Linear(inner_dim, dim, bias=False)
|
||||
|
||||
def forward(self, x, latents):
|
||||
"""
|
||||
Args:
|
||||
x (torch.Tensor): image features
|
||||
shape (b, n1, D)
|
||||
latent (torch.Tensor): latent features
|
||||
shape (b, n2, D)
|
||||
"""
|
||||
x = self.norm1(x)
|
||||
latents = self.norm2(latents)
|
||||
|
||||
b, l, _ = latents.shape
|
||||
|
||||
q = self.to_q(latents)
|
||||
kv_input = torch.cat((x, latents), dim=-2)
|
||||
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
||||
|
||||
q = reshape_tensor(q, self.heads)
|
||||
k = reshape_tensor(k, self.heads)
|
||||
v = reshape_tensor(v, self.heads)
|
||||
|
||||
# attention
|
||||
scale = 1 / math.sqrt(math.sqrt(self.dim_head))
|
||||
weight = (q * scale) @ (k * scale).transpose(
|
||||
-2, -1
|
||||
) # More stable with f16 than dividing afterwards
|
||||
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
||||
out = weight @ v
|
||||
|
||||
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
|
||||
|
||||
return self.to_out(out)
|
||||
|
||||
|
||||
class Resampler(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
dim=1024,
|
||||
depth=8,
|
||||
dim_head=64,
|
||||
heads=16,
|
||||
num_queries=8,
|
||||
embedding_dim=768,
|
||||
output_dim=1024,
|
||||
ff_mult=4,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
|
||||
|
||||
self.proj_in = nn.Linear(embedding_dim, dim)
|
||||
|
||||
self.proj_out = nn.Linear(dim, output_dim)
|
||||
self.norm_out = nn.LayerNorm(output_dim)
|
||||
|
||||
self.layers = nn.ModuleList([])
|
||||
for _ in range(depth):
|
||||
self.layers.append(
|
||||
nn.ModuleList(
|
||||
[
|
||||
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
||||
FeedForward(dim=dim, mult=ff_mult),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
def forward(self, x): # x (b, 512, 1)
|
||||
latents = self.latents.repeat(x.size(0), 1, 1)
|
||||
|
||||
x = self.proj_in(x) # (b, 512, 1024)
|
||||
|
||||
for attn, ff in self.layers:
|
||||
latents = attn(x, latents) + latents # b 16 1024
|
||||
latents = ff(latents) + latents
|
||||
|
||||
latents = self.proj_out(latents)
|
||||
return self.norm_out(latents)
|
||||
|
||||
|
||||
class PortraitAdapter(nn.Module):
|
||||
def __init__(self, adapter_in_dim: int, adapter_proj_dim: int, dtype: torch.dtype):
|
||||
super().__init__()
|
||||
|
||||
self.adapter_in_dim = adapter_in_dim
|
||||
self.adapter_proj_dim = adapter_proj_dim
|
||||
self.proj_model = self.init_proj(self.adapter_proj_dim)
|
||||
self.dtype = dtype
|
||||
|
||||
self.mouth_proj_model = Resampler(
|
||||
dim=1280,
|
||||
depth=4,
|
||||
dim_head=64,
|
||||
heads=20,
|
||||
num_queries=16,
|
||||
embedding_dim=512,
|
||||
output_dim=2048,
|
||||
ff_mult=4,
|
||||
)
|
||||
|
||||
self.emo_proj_model = Resampler(
|
||||
dim=1280,
|
||||
depth=4,
|
||||
dim_head=64,
|
||||
heads=20,
|
||||
num_queries=4,
|
||||
embedding_dim=30,
|
||||
output_dim=2048,
|
||||
ff_mult=4,
|
||||
)
|
||||
|
||||
def init_proj(self, cross_attention_dim=5120):
|
||||
proj_model = MultiProjModel(
|
||||
adapter_in_dim=self.adapter_in_dim, cross_attention_dim=cross_attention_dim
|
||||
)
|
||||
return proj_model
|
||||
|
||||
def get_adapter_proj(self, adapter_fea=None, adapter_scale=1.0, mouth_scale=1.0, emo_scale=1.0):
|
||||
split_sizes = [6, 6, 30, 512]
|
||||
headpose, eye, emo, mouth = torch.split(
|
||||
adapter_fea, split_sizes, dim=-1
|
||||
)
|
||||
B, frames, dim = mouth.shape
|
||||
mouth = mouth.view(B * frames, 1, 512)
|
||||
emo = emo.view(B * frames, 1, 30)
|
||||
|
||||
mouth_fea = self.mouth_proj_model(mouth) * mouth_scale
|
||||
emo_fea = self.emo_proj_model(emo) * emo_scale
|
||||
|
||||
mouth_fea = mouth_fea.view(B, frames, 16, 2048)
|
||||
emo_fea = emo_fea.view(B, frames, 4, 2048)
|
||||
|
||||
adapter_fea = self.proj_model(adapter_fea) * adapter_scale
|
||||
|
||||
adapter_fea = adapter_fea.view(B, frames, 4, 2048)
|
||||
|
||||
all_fea = torch.cat([adapter_fea, mouth_fea, emo_fea], dim=2)
|
||||
|
||||
result_final = all_fea.view(B, frames * 24, 2048)
|
||||
|
||||
return result_final
|
||||
|
||||
|
||||
def split_audio_adapter_sequence(self, adapter_proj_length, num_frames=80):
|
||||
tokens_pre_frame = adapter_proj_length / num_frames
|
||||
tokens_pre_latents_frame = tokens_pre_frame * 4
|
||||
half_tokens_pre_latents_frame = tokens_pre_latents_frame / 2
|
||||
pos_idx = []
|
||||
for i in range(int((num_frames - 1) / 4) + 1):
|
||||
if i == 0:
|
||||
pos_idx.append(0)
|
||||
else:
|
||||
begin_token_id = tokens_pre_frame * ((i - 1) * 4 + 1)
|
||||
end_token_id = tokens_pre_frame * (i * 4 + 1)
|
||||
pos_idx.append(int((sum([begin_token_id, end_token_id]) / 2)) - 1)
|
||||
pos_idx_range = [
|
||||
[
|
||||
idx - int(half_tokens_pre_latents_frame),
|
||||
idx + int(half_tokens_pre_latents_frame),
|
||||
]
|
||||
for idx in pos_idx
|
||||
]
|
||||
pos_idx_range[0] = [
|
||||
-(int(half_tokens_pre_latents_frame) * 2 - pos_idx_range[1][0]),
|
||||
pos_idx_range[1][0],
|
||||
]
|
||||
return pos_idx_range
|
||||
|
||||
|
||||
def split_tensor_with_padding(self, input_tensor, pos_idx_range, expand_length=0):
|
||||
pos_idx_range = [
|
||||
[idx[0] - expand_length, idx[1] + expand_length] for idx in pos_idx_range
|
||||
]
|
||||
sub_sequences = []
|
||||
seq_len = input_tensor.size(1)
|
||||
max_valid_idx = seq_len - 1
|
||||
k_lens_list = []
|
||||
for start, end in pos_idx_range:
|
||||
pad_front = max(-start, 0)
|
||||
pad_back = max(end - max_valid_idx, 0)
|
||||
|
||||
valid_start = max(start, 0)
|
||||
valid_end = min(end, max_valid_idx)
|
||||
|
||||
if valid_start <= valid_end:
|
||||
valid_part = input_tensor[:, valid_start : valid_end + 1, :]
|
||||
else:
|
||||
valid_part = input_tensor.new_zeros((1, 0, input_tensor.size(2)))
|
||||
|
||||
padded_subseq = F.pad(
|
||||
valid_part,
|
||||
(0, 0, 0, pad_back + pad_front, 0, 0),
|
||||
mode="constant",
|
||||
value=0,
|
||||
)
|
||||
k_lens_list.append(padded_subseq.size(-2) - pad_back - pad_front)
|
||||
|
||||
sub_sequences.append(padded_subseq)
|
||||
return torch.stack(sub_sequences, dim=1), torch.tensor(
|
||||
k_lens_list, dtype=torch.long
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,293 @@
|
||||
import os
|
||||
import torch
|
||||
import numpy as np
|
||||
from ..utils import log
|
||||
|
||||
from accelerate import init_empty_weights
|
||||
from accelerate.utils import set_module_tensor_to_device
|
||||
|
||||
import comfy.model_management as mm
|
||||
from comfy.utils import load_torch_file, ProgressBar
|
||||
import folder_paths
|
||||
|
||||
script_directory = os.path.dirname(os.path.abspath(__file__))
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
|
||||
alignment_model_path = os.path.join(script_directory, "models", "face_landmark.onnx")
|
||||
det_model_path = os.path.join(script_directory, "models", "face_det.onnx")
|
||||
|
||||
from .model import PortraitAdapter
|
||||
from .pd_fgc.pdf import get_drive_expression_pd_fgc, det_landmarks, FanEncoder
|
||||
from .pd_fgc.camer import CameraDemo
|
||||
from .pd_fgc.face_align import FaceAlignment
|
||||
|
||||
def load_pd_fgc_model(state_dict, providers):
|
||||
face_aligner = CameraDemo(
|
||||
face_alignment_module=FaceAlignment(
|
||||
providers=providers,
|
||||
alignment_model_path=alignment_model_path,
|
||||
det_model_path=det_model_path,
|
||||
),
|
||||
reset=False,
|
||||
)
|
||||
|
||||
pd_fpg_motion = FanEncoder()
|
||||
m, u = pd_fpg_motion.load_state_dict(state_dict, strict=False)
|
||||
pd_fpg_motion = pd_fpg_motion.eval()
|
||||
|
||||
return face_aligner, pd_fpg_motion
|
||||
|
||||
|
||||
def get_emo_feature(frame_list, face_aligner, pd_fpg_motion, device):
|
||||
|
||||
|
||||
comfy_pbar = ProgressBar(3)
|
||||
_, landmark_list, rect_list = det_landmarks(face_aligner, frame_list, comfy_pbar)
|
||||
|
||||
|
||||
# Fill missing landmarks and rects with previous valid one
|
||||
last_valid_landmark = None
|
||||
last_valid_rect = None
|
||||
for i in range(len(landmark_list)):
|
||||
if landmark_list[i] is None:
|
||||
landmark_list[i] = last_valid_landmark
|
||||
else:
|
||||
last_valid_landmark = landmark_list[i]
|
||||
if rect_list[i] is None:
|
||||
rect_list[i] = last_valid_rect
|
||||
else:
|
||||
last_valid_rect = rect_list[i]
|
||||
|
||||
# Forward fill for leading None values
|
||||
if landmark_list[0] is None:
|
||||
first_valid = next((l for l in landmark_list if l is not None), None)
|
||||
for i in range(len(landmark_list)):
|
||||
if landmark_list[i] is None:
|
||||
landmark_list[i] = first_valid
|
||||
else:
|
||||
break
|
||||
if rect_list[0] is None:
|
||||
first_valid = next((r for r in rect_list if r is not None), None)
|
||||
for i in range(len(rect_list)):
|
||||
if rect_list[i] is None:
|
||||
rect_list[i] = first_valid
|
||||
else:
|
||||
break
|
||||
|
||||
emo_list = get_drive_expression_pd_fgc(pd_fpg_motion, frame_list, landmark_list, device)
|
||||
comfy_pbar.update(1)
|
||||
|
||||
#emo_feat_list = []
|
||||
head_emo_feat_list = []
|
||||
for emo in emo_list:
|
||||
headpose_emb = emo["headpose_emb"]
|
||||
eye_embed = emo["eye_embed"]
|
||||
emo_embed = emo["emo_embed"]
|
||||
mouth_feat = emo["mouth_feat"]
|
||||
|
||||
emo_feat = torch.cat([eye_embed, emo_embed, mouth_feat], dim=1)
|
||||
head_emo_feat = torch.cat([headpose_emb, emo_feat], dim=1)
|
||||
|
||||
#emo_feat_list.append(emo_feat)
|
||||
head_emo_feat_list.append(head_emo_feat)
|
||||
|
||||
#emo_feat_all = torch.cat(emo_feat_list, dim=0).unsqueeze(0)
|
||||
head_emo_feat_all = torch.cat(head_emo_feat_list, dim=0).unsqueeze(0)
|
||||
|
||||
return head_emo_feat_all, rect_list, landmark_list
|
||||
|
||||
class FantasyPortraitFaceDetector:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"portrait_model": ("FANTASYPORTRAITMODEL",),
|
||||
"images": ("IMAGE",),
|
||||
},
|
||||
"optional": {
|
||||
"adapter_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "tooltip": "Scale for the adapter projection"}),
|
||||
"mouth_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "tooltip": "Scale for the mouth projection"}),
|
||||
"emo_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "tooltip": "Scale for the emotion projection"}),
|
||||
"device": (["cuda", "cpu"], {"default": "cuda", "tooltip": "Device to run the model on"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("PORTRAIT_EMBEDS", "BBOX", "LANDMARKS")
|
||||
RETURN_NAMES = ("portrait_embeds", "bbox", "landmarks")
|
||||
FUNCTION = "detect"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def detect(self, images, portrait_model, adapter_scale=1.0, mouth_scale=1.0, emo_scale=1.0, device="cuda"):
|
||||
B, H, W, C = images.shape
|
||||
num_frames = ((B - 1) // 4) * 4 + 1
|
||||
images = images.clone()[:num_frames]
|
||||
|
||||
def tensor_batch_to_numpy_list(images):
|
||||
images = images.detach().cpu()
|
||||
numpy_list = []
|
||||
for img in images:
|
||||
# img shape: (H, W, C)
|
||||
img = img.numpy()
|
||||
img = img[..., :3]
|
||||
img = (img * 255).clip(0, 255)
|
||||
img = img.astype(np.uint8)
|
||||
numpy_list.append(img)
|
||||
return numpy_list
|
||||
|
||||
|
||||
numpy_list = tensor_batch_to_numpy_list(images)
|
||||
|
||||
pd_fpg_sd = {}
|
||||
for k, v in portrait_model["sd"].items():
|
||||
if k.startswith("pd_fpg."):
|
||||
pd_fpg_sd[k.replace("pd_fpg.", "")] = v
|
||||
|
||||
if device == "cuda":
|
||||
providers = ["CUDAExecutionProvider"]
|
||||
else:
|
||||
providers = ["CPUExecutionProvider"]
|
||||
|
||||
face_aligner, pd_fpg_motion = load_pd_fgc_model(pd_fpg_sd, providers)
|
||||
|
||||
pd_fpg_motion.to(device)
|
||||
head_emo_feat_all, rect_list, landmark_list = get_emo_feature(numpy_list, face_aligner, pd_fpg_motion, device=device)
|
||||
log.info(f"FantasyPortraitFaceDetector: input frames: {num_frames}")
|
||||
log.info(f"FantasyPortraitFaceDetector: features extracted for {head_emo_feat_all.shape[1]} frames")
|
||||
pd_fpg_motion.to(offload_device)
|
||||
|
||||
portrait_model = portrait_model["proj_model"]
|
||||
|
||||
portrait_model.to(device)
|
||||
adapter_proj = portrait_model.get_adapter_proj(head_emo_feat_all.to(device, dtype=portrait_model.dtype), adapter_scale=adapter_scale, mouth_scale=mouth_scale, emo_scale=emo_scale)
|
||||
portrait_model.to(offload_device)
|
||||
|
||||
pos_idx_range = portrait_model.split_audio_adapter_sequence(adapter_proj.size(1), num_frames=num_frames)
|
||||
proj_split, context_lens = portrait_model.split_tensor_with_padding(adapter_proj, pos_idx_range, expand_length=0)
|
||||
|
||||
return (proj_split, rect_list, landmark_list)
|
||||
|
||||
class LandmarksToImage:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"landmarks": ("LANDMARKS", {"default": []}),
|
||||
"width": ("INT", {"default": 512, "min": 1, "max": 2048, "step": 1, "tooltip": "Width of the output image"}),
|
||||
"height": ("INT", {"default": 512, "min": 1, "max": 2048, "step": 1, "tooltip": "Height of the output image"}),
|
||||
|
||||
},
|
||||
"optional": {
|
||||
"image": ("IMAGE", ),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("keypoints_image",)
|
||||
FUNCTION = "drawkeypoints"
|
||||
CATEGORY = "LivePortrait"
|
||||
|
||||
def drawkeypoints(self, landmarks, width=512, height=512, image=None):
|
||||
import cv2
|
||||
if image is not None:
|
||||
image = image.detach().cpu().numpy() * 255
|
||||
|
||||
keypoints_img_list = []
|
||||
pbar = ProgressBar(len(landmarks))
|
||||
for i, lmk in enumerate(landmarks):
|
||||
if len(lmk) > 0:
|
||||
if image is None:
|
||||
keypoints_image = np.zeros((height, width, 3), dtype=np.uint8) * 255
|
||||
else:
|
||||
keypoints_image = image[i].copy()
|
||||
for (x, y) in lmk:
|
||||
cv2.circle(keypoints_image, (int(x), int(y)), radius=2, thickness=-1, color=(255,255,255))
|
||||
else:
|
||||
keypoints_image = np.zeros((height, width, 3), dtype=np.uint8) * 255
|
||||
keypoints_img_list.append(keypoints_image)
|
||||
pbar.update(1)
|
||||
|
||||
keypoints_img_tensor = (
|
||||
torch.stack([torch.from_numpy(np_array) for np_array in keypoints_img_list]) / 255).float()
|
||||
|
||||
return (keypoints_img_tensor,)
|
||||
|
||||
class WanVideoAddFantasyPortrait:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"embeds": ("WANVIDIMAGE_EMBEDS",),
|
||||
"portrait_embeds": ("PORTRAIT_EMBEDS",),
|
||||
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01, "tooltip": "Strength of the portrait embedding"}),
|
||||
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Start percentage of the embedding application"}),
|
||||
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "End percentage of the embedding application"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("WANVIDIMAGE_EMBEDS",)
|
||||
RETURN_NAMES = ("image_embeds",)
|
||||
FUNCTION = "add"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def add(self, embeds, portrait_embeds, strength, start_percent=0.0, end_percent=1.0):
|
||||
new_entry = {
|
||||
"adapter_proj": portrait_embeds,
|
||||
"strength": strength,
|
||||
"start_percent": start_percent,
|
||||
"end_percent": end_percent,
|
||||
}
|
||||
|
||||
updated = dict(embeds)
|
||||
updated["portrait_embeds"] = new_entry
|
||||
return (updated,)
|
||||
|
||||
class FantasyPortraitModelLoader:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": (folder_paths.get_filename_list("diffusion_models"), {"tooltip": "These models are loaded from the 'ComfyUI/models/diffusion_models' -folder",}),
|
||||
|
||||
"base_precision": (["fp32", "bf16", "fp16"], {"default": "fp16"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FANTASYPORTRAITMODEL",)
|
||||
RETURN_NAMES = ("model", )
|
||||
FUNCTION = "loadmodel"
|
||||
CATEGORY = "WanVideoWrapper"
|
||||
|
||||
def loadmodel(self, model, base_precision):
|
||||
device = mm.get_torch_device()
|
||||
offload_device = mm.unet_offload_device()
|
||||
base_dtype = {"fp8_e4m3fn": torch.float8_e4m3fn, "fp8_e4m3fn_fast": torch.float8_e4m3fn, "bf16": torch.bfloat16, "fp16": torch.float16, "fp16_fast": torch.float16, "fp32": torch.float32}[base_precision]
|
||||
|
||||
model_path = folder_paths.get_full_path_or_raise("diffusion_models", model)
|
||||
sd = load_torch_file(model_path, device=offload_device, safe_load=True)
|
||||
adapter_in_dim = sd["proj_model.norm.weight"].shape[0]
|
||||
|
||||
with init_empty_weights():
|
||||
fantasyportrait_proj_adapter = PortraitAdapter(adapter_in_dim=adapter_in_dim, adapter_proj_dim=adapter_in_dim, dtype=base_dtype)
|
||||
|
||||
for name, param in fantasyportrait_proj_adapter.named_parameters():
|
||||
set_module_tensor_to_device(fantasyportrait_proj_adapter, name, device=offload_device, dtype=base_dtype, value=sd[name])
|
||||
|
||||
fantasyportrait = {
|
||||
"proj_model": fantasyportrait_proj_adapter,
|
||||
"sd": sd,
|
||||
}
|
||||
|
||||
return (fantasyportrait,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"FantasyPortraitModelLoader": FantasyPortraitModelLoader,
|
||||
"FantasyPortraitFaceDetector": FantasyPortraitFaceDetector,
|
||||
"WanVideoAddFantasyPortrait": WanVideoAddFantasyPortrait,
|
||||
"LandmarksToImage": LandmarksToImage,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"FantasyPortraitModelLoader": "FantasyPortrait Model Loader",
|
||||
"FantasyPortraitFaceDetector": "FantasyPortrait Face Detector",
|
||||
"WanVideoAddFantasyPortrait": "WanVideo Add Fantasy Portrait",
|
||||
"LandmarksToImage": "Landmarks to Image",
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
Attribution 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More_considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution 4.0 International Public License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution 4.0 International Public License ("Public License"). To the
|
||||
extent this Public License may be interpreted as a contract, You are
|
||||
granted the Licensed Rights in consideration of Your acceptance of
|
||||
these terms and conditions, and the Licensor grants You such rights in
|
||||
consideration of benefits the Licensor receives from making the
|
||||
Licensed Material available under these terms and conditions.
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
d. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
f. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
g. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
h. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
i. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
j. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
k. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
4. If You Share Adapted Material You produce, the Adapter's
|
||||
License You apply must not prevent recipients of the Adapted
|
||||
Material from complying with this Public License.
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material; and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public licenses.
|
||||
Notwithstanding, Creative Commons may elect to apply one of its public
|
||||
licenses to material it publishes and in those instances will be
|
||||
considered the "Licensor." Except for the limited purpose of indicating
|
||||
that material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the public
|
||||
licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
@@ -0,0 +1,503 @@
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
def smoothing_factor(t_e, cutoff):
|
||||
r = 2 * math.pi * cutoff * t_e
|
||||
return r / (r + 1)
|
||||
|
||||
|
||||
def exponential_smoothing(a, x, x_prev):
|
||||
return a * x + (1 - a) * x_prev
|
||||
|
||||
|
||||
class OneEuroFilter:
|
||||
def __init__(self, dx0=0.0, d_cutoff=1.0):
|
||||
self.d_cutoff = float(d_cutoff)
|
||||
self.dx_prev = float(dx0)
|
||||
|
||||
def __call__(self, x, x_prev, fcmin=1.0, min_cutoff=1.0, beta=0.0):
|
||||
if x_prev is None:
|
||||
return x
|
||||
# t_e = 1
|
||||
a_d = smoothing_factor(fcmin, self.d_cutoff)
|
||||
dx = (x - x_prev) / fcmin
|
||||
dx_hat = exponential_smoothing(a_d, dx, self.dx_prev)
|
||||
cutoff = min_cutoff + beta * abs(dx_hat)
|
||||
a = smoothing_factor(fcmin, cutoff)
|
||||
x_hat = exponential_smoothing(a, x, x_prev)
|
||||
self.dx_prev = dx_hat
|
||||
return x_hat
|
||||
|
||||
|
||||
def cult_dis(old_kpts, new_kpts):
|
||||
dis = np.sqrt(
|
||||
np.square(new_kpts[:, 0] - old_kpts[:, 0])
|
||||
+ np.square(new_kpts[:, 1] - old_kpts[:, 1])
|
||||
)
|
||||
return dis
|
||||
|
||||
|
||||
class Smoother222(object):
|
||||
def __init__(self):
|
||||
# face config
|
||||
self.face_idx = list(range(0, 33))
|
||||
self.face_down_idx = list(range(9, 24))
|
||||
self.filter_face = OneEuroFilter()
|
||||
# nose config
|
||||
self.nose_idx = list(range(33, 48))
|
||||
self.filter_nose = OneEuroFilter()
|
||||
# eyebrow config
|
||||
self.eyebrow_idx = list(range(48, 74))
|
||||
self.filter_eyebrow = OneEuroFilter()
|
||||
# eye config
|
||||
self.left_eye_idx = list(range(74, 96))
|
||||
self.filter_left_eye = OneEuroFilter()
|
||||
self.right_eye_idx = list(range(96, 118))
|
||||
self.filter_right_eye = OneEuroFilter()
|
||||
# mouth config
|
||||
self.mouth_idx = list(range(118, 182))
|
||||
self.filter_mouth = OneEuroFilter()
|
||||
# pupil config
|
||||
self.left_pupil_idx = list(range(182, 202))
|
||||
self.filter_left_pupil = OneEuroFilter()
|
||||
self.right_pupil_idx = list(range(202, 222))
|
||||
self.filter_right_pupil = OneEuroFilter()
|
||||
self.prev_points = None
|
||||
|
||||
def smooth(self, new_points, face_dis):
|
||||
if self.prev_points is None:
|
||||
self.prev_points = new_points.copy()
|
||||
return new_points
|
||||
dis = cult_dis(self.prev_points, new_points) / face_dis
|
||||
smooth_points = new_points.copy()
|
||||
|
||||
# smooth face
|
||||
if np.mean(dis[self.face_down_idx]) < 0.005:
|
||||
ratio_tmp = np.mean(dis[self.face_down_idx]) / 0.005
|
||||
fcmin_tmp = 0.05 * ratio_tmp
|
||||
beta_tmp = 0.05 * ratio_tmp
|
||||
smooth_points[self.face_idx] = self.filter_face(
|
||||
new_points[self.face_idx],
|
||||
self.prev_points[self.face_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.face_down_idx]) < 0.02:
|
||||
ratio_tmp = (np.mean(dis[self.face_down_idx]) - 0.005) / (0.02 - 0.005)
|
||||
fcmin_tmp = 0.05 + (0.3 - 0.05) * ratio_tmp
|
||||
beta_tmp = 0.05 + (0.3 - 0.05) * ratio_tmp
|
||||
smooth_points[self.face_idx] = self.filter_face(
|
||||
new_points[self.face_idx],
|
||||
self.prev_points[self.face_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
smooth_points[self.face_idx] = self.filter_face(
|
||||
new_points[self.face_idx],
|
||||
self.prev_points[self.face_idx],
|
||||
fcmin=0.3,
|
||||
beta=0.3,
|
||||
)
|
||||
# smooth nose
|
||||
if np.mean(dis[self.nose_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.nose_idx]) / 0.003
|
||||
fcmin_tmp = 0.03 * ratio_tmp
|
||||
beta_tmp = 0.03 * ratio_tmp
|
||||
smooth_points[self.nose_idx] = self.filter_nose(
|
||||
new_points[self.nose_idx],
|
||||
self.prev_points[self.nose_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.nose_idx]) < 0.02:
|
||||
ratio_tmp = (np.mean(dis[self.nose_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
beta_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
smooth_points[self.nose_idx] = self.filter_nose(
|
||||
new_points[self.nose_idx],
|
||||
self.prev_points[self.nose_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# filter
|
||||
smooth_points[self.nose_idx] = self.filter_nose(
|
||||
new_points[self.nose_idx],
|
||||
self.prev_points[self.nose_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
# smooth eyebrow
|
||||
if np.mean(dis[self.eyebrow_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.eyebrow_idx]) / 0.003
|
||||
fcmin_tmp = 0.02 * ratio_tmp
|
||||
beta_tmp = 0.02 * ratio_tmp
|
||||
smooth_points[self.eyebrow_idx] = self.filter_eyebrow(
|
||||
new_points[self.eyebrow_idx],
|
||||
self.prev_points[self.eyebrow_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.eyebrow_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.eyebrow_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.02 + (0.5 - 0.02) * ratio_tmp
|
||||
beta_tmp = 0.02 + (0.5 - 0.02) * ratio_tmp
|
||||
smooth_points[self.eyebrow_idx] = self.filter_eyebrow(
|
||||
new_points[self.eyebrow_idx],
|
||||
self.prev_points[self.eyebrow_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# filter
|
||||
smooth_points[self.eyebrow_idx] = self.filter_eyebrow(
|
||||
new_points[self.eyebrow_idx],
|
||||
self.prev_points[self.eyebrow_idx],
|
||||
fcmin=0.5,
|
||||
beta=0.5,
|
||||
)
|
||||
# smooth eye
|
||||
if np.mean(dis[self.left_eye_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.left_eye_idx]) / 0.003
|
||||
fcmin_tmp = 0.03 * ratio_tmp
|
||||
beta_tmp = 0.03 * ratio_tmp
|
||||
smooth_points[self.left_eye_idx] = self.filter_left_eye(
|
||||
new_points[self.left_eye_idx],
|
||||
self.prev_points[self.left_eye_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.left_eye_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.left_eye_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
beta_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
smooth_points[self.left_eye_idx] = self.filter_left_eye(
|
||||
new_points[self.left_eye_idx],
|
||||
self.prev_points[self.left_eye_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# fast
|
||||
smooth_points[self.left_eye_idx] = self.filter_left_eye(
|
||||
new_points[self.left_eye_idx],
|
||||
self.prev_points[self.left_eye_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
if np.mean(dis[self.right_eye_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.right_eye_idx]) / 0.003
|
||||
fcmin_tmp = 0.03 * ratio_tmp
|
||||
beta_tmp = 0.03 * ratio_tmp
|
||||
smooth_points[self.right_eye_idx] = self.filter_right_eye(
|
||||
new_points[self.right_eye_idx],
|
||||
self.prev_points[self.right_eye_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.right_eye_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.right_eye_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
beta_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
smooth_points[self.right_eye_idx] = self.filter_right_eye(
|
||||
new_points[self.right_eye_idx],
|
||||
self.prev_points[self.right_eye_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# fast
|
||||
smooth_points[self.right_eye_idx] = self.filter_right_eye(
|
||||
new_points[self.right_eye_idx],
|
||||
self.prev_points[self.right_eye_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
|
||||
# smooth mouth
|
||||
if np.mean(dis[self.mouth_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.mouth_idx]) / 0.003
|
||||
fcmin_tmp = 0.05 * ratio_tmp
|
||||
beta_tmp = 0.05 * ratio_tmp
|
||||
smooth_points[self.mouth_idx] = self.filter_mouth(
|
||||
new_points[self.mouth_idx],
|
||||
self.prev_points[self.mouth_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.mouth_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.mouth_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.05 + (0.7 - 0.05) * ratio_tmp
|
||||
beta_tmp = 0.05 + (0.7 - 0.05) * ratio_tmp
|
||||
smooth_points[self.mouth_idx] = self.filter_mouth(
|
||||
new_points[self.mouth_idx],
|
||||
self.prev_points[self.mouth_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# fast
|
||||
smooth_points[self.mouth_idx] = self.filter_mouth(
|
||||
new_points[self.mouth_idx],
|
||||
self.prev_points[self.mouth_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
|
||||
# smooth pupil
|
||||
if np.mean(dis[self.left_pupil_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.left_pupil_idx]) / 0.003
|
||||
fcmin_tmp = 0.03 * ratio_tmp
|
||||
beta_tmp = 0.03 * ratio_tmp
|
||||
smooth_points[self.left_pupil_idx] = self.filter_left_pupil(
|
||||
new_points[self.left_pupil_idx],
|
||||
self.prev_points[self.left_pupil_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.left_pupil_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.left_pupil_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
beta_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
smooth_points[self.left_pupil_idx] = self.filter_left_pupil(
|
||||
new_points[self.left_pupil_idx],
|
||||
self.prev_points[self.left_pupil_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# fast
|
||||
smooth_points[self.left_pupil_idx] = self.filter_left_pupil(
|
||||
new_points[self.left_pupil_idx],
|
||||
self.prev_points[self.left_pupil_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
if np.mean(dis[self.right_pupil_idx]) < 0.003:
|
||||
# stable
|
||||
ratio_tmp = np.mean(dis[self.right_pupil_idx]) / 0.003
|
||||
fcmin_tmp = 0.03 * ratio_tmp
|
||||
beta_tmp = 0.03 * ratio_tmp
|
||||
smooth_points[self.right_pupil_idx] = self.filter_right_pupil(
|
||||
new_points[self.right_pupil_idx],
|
||||
self.prev_points[self.right_pupil_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
elif np.mean(dis[self.right_pupil_idx]) < 0.02:
|
||||
# filter
|
||||
ratio_tmp = (np.mean(dis[self.right_pupil_idx]) - 0.003) / (0.02 - 0.003)
|
||||
fcmin_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
beta_tmp = 0.03 + (0.7 - 0.03) * ratio_tmp
|
||||
smooth_points[self.right_pupil_idx] = self.filter_right_pupil(
|
||||
new_points[self.right_pupil_idx],
|
||||
self.prev_points[self.right_pupil_idx],
|
||||
fcmin=fcmin_tmp,
|
||||
beta=beta_tmp,
|
||||
)
|
||||
else:
|
||||
# fast
|
||||
smooth_points[self.right_pupil_idx] = self.filter_right_pupil(
|
||||
new_points[self.right_pupil_idx],
|
||||
self.prev_points[self.right_pupil_idx],
|
||||
fcmin=0.7,
|
||||
beta=0.7,
|
||||
)
|
||||
|
||||
# update pre points
|
||||
self.prev_points = smooth_points
|
||||
return smooth_points
|
||||
|
||||
|
||||
class CameraDemo(object):
|
||||
def __init__(self, face_alignment_module, reset=False):
|
||||
self.face_alignment_module = face_alignment_module
|
||||
self.face_prob_th = 0.0001
|
||||
self.min_face = 96
|
||||
self.face_image_size = self.face_alignment_module.face_image_size
|
||||
self.trackingFaces = []
|
||||
self.reset = reset
|
||||
|
||||
def reset_track(self):
|
||||
self.trackingFaces = []
|
||||
|
||||
def forward(self, src_image, reset=False, pre_rect=None):
|
||||
|
||||
if self.reset or reset:
|
||||
self.trackingFaces = []
|
||||
|
||||
if len(self.trackingFaces) == 0:
|
||||
if pre_rect is not None:
|
||||
detected_faces = [pre_rect]
|
||||
else:
|
||||
detected_faces, _, _ = self.face_alignment_module.face_detector.detect(
|
||||
src_image
|
||||
)
|
||||
for face_rect in detected_faces:
|
||||
new_tracking_object = {
|
||||
"face_rect": face_rect,
|
||||
"rotate_angle": 0.0,
|
||||
"pre_kpt_222": None,
|
||||
"face_dis": np.sqrt(
|
||||
np.square((face_rect[2] - face_rect[0]))
|
||||
+ np.square((face_rect[3] - face_rect[1]))
|
||||
),
|
||||
"smoother_222": Smoother222(),
|
||||
"prob": 0,
|
||||
}
|
||||
self.trackingFaces.append(new_tracking_object)
|
||||
else:
|
||||
detected_faces, _, _ = self.face_alignment_module.face_detector.detect(
|
||||
src_image
|
||||
)
|
||||
for face_rect in detected_faces:
|
||||
new_tracking_object = {
|
||||
"face_rect": face_rect,
|
||||
"rotate_angle": 0.0,
|
||||
"pre_kpt_222": None,
|
||||
"face_dis": np.sqrt(
|
||||
np.square((face_rect[2] - face_rect[0]))
|
||||
+ np.square((face_rect[3] - face_rect[1]))
|
||||
),
|
||||
"smoother_222": Smoother222(),
|
||||
"prob": 0,
|
||||
}
|
||||
self.trackingFaces.append(new_tracking_object)
|
||||
|
||||
delete_idx_list = []
|
||||
for face_idx, tracking_face in enumerate(self.trackingFaces):
|
||||
if tracking_face["pre_kpt_222"] is not None:
|
||||
result_dict = self.face_alignment_module.forward(
|
||||
src_image, pre_pts=tracking_face["pre_kpt_222"], iterations=3
|
||||
)
|
||||
else:
|
||||
result_dict = self.face_alignment_module.forward(
|
||||
src_image, face_box=tracking_face["face_rect"], iterations=3
|
||||
)
|
||||
|
||||
if result_dict["prob"] < self.face_prob_th:
|
||||
if not face_idx in delete_idx_list:
|
||||
delete_idx_list.append(face_idx)
|
||||
continue
|
||||
|
||||
landmarks_final = tracking_face["smoother_222"].smooth(
|
||||
result_dict["pt222"], tracking_face["face_dis"]
|
||||
)
|
||||
tracking_face["pre_kpt_222"] = landmarks_final
|
||||
|
||||
left_eye_corner = landmarks_final[74]
|
||||
right_eye_corner = landmarks_final[96]
|
||||
|
||||
radian = np.arctan2(
|
||||
right_eye_corner[1] - left_eye_corner[1],
|
||||
right_eye_corner[0] - left_eye_corner[0] + 0.00000001,
|
||||
)
|
||||
rotate_angle = np.rad2deg(radian)
|
||||
face_x_min, face_x_max = np.min(landmarks_final[:, 0]), np.max(
|
||||
landmarks_final[:, 0]
|
||||
)
|
||||
face_y_min, face_y_max = np.min(landmarks_final[:, 1]), np.max(
|
||||
landmarks_final[:, 1]
|
||||
)
|
||||
face_bbox = [face_x_min, face_y_min, face_x_max, face_y_max]
|
||||
face_dis = np.linalg.norm(landmarks_final[0] - landmarks_final[32])
|
||||
|
||||
if (
|
||||
face_x_max - face_x_min < self.min_face
|
||||
or face_y_max - face_y_min < self.min_face
|
||||
):
|
||||
if not face_idx in delete_idx_list:
|
||||
delete_idx_list.append(face_idx)
|
||||
|
||||
euler_pred = result_dict["euler_rad"]
|
||||
pitch = np.rad2deg(euler_pred[0])
|
||||
yaw = np.rad2deg(euler_pred[1])
|
||||
roll = np.rad2deg(euler_pred[2])
|
||||
# print("pitch, yaw, roll", pitch, yaw, roll)
|
||||
|
||||
# one filter model
|
||||
max_euler = abs(pitch) + (abs(yaw) * 0.6)
|
||||
face_dis *= 1.0 + max_euler / 18.0
|
||||
|
||||
# two filter model
|
||||
tracking_face["face_rect"] = face_bbox
|
||||
tracking_face["rotate_angle"] = rotate_angle
|
||||
tracking_face["face_dis"] = face_dis
|
||||
tracking_face["prob"] = result_dict["prob"]
|
||||
tracking_face["pitch"] = pitch
|
||||
tracking_face["yaw"] = yaw
|
||||
tracking_face["roll"] = roll
|
||||
tracking_face["euler_rad"] = result_dict["euler_rad"]
|
||||
|
||||
if len(self.trackingFaces) > 1:
|
||||
for face_idx, tracking_face_target in enumerate(self.trackingFaces):
|
||||
if face_idx in delete_idx_list:
|
||||
continue
|
||||
for idx, tracking_face in enumerate(self.trackingFaces):
|
||||
if idx in delete_idx_list:
|
||||
continue
|
||||
if face_idx == idx:
|
||||
continue
|
||||
iou_temp = self.count_iou(
|
||||
tracking_face_target["face_rect"], tracking_face["face_rect"]
|
||||
)
|
||||
# prog 2
|
||||
if iou_temp > 0.12:
|
||||
if (
|
||||
self.area(tracking_face_target["face_rect"])
|
||||
- self.area(tracking_face["face_rect"])
|
||||
< 0
|
||||
):
|
||||
if not face_idx in delete_idx_list:
|
||||
delete_idx_list.append(face_idx)
|
||||
else:
|
||||
if not idx in delete_idx_list:
|
||||
delete_idx_list.append(idx)
|
||||
|
||||
idx_offset = 0
|
||||
for delete_idx in sorted(delete_idx_list):
|
||||
self.trackingFaces.pop(delete_idx - idx_offset)
|
||||
idx_offset += 1
|
||||
|
||||
return self.trackingFaces
|
||||
|
||||
def count_iou(self, boxA, boxB):
|
||||
# determine the (x, y)-coordinates of the intersection rectangle
|
||||
xA = max(boxA[0], boxB[0])
|
||||
yA = max(boxA[1], boxB[1])
|
||||
xB = min(boxA[2], boxB[2])
|
||||
yB = min(boxA[3], boxB[3])
|
||||
|
||||
# compute the area of intersection rectangle
|
||||
interArea = abs(max((xB - xA, 0)) * max((yB - yA), 0))
|
||||
if interArea == 0:
|
||||
return 0
|
||||
# compute the area of both the prediction and ground-truth
|
||||
# rectangles
|
||||
boxAArea = abs((boxA[2] - boxA[0]) * (boxA[3] - boxA[1]))
|
||||
boxBArea = abs((boxB[2] - boxB[0]) * (boxB[3] - boxB[1]))
|
||||
|
||||
# compute the intersection over union by taking the intersection
|
||||
# area and dividing it by the sum of prediction + ground-truth
|
||||
# areas - the interesection area
|
||||
iou = interArea / float(boxAArea + boxBArea - interArea)
|
||||
|
||||
# return the intersection over union value
|
||||
return iou
|
||||
|
||||
def area(self, bbox):
|
||||
w = bbox[3] - bbox[1]
|
||||
h = bbox[2] - bbox[0]
|
||||
return w * h
|
||||
@@ -0,0 +1,117 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from .face_det import FaceDet
|
||||
from .face_utils import (create_onnx_session, get_warp_mat_bbox,
|
||||
get_warp_mat_bbox_by_gt_pts_float, transform_points)
|
||||
|
||||
|
||||
class FaceAlignment(object):
|
||||
def __init__(self, providers=["CUDAExecutionProvider"], alignment_model_path="", det_model_path=""):
|
||||
expand_ratio = 0.15
|
||||
|
||||
self.face_alignment_net_222 = create_onnx_session(
|
||||
alignment_model_path, providers=providers
|
||||
)
|
||||
self.onnx_input_name_222 = self.face_alignment_net_222.get_inputs()[0].name
|
||||
self.onnx_output_name_222 = [
|
||||
output.name for output in self.face_alignment_net_222.get_outputs()
|
||||
]
|
||||
self.face_image_size = 128
|
||||
|
||||
self.face_detector = FaceDet(det_model_path, providers=providers)
|
||||
self.expand_ratio = expand_ratio
|
||||
|
||||
def onnx_infer(self, input_uint8):
|
||||
assert input_uint8.shape[0] == input_uint8.shape[1] == self.face_image_size
|
||||
onnx_input = (
|
||||
input_uint8.transpose((2, 0, 1)).astype(np.float32)[np.newaxis, :, :, :]
|
||||
/ 255.0
|
||||
)
|
||||
landmark, euler, prob = self.face_alignment_net_222.run(
|
||||
self.onnx_output_name_222, {self.onnx_input_name_222: onnx_input}
|
||||
)
|
||||
|
||||
landmark = (
|
||||
np.reshape(landmark[0], (2, -1)).transpose((1, 0)) * self.face_image_size
|
||||
)
|
||||
left_eye_corner = landmark[74]
|
||||
right_eye_corner = landmark[96]
|
||||
radian = np.arctan2(
|
||||
right_eye_corner[1] - left_eye_corner[1],
|
||||
right_eye_corner[0] - left_eye_corner[0] + 0.00000001,
|
||||
)
|
||||
euler_rad = np.array([euler[0, 0], euler[0, 1], radian], dtype=np.float32)
|
||||
prob = prob[0]
|
||||
|
||||
return landmark, euler_rad, prob
|
||||
|
||||
def forward(self, src_image, face_box=None, pre_pts=None, iterations=3):
|
||||
if pre_pts is None:
|
||||
if face_box is None:
|
||||
# Detect max size face
|
||||
bounding_boxes, _, score = self.face_detector.detect(src_image)
|
||||
print("facedet score", score)
|
||||
if len(bounding_boxes) == 0:
|
||||
return None
|
||||
bbox = np.zeros(4, dtype=np.float32)
|
||||
if len(bounding_boxes) >= 1:
|
||||
max_area = 0.0
|
||||
for each_bbox in bounding_boxes:
|
||||
area = (each_bbox[2] - each_bbox[0]) * (
|
||||
each_bbox[3] - each_bbox[1]
|
||||
)
|
||||
if area > max_area:
|
||||
bbox[:4] = each_bbox[:4]
|
||||
max_area = area
|
||||
else:
|
||||
bbox = bounding_boxes[0, :4]
|
||||
else:
|
||||
bbox = face_box.copy()
|
||||
M_Face = get_warp_mat_bbox(
|
||||
bbox, 0, self.face_image_size, expand_ratio=self.expand_ratio
|
||||
)
|
||||
else:
|
||||
left_eye_corner = pre_pts[74]
|
||||
right_eye_corner = pre_pts[96]
|
||||
|
||||
radian = np.arctan2(
|
||||
right_eye_corner[1] - left_eye_corner[1],
|
||||
right_eye_corner[0] - left_eye_corner[0] + 0.00000001,
|
||||
)
|
||||
M_Face = get_warp_mat_bbox_by_gt_pts_float(
|
||||
pre_pts,
|
||||
np.rad2deg(radian),
|
||||
self.face_image_size,
|
||||
expand_ratio=self.expand_ratio,
|
||||
)
|
||||
|
||||
face_input = cv2.warpAffine(
|
||||
src_image, M_Face, (self.face_image_size, self.face_image_size)
|
||||
)
|
||||
landmarks, euler, prob = self.onnx_infer(face_input)
|
||||
landmarks = transform_points(landmarks, M_Face, invert=True)
|
||||
|
||||
# Repeat
|
||||
for i in range(iterations - 1):
|
||||
M_Face = get_warp_mat_bbox_by_gt_pts_float(
|
||||
landmarks,
|
||||
np.rad2deg(euler[2]),
|
||||
self.face_image_size,
|
||||
expand_ratio=self.expand_ratio,
|
||||
)
|
||||
face_input = cv2.warpAffine(
|
||||
src_image, M_Face, (self.face_image_size, self.face_image_size)
|
||||
)
|
||||
landmarks, euler, prob = self.onnx_infer(face_input)
|
||||
landmarks = transform_points(landmarks, M_Face, invert=True)
|
||||
|
||||
return_dict = {
|
||||
"pt222": landmarks,
|
||||
"euler_rad": euler,
|
||||
"prob": prob,
|
||||
"M_Face": M_Face,
|
||||
"face_input": face_input,
|
||||
}
|
||||
|
||||
return return_dict
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user