File size: 268,607 Bytes
2ea2835 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 | """distribution matching: match generated videos in frozen encoder feature spaces.
Read the active path in this order:
collect_rollout_features -> hybrid MMD -> prepare_latent_gradients
-> replay_generator_gradients.
The encoders and VAE are frozen, but their input derivatives connect the
feature-space objective to the generator. Modules/attributes used in saved
state dictionaries keep their original names for checkpoint compatibility.
See docs/paper-to-code.md for the paper mapping and estimator conventions.
"""
from __future__ import annotations
import copy
from contextlib import contextmanager, nullcontext
import hashlib
import json
import os
import random
import time
from typing import Mapping, Optional, Tuple
import numpy as np
import torch
import torch.distributed as dist
from losses.multilayer_video_nystrom_mmd import (
MultiLayerVideoNystromMMD,
)
from losses.wan_kv_mmd import EMARBFMMD
from model.generation_base import GeneratorRuntimeBase
from utils.active_mmd_branches import active_mmd_branches
from utils.model_identity import (
canonical_identity_value,
canonical_sha256,
distributed_file_sha256,
distributed_runtime_file_identity,
file_sha256,
runtime_file_identity,
)
from video_fd.encoders.vjepa2_dense_metadata import (
canonical_vjepa2_dense_feature_metadata,
uniform_dense_token_indices,
)
from video_fd.encoders.vjepa2_temporal_sampling import (
stateless_temporal_window_start,
)
from video_fd.replay.replay_video_encoder_vjp import replay_decoder_vjp
def _canonicalize_shared_asset_paths(value):
"""Normalize the local and shared mount names recursively."""
local_root = "/path/to/local-assets"
logical_root = "/path/to/video-generation-assets"
if isinstance(value, str):
if value == local_root or value.startswith(local_root + "/"):
return logical_root + value[len(local_root):]
return value
if isinstance(value, Mapping):
return {
key: _canonicalize_shared_asset_paths(item)
for key, item in value.items()
}
if isinstance(value, tuple):
return tuple(_canonicalize_shared_asset_paths(item) for item in value)
if isinstance(value, list):
return [_canonicalize_shared_asset_paths(item) for item in value]
return value
def _accumulate_fp32_pixel_cotangent(
accumulated: Optional[torch.Tensor],
value: torch.Tensor,
expected_shape: Optional[tuple[int, ...]],
*,
branch_name: str,
) -> tuple[torch.Tensor, tuple[int, ...], torch.Tensor]:
"""Accumulate one branch immediately and retain only its scalar norm."""
if not isinstance(value, torch.Tensor) or not value.is_floating_point():
raise TypeError(f"{branch_name} pixel cotangent must be floating")
detached = value.detach().float()
shape = tuple(detached.shape)
if expected_shape is not None and shape != expected_shape:
raise ValueError(
"triple encoder pixel cotangent shapes differ: "
f"{branch_name}={shape} != {expected_shape}")
if not bool(torch.isfinite(detached).all().item()):
raise FloatingPointError(
f"{branch_name} pixel cotangent is non-finite")
branch_norm = detached.norm().detach()
if accumulated is None:
accumulated = detached
else:
accumulated.add_(detached)
return accumulated, shape, branch_norm
class DistributionMatchingModel(GeneratorRuntimeBase):
"""Match generated and teacher latents in a configured dense feature space.
The generator remains the only trainable model. In ``post_block_latent``
mode ``real_score`` is reused as the frozen Wan encoder so the trainer can
shard it normally with FSDP. In ``vjepa2_dense_latent`` mode ``real_score``
is not constructed; a frozen, replicated FP32 V-JEPA2 prefix is used
instead.
"""
uses_critic = False
uses_vae_for_loss = False
uses_vae_for_visualization = True
requires_distribution_state_on_resume = True
_DENSE_VIDEO_FEATURE_TYPES = frozenset({
"vjepa2_dense_latent",
"dinov3_dense_latent",
"videomae_v2_dense_latent",
"dual_vjepa2_videomae_v2_dense_latent",
"dual_dinov3_vjepa2_dense_latent",
"triple_dinov3_vjepa2_videomae_v2_dense_latent",
})
@staticmethod
def _dense_feature_prefix_for(feature_type: str) -> Optional[str]:
return {
"vjepa2_dense_latent": "vjepa2",
"dinov3_dense_latent": "dinov3",
"videomae_v2_dense_latent": "videomae_v2",
"dual_vjepa2_videomae_v2_dense_latent": "dual",
"dual_dinov3_vjepa2_dense_latent": "dinov3_vjepa2",
"triple_dinov3_vjepa2_videomae_v2_dense_latent": "triple",
}.get(str(feature_type))
def _dense_config_value(self, args, suffix: str, default):
"""Read a backbone-specific public config key.
The established replay implementation keeps its historical internal
``vjepa2_*`` attributes for compatibility. Public VideoMAE-v2 configs,
metadata, logs, and checkpoint keys remain independently namespaced.
"""
prefix = self.dense_feature_prefix
return getattr(args, f"{prefix}_{suffix}", default)
@property
def dense_state_prefix(self) -> str:
"""Public artifact namespace for the active dense-video backbone."""
prefix = getattr(self, "dense_feature_prefix", None)
if prefix is None:
prefix = self._dense_feature_prefix_for(
getattr(self, "feature_type", ""))
return prefix or "vjepa2"
@property
def dense_nystrom_version_key(self) -> str:
return f"{self.dense_state_prefix}_dense_nystrom_mmd_version"
@property
def dense_ema_version_key(self) -> str:
return f"{self.dense_state_prefix}_dense_mmd_version"
@property
def dense_ema_payload_key(self) -> str:
return f"{self.dense_state_prefix}_dense_mmd"
@property
def dense_feature_display_name(self) -> str:
return (
"VideoMAE-v2"
if self.dense_state_prefix == "videomae_v2"
else (
"DINOv3 + V-JEPA2 + VideoMAE-v2"
if self.dense_state_prefix == "triple"
else (
"DINOv3 + V-JEPA2"
if self.dense_state_prefix == "dinov3_vjepa2"
else (
"V-JEPA2 + VideoMAE-v2"
if self.dense_state_prefix == "dual"
else ("DINOv3" if self.dense_state_prefix == "dinov3" else "V-JEPA2")
)
)
)
)
@property
def dense_feature_metric_prefix(self) -> str:
return f"{self.dense_state_prefix}_dense"
@property
def dense_sampled_tokens_per_layer(self) -> int:
return int(self.vjepa2_dense_num_tokens) * int(
getattr(self, "dense_feature_segment_count", 1))
@property
def dense_raw_tokens_total(self) -> int:
return int(self.vjepa2_dense_raw_tokens) * int(
getattr(self, "dense_feature_segment_count", 1))
def _namespace_dense_metrics(self, values: Mapping[str, object]) -> dict:
"""Translate legacy internal metric names at the public boundary."""
if self.dense_state_prefix == "vjepa2":
return dict(values)
if self.dense_state_prefix in {
"dual", "triple", "dinov3", "dinov3_vjepa2"
}:
return dict(values)
return {
(
key.replace("vjepa2_", "videomae_v2_", 1)
if isinstance(key, str) and key.startswith("vjepa2_")
else key
): value
for key, value in values.items()
}
@staticmethod
def _all_ranks_true(local_value: bool, device) -> bool:
flag = torch.tensor(
int(bool(local_value)), device=device, dtype=torch.int32)
if (
dist.is_available()
and dist.is_initialized()
and dist.get_world_size() > 1
):
dist.all_reduce(flag, op=dist.ReduceOp.MIN)
return bool(flag.item())
def _synchronize_dinov3_local_failure(
self,
error: Optional[BaseException],
device,
*,
operation: str,
) -> None:
"""Make a rank-local DINOv3 failure an all-rank branch decision.
DINOv3 startup performs expensive local imports, file inspection and
metadata validation before it hashes shared artifacts. A rank that
raises before a peer enters one of those hash broadcasts would strand
the peer. Every such local-only phase terminates through this helper.
Single-process callers retain the original exception type and message.
"""
if self._all_ranks_true(error is None, device):
return
is_distributed = (
dist.is_available()
and dist.is_initialized()
and dist.get_world_size() > 1
)
if error is not None and not is_distributed:
raise error
detail = (
f": {type(error).__name__}: {error}"
if error is not None
else " on another rank"
)
raise RuntimeError(operation + detail) from error
@staticmethod
def _configured_current_teacher_global_samples(args) -> int:
"""Resolve the exact live-teacher geometry for this process group.
Legacy GradCache updates use every forward sample for the MMD VJP, so
their teacher count remains ``total_batch_size``. Partial replay
explicitly configures a per-rank gradient suffix; only that suffix has
a matched teacher and therefore the exact teacher kernel has
``gradient_local * world_size`` rows.
"""
configured_total = int(getattr(args, "total_batch_size", 0))
gradient_local = getattr(
args, "fresh_video_generator_grad_local_samples", None)
if gradient_local is None:
return configured_total
if type(gradient_local) is not int or gradient_local <= 0:
raise ValueError(
"fresh_video_generator_grad_local_samples must be a "
"positive integer")
forward_local = getattr(args, "fresh_video_local_samples", None)
if type(forward_local) is not int or forward_local <= 0:
raise ValueError(
"fresh_video_local_samples must be a positive integer when "
"partial GradCache replay is configured")
if gradient_local > forward_local:
raise ValueError(
"fresh_video_generator_grad_local_samples must not exceed "
"fresh_video_local_samples")
if dist.is_available() and dist.is_initialized():
world_size = int(dist.get_world_size())
else:
if configured_total <= 0 or configured_total % forward_local != 0:
raise ValueError(
"total_batch_size must be divisible by "
"fresh_video_local_samples before distributed "
"initialization")
world_size = configured_total // forward_local
expected_forward = forward_local * world_size
if configured_total != expected_forward:
raise ValueError(
"total_batch_size does not match the partial GradCache "
"forward geometry: "
f"{configured_total} != {forward_local} * {world_size}")
return gradient_local * world_size
def __init__(self, args, device):
p0_value = os.environ.get("SF_FRESH_VIDEO_P0_REPLAY")
if p0_value is None:
self._fresh_video_p0_requested = True
else:
normalized = p0_value.strip().lower()
if normalized not in {"0", "1", "false", "true", "no", "yes"}:
raise ValueError(
"SF_FRESH_VIDEO_P0_REPLAY must be one of "
"0/1/false/true/no/yes")
self._fresh_video_p0_requested = normalized in {
"1", "true", "yes"}
# Final eligibility is known only after the estimator is initialized.
self.fresh_video_prepared_replay_enabled = False
self.fresh_video_pixel_cache_device = os.environ.get(
"SF_FRESH_VIDEO_PIXEL_CACHE_DEVICE", "cuda"
).strip().lower()
if self.fresh_video_pixel_cache_device not in {"cpu", "cuda"}:
raise ValueError(
"SF_FRESH_VIDEO_PIXEL_CACHE_DEVICE must be cpu or cuda")
requested_feature_type = str(
getattr(args, "wan_feature_type", "post_block_latent"))
supported_feature_types = {
"post_block_latent",
"vjepa2_dense_latent",
"dinov3_dense_latent",
"videomae_v2_dense_latent",
"dual_vjepa2_videomae_v2_dense_latent",
"dual_dinov3_vjepa2_dense_latent",
"triple_dinov3_vjepa2_videomae_v2_dense_latent",
}
if requested_feature_type not in supported_feature_types:
raise ValueError(
"wan_feature_type must be one of "
f"{sorted(supported_feature_types)}, got "
f"{requested_feature_type!r}")
self.dense_feature_prefix = self._dense_feature_prefix_for(
requested_feature_type)
is_dense_video_feature = bool(
requested_feature_type in self._DENSE_VIDEO_FEATURE_TYPES)
self.mmd_estimator = str(
getattr(args, "wan_mmd_estimator", "ema_rff"))
supported_estimators = {"ema_rff", "nystrom_exact_repulsion"}
if self.mmd_estimator not in supported_estimators:
raise ValueError(
"wan_mmd_estimator must be one of "
f"{sorted(supported_estimators)}, got "
f"{self.mmd_estimator!r}")
if (
self.mmd_estimator == "nystrom_exact_repulsion"
and not is_dense_video_feature
):
raise ValueError(
"nystrom_exact_repulsion currently requires "
"a dense video feature backend")
self.is_vjepa2_dense = (
requested_feature_type == "vjepa2_dense_latent")
self.is_dinov3_dense = (
requested_feature_type == "dinov3_dense_latent")
self.is_videomae_v2_dense = (
requested_feature_type == "videomae_v2_dense_latent")
self.is_dinov3_vjepa2_dense = (
requested_feature_type == "dual_dinov3_vjepa2_dense_latent")
self.is_triple_dense = (
requested_feature_type
== "triple_dinov3_vjepa2_videomae_v2_dense_latent")
self.is_dense_video_feature = is_dense_video_feature
if self.is_dinov3_dense and (
self.mmd_estimator != "nystrom_exact_repulsion"
):
raise ValueError(
"wan_feature_type=dinov3_dense_latent currently requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if self.is_dense_video_feature:
# BaseModel otherwise constructs full real/fake Wan score models.
# Neither participates in this generator-only replay objective.
args.uses_score_models = False
args.uses_real_score = False
args.uses_fake_score = False
self.generator_replay_activation_cpu_offload = bool(getattr(
args, "generator_replay_activation_cpu_offload", False))
self.generator_replay_activation_cpu_offload_block_stride = int(
getattr(
args,
"generator_replay_activation_cpu_offload_block_stride",
0,
))
if self.generator_replay_activation_cpu_offload_block_stride < 0:
raise ValueError(
"generator_replay_activation_cpu_offload_block_stride must "
"be non-negative")
if (
self.generator_replay_activation_cpu_offload
and self.generator_replay_activation_cpu_offload_block_stride
):
raise ValueError(
"choose either full generator replay activation CPU "
"offload or a positive block stride, not both")
self.generator_replay_frozen_encoder_cpu_offload = bool(getattr(
args, "generator_replay_frozen_encoder_cpu_offload", False))
self._generator_replay_frozen_encoder_offload_state = None
if (
self.generator_replay_frozen_encoder_cpu_offload
and not self.is_triple_dense
):
raise ValueError(
"generator replay frozen-encoder CPU offload is only "
"implemented for the triple video MMD objective")
super().__init__(args, device)
self.generator.model.gradient_checkpointing_activation_cpu_offload = (
False)
self.generator.model.gradient_checkpointing_activation_cpu_offload_block_stride = (
self.generator_replay_activation_cpu_offload_block_stride)
if self.generator_replay_activation_cpu_offload and (
not dist.is_initialized() or dist.get_rank() == 0):
print("[memory] generator checkpoint activations offload to CPU")
if self.generator_replay_activation_cpu_offload_block_stride and (
not dist.is_initialized() or dist.get_rank() == 0):
print(
"[memory] generator checkpoint activations selectively "
"offload to CPU every "
f"{self.generator_replay_activation_cpu_offload_block_stride} "
"blocks")
self.feature_type = requested_feature_type
self.dense_encoder_name = self.dense_state_prefix
self.dense_log_prefix = f"{self.dense_encoder_name}_dense"
if self.feature_type == "post_block_latent":
self._initialize_wan_features(args)
elif self.is_vjepa2_dense:
self._initialize_vjepa2_features(args, device)
elif self.is_dinov3_dense:
self._initialize_dinov3_features(args, device)
elif self.feature_type == "videomae_v2_dense_latent":
self._initialize_videomae_v2_features(args, device)
elif self.is_dinov3_vjepa2_dense:
self._initialize_dual_dinov3_vjepa2_features(args, device)
else:
self._initialize_multi_encoder_features(args, device)
self.latent_loss_weight = float(
getattr(args, "wan_kv_loss_weight", 1.0))
self.latent_self_normalize = bool(
getattr(args, "wan_kv_self_normalize", True))
self.latent_norm_eps = float(
getattr(args, "wan_kv_norm_eps", 1e-4))
if (
getattr(self, "vjepa2_multilayer_enabled", False)
and self.mmd_estimator != "nystrom_exact_repulsion"
):
raise ValueError(
"multi-layer V-JEPA2 MMD requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if (
getattr(self, "vjepa2_multilayer_enabled", False)
and not self.latent_self_normalize
):
raise ValueError(
"multi-layer V-JEPA2 MMD requires "
"wan_kv_self_normalize=true so layer losses are normalized "
"independently before summation")
if self.is_vjepa2_dense:
self.vjepa2_token_sampling = str(getattr(
args, "vjepa2_token_sampling", "uniform_fixed"))
if self.vjepa2_token_sampling != "uniform_fixed":
raise ValueError(
"this release supports vjepa2_token_sampling="
"uniform_fixed")
else:
self.vjepa2_token_sampling = None
self.uses_fresh_video_gradcache = (
self.mmd_estimator == "nystrom_exact_repulsion")
self.nystrom_attraction_ema_enabled = bool(
self._dense_config_value(
args, "nystrom_attraction_ema_enabled", False))
self.nystrom_attraction_ema_beta = float(
self._dense_config_value(
args, "nystrom_attraction_ema_beta", 0.99))
self.nystrom_attraction_weight = float(
self._dense_config_value(
args, "nystrom_attraction_weight", 1.0))
self.current_teacher_attraction_enabled = bool(
self._dense_config_value(
args, "nystrom_current_teacher_attraction_enabled", False))
self.current_teacher_attraction_weight = float(
self._dense_config_value(
args, "nystrom_current_teacher_attraction_weight", 1.0))
self.expected_current_teacher_samples = int(getattr(
args, "expected_current_teacher_samples", 0))
self.current_teacher_source = str(getattr(
args, "current_teacher_source", "auto"))
if self.current_teacher_source not in {
"auto", "none", "lmdb_latent", "openvid_video",
"matched_manifest_video", "matched_dual_feature_bank",
"matched_triple_feature_bank",
"matched_dinov3_vjepa2_feature_bank",
}:
raise ValueError(
"unsupported current_teacher_source: "
f"{self.current_teacher_source!r}")
self.nystrom_repulsion_fifo_size = int(
self._dense_config_value(
args, "nystrom_repulsion_fifo_size", 0))
if (
not np.isfinite(self.nystrom_attraction_weight)
or self.nystrom_attraction_weight < 0.0
):
raise ValueError(
f"{self.dense_state_prefix}_nystrom_attraction_weight must "
"be finite and non-negative")
if (
not np.isfinite(self.current_teacher_attraction_weight)
or self.current_teacher_attraction_weight < 0.0
):
raise ValueError(
f"{self.dense_state_prefix}_nystrom_current_teacher_"
"attraction_weight must be finite and non-negative")
if (
self.current_teacher_attraction_enabled
and self.nystrom_attraction_weight
+ self.current_teacher_attraction_weight <= 0.0
):
raise ValueError(
"fixed/current teacher attraction weights must have a "
"positive sum")
if self.nystrom_repulsion_fifo_size < 0:
raise ValueError(
"dense Nyström repulsion FIFO size must be non-negative")
self.nystrom_repulsion_fifo_enabled = bool(
self.nystrom_repulsion_fifo_size > 0)
if (
not np.isfinite(self.nystrom_attraction_ema_beta)
or not 0.0 <= self.nystrom_attraction_ema_beta < 1.0
):
raise ValueError(
"dense Nyström attraction EMA beta must be in [0, 1)")
if (
self.nystrom_attraction_ema_enabled
and not self.uses_fresh_video_gradcache
):
raise ValueError(
"vjepa2_nystrom_attraction_ema_enabled requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if (
self.current_teacher_attraction_enabled
and not self.uses_fresh_video_gradcache
):
raise ValueError(
"current teacher attraction requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if (
self.current_teacher_attraction_enabled
and getattr(self, "vjepa2_multilayer_enabled", False)
):
raise ValueError(
"current teacher attraction currently supports one dense "
"feature layer")
if self.current_teacher_attraction_enabled:
configured_teacher_total = (
self._configured_current_teacher_global_samples(args)
)
if self.expected_current_teacher_samples <= 0:
raise ValueError(
"expected_current_teacher_samples must be explicitly "
"positive when current teacher attraction is enabled")
if configured_teacher_total != self.expected_current_teacher_samples:
raise ValueError(
"the configured GradCache gradient geometry must match "
"expected_current_teacher_samples for exact current "
"teacher MMD: "
f"{configured_teacher_total} != "
f"{self.expected_current_teacher_samples}")
if (
self.nystrom_repulsion_fifo_enabled
and not self.uses_fresh_video_gradcache
):
raise ValueError(
"vjepa2_nystrom_repulsion_fifo_size requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if (
self.nystrom_repulsion_fifo_enabled
and getattr(self, "vjepa2_multilayer_enabled", False)
):
raise ValueError(
"repulsion FIFO currently supports one fixed V-JEPA2 layer")
if (
self.nystrom_repulsion_fifo_enabled
and self.nystrom_attraction_ema_enabled
):
raise ValueError(
"repulsion FIFO training requires attraction EMA to be disabled")
self.fresh_video_prepared_replay_enabled = bool(
self._fresh_video_p0_requested
and self.uses_fresh_video_gradcache
)
if self.uses_fresh_video_gradcache:
if not self.causal_generator:
raise NotImplementedError(
"nystrom_exact_repulsion currently requires the causal "
"generator so every stochastic rollout input can be "
"captured explicitly")
from losses.video_nystrom_mmd import (
VideoNystromMMD,
load_reference_pack,
)
kernel_chunk_size = int(
getattr(
args,
"dinov3_nystrom_kernel_chunk_size",
32,
)
if self.is_dinov3_dense
else self._dense_config_value(
args, "nystrom_kernel_chunk_size", 32)
)
if self.is_dinov3_dense:
reference_load_error = None
reference_path = None
reference_pack = None
try:
configured_reference = str(getattr(
args,
"dinov3_nystrom_reference_path",
"",
)).strip()
reference_path = (
os.path.realpath(os.path.expanduser(
configured_reference))
if configured_reference else ""
)
if (
not reference_path
or not os.path.isfile(reference_path)
):
raise FileNotFoundError(
"DINOv3 dense Nyström requires a precomputed fixed "
"reference pack under "
"dinov3_nystrom_reference_path; "
f"got {reference_path!r}")
reference_pack = load_reference_pack(
reference_path, map_location="cpu")
except BaseException as exc:
reference_load_error = exc
self._synchronize_dinov3_local_failure(
reference_load_error,
device,
operation="DINOv3 reference-pack loading failed",
)
self._validate_dinov3_reference_runtime_identity(
args, reference_pack["metadata"])
objective_error = None
try:
reference_section = reference_pack["metadata"].get(
"reference", {})
reference_source = (
reference_section.get("source", {})
if isinstance(reference_section, dict)
else {}
)
feature_bank_hash = reference_source.get(
"feature_bank_fp16_sha256")
if (
not isinstance(feature_bank_hash, str)
or len(feature_bank_hash) != 64
or any(
character not in "0123456789abcdef"
for character in feature_bank_hash
)
):
raise ValueError(
"DINOv3 Nyström reference is missing a valid "
"frozen teacher feature_bank_fp16_sha256")
objective = VideoNystromMMD(
reference_pack,
expected_metadata={
"feature": self._dinov3_feature_metadata(),
"nystrom": {
"num_landmarks": int(getattr(
args, "dinov3_nystrom_landmarks", 256)),
"seed": int(getattr(
args, "dinov3_nystrom_seed", 0)),
},
},
kernel_chunk_size=kernel_chunk_size,
attraction_ema_enabled=False,
repulsion_fifo_size=0,
)
reference_count = int(
objective.reference_metadata[
"nystrom"]["reference_count"])
if int(reference_source.get(
"selected_samples", -1
)) != reference_count:
raise ValueError(
"DINOv3 Nyström reference source count does not "
"match the frozen kernel reference count")
self.dinov3_nystrom_reference_path = reference_path
self.dinov3_nystrom_reference_hash = str(
objective.reference_hash)
self.dinov3_teacher_feature_bank_hash = feature_bank_hash
self.dinov3_nystrom_reference_count = reference_count
self.latent_mmd = objective.to(device=device)
except BaseException as exc:
objective_error = exc
self._synchronize_dinov3_local_failure(
objective_error,
device,
operation="DINOv3 reference objective setup failed",
)
else:
def load_fixed_reference(layer_index, configured_path):
reference_path = (
os.path.realpath(os.path.expanduser(
str(configured_path).strip()))
if str(configured_path).strip() else ""
)
if (
not reference_path
or not os.path.isfile(reference_path)
):
raise FileNotFoundError(
"nystrom_exact_repulsion requires a precomputed "
"reference pack; got "
f"{reference_path!r} for layer {layer_index}")
reference_pack = load_reference_pack(
reference_path, map_location="cpu")
reference_section = reference_pack["metadata"].get(
"reference", {})
reference_source = (
reference_section.get("source", {})
if isinstance(reference_section, dict)
else {}
)
feature_bank_hash = reference_source.get(
"feature_bank_fp16_sha256")
if (
not isinstance(feature_bank_hash, str)
or len(feature_bank_hash) != 64
or any(
character not in "0123456789abcdef"
for character in feature_bank_hash
)
):
raise ValueError(
"Nyström reference is missing a valid frozen "
"teacher feature_bank_fp16_sha256 for layer "
f"{layer_index}")
objective = VideoNystromMMD(
reference_pack,
expected_metadata={
"feature": self._vjepa2_feature_metadata(
layer_index=layer_index),
"nystrom": {
"num_landmarks": int(
self._dense_config_value(
args, "nystrom_landmarks", 256)),
"seed": int(
self._dense_config_value(
args, "nystrom_seed", 0)),
},
},
kernel_chunk_size=kernel_chunk_size,
attraction_ema_enabled=(
self.nystrom_attraction_ema_enabled),
attraction_ema_beta=(
self.nystrom_attraction_ema_beta),
attraction_weight=(
self.nystrom_attraction_weight),
current_teacher_attraction_enabled=(
self.current_teacher_attraction_enabled),
current_teacher_attraction_weight=(
self.current_teacher_attraction_weight),
repulsion_fifo_size=(
self.nystrom_repulsion_fifo_size),
)
reference_count = int(
objective.reference_metadata[
"nystrom"]["reference_count"])
if int(reference_source.get(
"selected_samples", -1
)) != reference_count:
raise ValueError(
"Nyström reference source count does not match "
"the frozen kernel reference count for layer "
f"{layer_index}")
source_identity = {
key: value
for key, value in reference_source.items()
if key != "feature_bank_fp16_sha256"
}
return (
reference_path,
objective,
feature_bank_hash,
reference_count,
source_identity,
)
if getattr(self, "vjepa2_multilayer_enabled", False):
configured_paths = getattr(
args, "vjepa2_nystrom_reference_paths", None)
if (
configured_paths is None
or isinstance(configured_paths, (str, bytes))
):
raise ValueError(
"multi-layer V-JEPA2 MMD requires "
"vjepa2_nystrom_reference_paths in layer order")
configured_paths = tuple(configured_paths)
if len(configured_paths) != len(
self.vjepa2_dense_layers
):
raise ValueError(
"vjepa2_nystrom_reference_paths must match "
"vjepa2_dense_layers one-for-one")
loaded = [
load_fixed_reference(layer, path)
for layer, path in zip(
self.vjepa2_dense_layers,
configured_paths,
)
]
objectives = {
layer: item[1]
for layer, item in zip(
self.vjepa2_dense_layers, loaded)
}
self.latent_mmd = MultiLayerVideoNystromMMD(
objectives,
self_normalize=self.latent_self_normalize,
norm_eps=self.latent_norm_eps,
).to(device=device)
self.vjepa2_nystrom_reference_paths = tuple(
item[0] for item in loaded)
self.vjepa2_nystrom_reference_hashes = tuple(
objective.reference_hash
for objective in objectives.values())
self.vjepa2_teacher_feature_bank_hashes = tuple(
item[2] for item in loaded)
reference_counts = tuple(
item[3] for item in loaded)
if len(set(reference_counts)) != 1:
raise ValueError(
"multi-layer Nyström references must contain "
"the same teacher sample count")
source_identities = tuple(
item[4] for item in loaded)
if any(
identity != source_identities[0]
for identity in source_identities[1:]
):
raise ValueError(
"multi-layer Nyström references must use the "
"same teacher LMDB rows and prompt index")
self.vjepa2_nystrom_reference_count = (
reference_counts[0])
# Singular aliases keep generic diagnostics compatible;
# checkpoint identity uses the complete tuples below.
self.vjepa2_nystrom_reference_path = (
self.vjepa2_nystrom_reference_paths[-1])
self.vjepa2_nystrom_reference_hash = (
self.vjepa2_nystrom_reference_hashes[-1])
self.vjepa2_teacher_feature_bank_hash = (
self.vjepa2_teacher_feature_bank_hashes[-1])
else:
configured_reference_path = self._dense_config_value(
args, "nystrom_reference_path", "")
(
reference_path,
objective,
feature_bank_hash,
reference_count,
_,
) = load_fixed_reference(
self.vjepa2_dense_layer,
configured_reference_path,
)
self.vjepa2_nystrom_reference_path = reference_path
self.latent_mmd = objective.to(device=device)
self.vjepa2_teacher_feature_bank_hash = (
feature_bank_hash)
self.vjepa2_nystrom_reference_hash = str(
objective.reference_hash)
self.vjepa2_nystrom_reference_count = reference_count
if self.is_dinov3_dense and (
not dist.is_available()
or not dist.is_initialized()
or dist.get_rank() == 0
):
print(
"[dinov3-nystrom] loaded frozen reference "
f"n={self.dinov3_nystrom_reference_count}, "
f"m={self.latent_mmd.landmarks.shape[0]}, "
f"sigma={float(self.latent_mmd.sigma):.6g}, "
f"hash={self.dinov3_nystrom_reference_hash}, "
"teacher_features="
f"{self.dinov3_teacher_feature_bank_hash}",
flush=True,
)
elif (
not dist.is_available()
or not dist.is_initialized()
or dist.get_rank() == 0
):
if getattr(self, "vjepa2_multilayer_enabled", False):
reference_summary = ", ".join(
(
f"layer={layer}:"
f"sigma={float(objective.sigma):.6g}:"
f"hash={objective.reference_hash}"
)
for layer, objective in zip(
self.vjepa2_dense_layers,
self.latent_mmd.objectives.values(),
)
)
print(
"[vjepa2-nystrom] loaded frozen multi-layer "
f"references n={self.vjepa2_nystrom_reference_count}, "
f"m={self.latent_mmd.landmarks.shape[0]}, "
f"normalized={self.latent_self_normalize}, "
"attraction_ema="
f"{self.nystrom_attraction_ema_enabled}, "
"attraction_weight="
f"{self.nystrom_attraction_weight:g}, "
"repulsion_fifo="
f"{self.nystrom_repulsion_fifo_size}, "
f"{reference_summary}",
flush=True,
)
else:
print(
f"[{self.dense_encoder_name}-nystrom] loaded frozen reference "
f"n={self.vjepa2_nystrom_reference_count}, "
f"m={self.latent_mmd.landmarks.shape[0]}, "
f"sigma={float(self.latent_mmd.sigma):.6g}, "
f"hash={self.vjepa2_nystrom_reference_hash}, "
"attraction_ema="
f"{self.nystrom_attraction_ema_enabled}, "
"repulsion_fifo="
f"{self.nystrom_repulsion_fifo_size}, "
"teacher_features="
f"{self.vjepa2_teacher_feature_bank_hash}",
flush=True,
)
else:
self.latent_mmd = EMARBFMMD(
beta=float(getattr(args, "wan_kv_ema_beta", 0.99)),
num_rff_features=int(
getattr(args, "wan_kv_rff_features", 256)),
bandwidth=getattr(args, "wan_kv_rbf_bandwidth", None),
bandwidth_multipliers=getattr(
args, "wan_kv_rbf_multipliers", [0.5, 1.0, 2.0]),
seed=int(getattr(args, "wan_kv_rff_seed", 0)),
row_normalize=bool(
getattr(args, "wan_kv_row_normalize", False)),
sample_mode=(
"video_matrix"
if self.is_dense_video_feature
else "rows"
),
).to(device)
if self.feature_type == "triple_dinov3_vjepa2_videomae_v2_dense_latent":
self._build_multi_encoder_objective(args, device)
elif self.is_dinov3_vjepa2_dense:
self._replace_with_dual_dinov3_vjepa2_nystrom_objective(
args, device)
# Dense video backends always decode videos. The Wan path only needs VAE
# loss decoding for longer causal rollouts.
self.uses_vae_for_loss = (
self.is_dense_video_feature
or bool(self.causal_generator and self.num_training_frames > 21)
)
def offload_frozen_modules_for_generator_replay(self) -> int:
"""Offload frozen representation modules after their exact VJPs.
This mirrors the proven VACE replay schedule: the complete-batch MMD
is evaluated first, selected samples replay the frozen encoders and
VAE to obtain detached latent cotangents, and only then are those
frozen modules moved to CPU for the generator-only replay.
"""
if not self.generator_replay_frozen_encoder_cpu_offload:
return 0
if self._generator_replay_frozen_encoder_offload_state is not None:
raise RuntimeError("frozen replay modules are already offloaded")
registry = getattr(self, "dual_branch_registry", None)
if not isinstance(registry, Mapping) or not registry:
raise RuntimeError("frozen replay requires an active encoder registry")
module_names = ("vae",) + tuple(
branch["encoder_attribute"] for branch in registry.values())
if len(set(module_names)) != len(module_names):
raise RuntimeError("frozen replay registry contains duplicate modules")
original_device = torch.device(self.device)
moved = []
tensor_bytes = 0
try:
torch.cuda.synchronize(original_device)
for module_name in module_names:
module = getattr(self, module_name, None)
if not isinstance(module, torch.nn.Module):
raise RuntimeError(
f"frozen replay module {module_name} is unavailable")
if module.training or any(
parameter.requires_grad for parameter in module.parameters()
):
raise RuntimeError(
f"refusing to offload non-frozen module {module_name}")
tensors = tuple(module.parameters()) + tuple(module.buffers())
if not tensors:
raise RuntimeError(
f"frozen replay module {module_name} is not fully CUDA-resident")
tensor_bytes += sum(
tensor.numel() * tensor.element_size() for tensor in tensors
)
module.to(device="cpu")
moved.append(module_name)
torch.cuda.synchronize(original_device)
torch.cuda.empty_cache()
except BaseException:
for module_name in moved:
getattr(self, module_name).to(device=original_device)
torch.cuda.synchronize(original_device)
raise
self._generator_replay_frozen_encoder_offload_state = {
"module_names": module_names,
"original_device": str(original_device),
"tensor_bytes": int(tensor_bytes),
}
if not dist.is_initialized() or dist.get_rank() == 0:
print(
f"[memory] replay offloaded frozen modules={module_names} "
f"({tensor_bytes / (1024 ** 3):.2f} GiB tensors)",
flush=True,
)
return int(tensor_bytes)
def restore_frozen_modules_before_feature_replay(self) -> int:
"""Restore frozen modules before the next complete-batch feature pass."""
state = self._generator_replay_frozen_encoder_offload_state
if state is None:
return 0
original_device = torch.device(state["original_device"])
for module_name in state["module_names"]:
module = getattr(self, module_name, None)
if not isinstance(module, torch.nn.Module):
raise RuntimeError(
f"offloaded replay module {module_name} disappeared")
tensors = tuple(module.parameters()) + tuple(module.buffers())
if not tensors or any(
tensor.device.type != "cpu" for tensor in tensors
):
raise RuntimeError(
f"offloaded replay module {module_name} is not fully on CPU")
module.to(device=original_device)
module.eval().requires_grad_(False)
torch.cuda.synchronize(original_device)
tensor_bytes = int(state["tensor_bytes"])
self._generator_replay_frozen_encoder_offload_state = None
if not dist.is_initialized() or dist.get_rank() == 0:
print(
f"[memory] restored frozen modules={state['module_names']} "
"for the next MMD feature/replay pass",
flush=True,
)
return tensor_bytes
_canonical_sha256 = staticmethod(canonical_sha256)
_canonical_identity_value = staticmethod(canonical_identity_value)
_file_sha256 = staticmethod(file_sha256)
_distributed_file_sha256 = staticmethod(distributed_file_sha256)
_runtime_file_identity = staticmethod(runtime_file_identity)
_distributed_runtime_file_identity = staticmethod(
distributed_runtime_file_identity)
def _validate_dinov3_reference_runtime_identity(
self,
args,
reference_metadata: Mapping,
*,
inspect_lmdb=None,
model_path_resolver=None,
wrapper_source_path=None,
file_hasher=None,
) -> dict:
"""Bind a DINOv3 reference to the active CausVid LMDB and Wan VAE.
All fallible rank-local inspection completes and reaches consensus
before any rank enters a shared-file hash broadcast. The large VAE
files are then identified entirely on rank zero. Injection seams keep
the artifact checks unit-testable without loading a real LMDB or VAE.
"""
from pathlib import Path
collective_device = getattr(self, "device", None)
if collective_device is None:
collective_device = torch.device("cpu")
preflight = None
preflight_error = None
try:
if not isinstance(reference_metadata, Mapping):
raise TypeError("DINOv3 reference metadata must be a mapping")
reference = reference_metadata.get("reference")
if not isinstance(reference, Mapping):
raise ValueError(
"DINOv3 reference metadata is missing reference identity")
source = reference.get("source")
saved_vae = reference.get("vae")
if not isinstance(source, Mapping) or not isinstance(
saved_vae, Mapping
):
raise ValueError(
"DINOv3 reference must contain source and VAE identities")
source = dict(source)
saved_vae = dict(saved_vae)
teacher_path = os.path.realpath(os.path.expanduser(str(getattr(
args, "teacher_latent_data_path", ""))))
if not teacher_path or not os.path.isdir(teacher_path):
raise FileNotFoundError(
"DINOv3 reference validation requires the configured "
f"teacher LMDB directory; got {teacher_path!r}")
active_inspector = inspect_lmdb
if active_inspector is None:
from tools.precompute_dinov3_dense_nystrom_reference import (
_inspect_lmdb,
)
active_inspector = _inspect_lmdb
live_lmdb = dict(active_inspector(Path(teacher_path)))
live_lmdb_path = os.path.realpath(str(
live_lmdb.get("path", "")))
live_latents_shape = [
int(value)
for value in live_lmdb.get("latents_shape", ())
]
live_prompts_shape = [
int(value)
for value in live_lmdb.get("prompts_shape", ())
]
if (
live_lmdb_path != teacher_path
or len(live_latents_shape) != 6
or live_prompts_shape != [live_latents_shape[0]]
):
raise ValueError(
"active teacher LMDB has an invalid CausVid array identity")
teacher_count = int(getattr(
args, "teacher_latent_count", live_latents_shape[0]))
data_mdb_path = os.path.join(teacher_path, "data.mdb")
if not os.path.isfile(data_mdb_path):
raise FileNotFoundError(
f"teacher LMDB data file is missing: {data_mdb_path}")
data_stat = os.stat(data_mdb_path)
expected_source_keys = {
"kind",
"lmdb_path",
"latents_shape",
"prompts_shape",
"selected_samples",
"selected_index_start",
"selected_index_stop_exclusive",
"trajectory_index",
"lmdb_storage_dtype",
"data_mdb_size_bytes",
"data_mdb_mtime_ns",
"prompt_index_sha256",
"feature_bank_fp16_sha256",
"identity_sha256",
}
source_without_hash = dict(source)
saved_source_hash = source_without_hash.pop(
"identity_sha256", None)
source_hash_valid = (
isinstance(saved_source_hash, str)
and saved_source_hash
== self._canonical_sha256(source_without_hash)
)
source_sha_fields_valid = all(
isinstance(source.get(key), str)
and len(source[key]) == 64
and all(
character in "0123456789abcdef"
for character in source[key]
)
for key in (
"prompt_index_sha256",
"feature_bank_fp16_sha256",
)
)
if (
set(source) != expected_source_keys
or source.get("kind")
!= "causvid_ode_teacher_lmdb_final_latent"
or os.path.realpath(str(source.get("lmdb_path", "")))
!= teacher_path
or source.get("latents_shape") != live_latents_shape
or source.get("prompts_shape") != live_prompts_shape
or int(source.get("selected_samples", -1))
!= live_latents_shape[0]
or live_latents_shape[0] != 1537
or teacher_count != live_latents_shape[0]
or int(source.get("selected_index_start", -1)) != 0
or int(source.get("selected_index_stop_exclusive", -1))
!= live_latents_shape[0]
or int(source.get("trajectory_index", -2)) != -1
or source.get("lmdb_storage_dtype") != "float16"
or int(source.get("data_mdb_size_bytes", -1))
!= int(data_stat.st_size)
or int(source.get("data_mdb_mtime_ns", -1))
!= int(data_stat.st_mtime_ns)
or int(live_lmdb.get("data_mdb_size_bytes", -1))
!= int(data_stat.st_size)
or int(live_lmdb.get("data_mdb_mtime_ns", -1))
!= int(data_stat.st_mtime_ns)
or not source_sha_fields_valid
or not source_hash_valid
):
raise ValueError(
"DINOv3 reference teacher LMDB identity does not match "
"the active CausVid dataset")
active_model_path_resolver = model_path_resolver
if active_model_path_resolver is None:
from utils.paths import model_path
active_model_path_resolver = model_path
vae_model_name = "Wan2.1-T2V-1.3B"
weights_path = (
Path(active_model_path_resolver(vae_model_name))
/ "Wan2.1_VAE.pth"
)
active_wrapper_source_path = wrapper_source_path
if active_wrapper_source_path is None:
active_wrapper_source_path = (
Path(__file__).resolve().parents[1]
/ "utils" / "wan_wrapper.py"
)
# Prove every rank can resolve/stat both identities before rank zero
# enters either hash transaction.
for identity_path in (weights_path, active_wrapper_source_path):
resolved = os.path.realpath(os.path.expanduser(
os.fspath(identity_path)))
if not os.path.isfile(resolved):
raise FileNotFoundError(
f"runtime identity target is not a file: {resolved}")
os.stat(resolved)
vae_mean = getattr(self.vae, "mean", None)
vae_std = getattr(self.vae, "std", None)
if not isinstance(vae_mean, torch.Tensor) or not isinstance(
vae_std, torch.Tensor
):
raise TypeError(
"active Wan VAE wrapper is missing tensor mean/std "
"constants")
runtime_vae_base = {
"wrapper": (
f"{type(self.vae).__module__}."
f"{type(self.vae).__qualname__}"),
"model_name": vae_model_name,
"latent_channels": int(vae_mean.numel()),
"latent_mean": [
round(float(value), 4) for value in
vae_mean.detach().float().cpu().reshape(-1).tolist()
],
"latent_std": [
round(float(value), 4) for value in
vae_std.detach().float().cpu().reshape(-1).tolist()
],
"mean_std_contract": "WanVAEWrapper.inline_constants.v1",
"compute_dtype": str(self.dtype).replace("torch.", ""),
"decode_use_cache": False,
"decode_output_range": "[-1,1]",
}
preflight = {
"saved_source_hash": saved_source_hash,
"saved_vae": saved_vae,
"weights_path": weights_path,
"wrapper_source_path": active_wrapper_source_path,
"runtime_vae_base": runtime_vae_base,
}
except BaseException as exc:
preflight_error = exc
self._synchronize_dinov3_local_failure(
preflight_error,
collective_device,
operation="DINOv3 runtime identity preflight failed",
)
identity_error = None
weights_identity = None
wrapper_identity = None
try:
if file_hasher is None:
weights_identity = self._distributed_runtime_file_identity(
preflight["weights_path"])
wrapper_identity = self._distributed_runtime_file_identity(
preflight["wrapper_source_path"])
else:
weights_identity = self._runtime_file_identity(
preflight["weights_path"], file_hasher=file_hasher)
wrapper_identity = self._runtime_file_identity(
preflight["wrapper_source_path"],
file_hasher=file_hasher,
)
except BaseException as exc:
identity_error = exc
self._synchronize_dinov3_local_failure(
identity_error,
collective_device,
operation="DINOv3 shared-file identity failed",
)
receipt = None
comparison_error = None
try:
runtime_vae = dict(preflight["runtime_vae_base"])
runtime_vae["wrapper_source"] = wrapper_identity
runtime_vae["weights"] = weights_identity
runtime_vae["identity_sha256"] = self._canonical_sha256(
runtime_vae)
if preflight["saved_vae"] != runtime_vae:
raise ValueError(
"DINOv3 reference Wan VAE identity does not match the "
"active decoder")
receipt = {
"source_identity_sha256": preflight["saved_source_hash"],
"vae_identity_sha256": runtime_vae["identity_sha256"],
}
except BaseException as exc:
comparison_error = exc
self._synchronize_dinov3_local_failure(
comparison_error,
collective_device,
operation="DINOv3 runtime identity comparison failed",
)
return receipt
@classmethod
def _resolve_vjepa2_model_configuration(
cls,
args,
) -> Tuple[str, str, str]:
"""Resolve the load source independently from reference metadata.
vjepa2_model_id identifies the model that transformers actually opens.
vjepa2_reference_model_id is the canonical identity stored in an
already-created feature/reference pack; it can legitimately be a path
from the machine that produced that pack. Keeping the two separate
lets a byte-identical local mirror satisfy strict reference metadata
without asking transformers to open the producer's path.
When configured, vjepa2_model_sha256 authenticates the local
model.safetensors before the adapter is constructed.
"""
configured_load_id = str(getattr(
args,
"vjepa2_model_id",
"assets/models/vjepa2-vitl-fpc64-256",
)).strip()
if not configured_load_id:
raise ValueError("vjepa2_model_id must be a non-empty string")
expanded_load_id = os.path.expanduser(configured_load_id)
model_load_path = (
os.path.realpath(expanded_load_id)
if os.path.exists(expanded_load_id)
else configured_load_id
)
configured_reference_id = getattr(
args, "vjepa2_reference_model_id", None)
reference_model_id = (
"" if configured_reference_id is None
else str(configured_reference_id).strip()
)
if not reference_model_id:
# Backward compatibility: old configs used one field for both
# loading and canonical reference metadata.
reference_model_id = model_load_path
expected_sha256 = str(getattr(
args, "vjepa2_model_sha256", "")).strip().lower()
if expected_sha256:
if (
len(expected_sha256) != 64
or any(
character not in "0123456789abcdef"
for character in expected_sha256
)
):
raise ValueError(
"vjepa2_model_sha256 must be a 64-character SHA-256")
if not os.path.isdir(model_load_path):
raise ValueError(
"vjepa2_model_sha256 requires vjepa2_model_id to be a "
"local model directory")
weight_path = os.path.join(
model_load_path, "model.safetensors")
if not os.path.isfile(weight_path):
raise FileNotFoundError(
"vjepa2_model_sha256 requires the local weight file "
f"{weight_path}")
actual_sha256 = cls._distributed_file_sha256(weight_path)
if actual_sha256 != expected_sha256:
raise RuntimeError(
"V-JEPA2 model.safetensors SHA-256 mismatch: "
f"expected {expected_sha256}, got {actual_sha256}")
return model_load_path, reference_model_id, expected_sha256
@staticmethod
@staticmethod
def _config_list(value) -> list:
if isinstance(value, str):
return [value]
return list(value)
def _dense_config(self, args, suffix: str, default):
"""Read an encoder-scoped dense option without changing old YAMLs."""
return getattr(
args, f"{self._dense_encoder_kind()}_{suffix}", default)
def _dense_key(self, suffix: str) -> str:
prefix = getattr(
self,
"dense_log_prefix",
f"{self._dense_encoder_kind()}_dense",
)
return f"{prefix}_{suffix}"
def _dense_encoder_kind(self) -> str:
return getattr(
self,
"dense_encoder_name",
(
"motionformer"
if getattr(self, "feature_type", None)
== "motionformer_dense_latent"
else "vjepa2"
),
)
def _dense_encoder_display_name(self) -> str:
return (
"MotionFormer"
if self._dense_encoder_kind() == "motionformer"
else "V-JEPA2"
)
def _dense_attr(self, suffix: str):
generic_name = f"dense_{suffix}"
if hasattr(self, generic_name):
return getattr(self, generic_name)
return getattr(self, f"vjepa2_dense_{suffix}")
def _dense_ema_version_key(self) -> str:
return self._dense_key("mmd_version")
def _dense_ema_state_key(self) -> str:
return self._dense_key("mmd")
def _dense_nystrom_version_key(self) -> str:
return self._dense_key("nystrom_mmd_version")
def _initialize_wan_features(self, args) -> None:
if self.real_score is None:
raise ValueError(
"post_block_latent requires uses_real_score: true")
self.latent_layer = int(getattr(args, "wan_latent_layer", 15))
num_encoder_blocks = len(self.real_score.model.blocks)
if self.latent_layer < 0 or self.latent_layer >= num_encoder_blocks:
raise ValueError(
f"wan_latent_layer={self.latent_layer} outside frozen Wan's "
f"0..{num_encoder_blocks - 1} range")
if bool(getattr(args, "wan_latent_prune_unused_blocks", True)):
# The feature path returns after the requested block, so later
# frozen blocks can never be used. Removing them before FSDP avoids
# sharding/loading another ~650M parameters for layers 16..29.
keep = self.latent_layer + 1
self.real_score.model.blocks = self.real_score.model.blocks[:keep]
self.latent_num_tokens = int(
getattr(args, "wan_latent_num_tokens", 128))
if self.latent_num_tokens <= 1:
raise ValueError("wan_latent_num_tokens must be > 1")
self.latent_timestep = float(
getattr(args, "wan_latent_timestep", 0.0))
self.latent_patch_size = tuple(
int(v) for v in self.real_score.model.patch_size)
self.latent_feature_dim = int(self.real_score.model.dim)
# We need input gradients through the frozen encoder, and checkpointing is
# the main activation-memory control for deeper prefixes.
if bool(getattr(args, "wan_latent_gradient_checkpointing", True)):
self.real_score.enable_gradient_checkpointing()
def _initialize_vjepa2_features(self, args, device) -> None:
# Lazy import keeps the transformers/V-JEPA2 dependency completely out
# of the unchanged Wan feature path.
from video_fd.encoders.vjepa2_adapter import VJEPA2Adapter
(
self.vjepa2_model_load_path,
self.vjepa2_reference_model_id,
self.vjepa2_model_sha256,
) = self._resolve_vjepa2_model_configuration(args)
# Retain the historical runtime attribute for reference-bank identity
# checks and downstream code that expects the actual load source.
self.vjepa2_model_id = self.vjepa2_model_load_path
self.vjepa2_reference_token_contract = str(getattr(
args,
"vjepa2_reference_token_contract",
"explicit_uniform_v2",
)).strip()
if self.vjepa2_reference_token_contract not in {
"explicit_uniform_v2",
"legacy_uniform_implicit_v1",
}:
raise ValueError(
"vjepa2_reference_token_contract must be "
"explicit_uniform_v2 or legacy_uniform_implicit_v1")
configured_dense_layers = getattr(
args, "vjepa2_dense_layers", None)
if configured_dense_layers is None:
dense_layers = (
int(getattr(args, "vjepa2_dense_layer", 15)),
)
else:
if isinstance(configured_dense_layers, (str, bytes)):
raise TypeError(
"vjepa2_dense_layers must be a sequence of integers")
dense_layers = tuple(
int(layer) for layer in configured_dense_layers)
if not dense_layers:
raise ValueError(
"vjepa2_dense_layers must not be empty")
if len(set(dense_layers)) != len(dense_layers):
raise ValueError(
"vjepa2_dense_layers must contain unique indices")
if tuple(sorted(dense_layers)) != dense_layers:
raise ValueError(
"vjepa2_dense_layers must be sorted")
self.vjepa2_dense_layers = dense_layers
self.vjepa2_multilayer_enabled = len(dense_layers) > 1
# The maximum layer controls prefix pruning. Single-layer callers keep
# the historical scalar attribute unchanged.
self.vjepa2_dense_layer = dense_layers[-1]
self.vjepa2_dense_num_frames = int(
getattr(args, "vjepa2_dense_num_frames", 64))
self.vjepa2_dense_frame_sampling = str(getattr(
args, "vjepa2_dense_frame_sampling", "center_contiguous"))
# Keep the immutable reference contract separate from the student
# temporal window. The historical ``last_contiguous`` alias denotes
# matched5k references that were actually extracted from frames 17..80;
# explicit ``center_contiguous`` + student ``last_contiguous`` is the
# legacy OpenVid-77,615 center64-reference protocol.
self.vjepa2_reference_frame_sampling = (
self.vjepa2_dense_frame_sampling)
self.vjepa2_dense_source_num_frames = int(getattr(
args,
"vjepa2_dense_source_num_frames",
self.vjepa2_dense_num_frames,
))
configured_student_frame_sampling = getattr(
args, "vjepa2_student_frame_sampling", None)
if self.vjepa2_dense_frame_sampling == "last_contiguous":
if (
configured_student_frame_sampling is not None
and str(configured_student_frame_sampling) != "last_contiguous"
):
raise ValueError(
"vjepa2_dense_frame_sampling=last_contiguous conflicts "
"with vjepa2_student_frame_sampling")
# The dense contract identifies the frozen center64 reference.
# Treat this alias as a student-only last64 request.
self.vjepa2_dense_frame_sampling = "center_contiguous"
self.vjepa2_student_frame_sampling = "last_contiguous"
else:
self.vjepa2_student_frame_sampling = str(
configured_student_frame_sampling
if configured_student_frame_sampling is not None
else self.vjepa2_dense_frame_sampling
)
default_student_source_frames = (
81
if self.vjepa2_student_frame_sampling == "last_contiguous"
else self.vjepa2_dense_source_num_frames
)
self.vjepa2_student_source_num_frames = int(getattr(
args, "vjepa2_student_source_num_frames",
default_student_source_frames,
))
self.vjepa2_dense_window_seed = str(getattr(
args, "vjepa2_dense_window_seed", "sf-vjepa2-window-v1"))
self.vjepa2_dense_num_tokens = int(
getattr(args, "vjepa2_dense_num_tokens", 128))
self.vjepa2_dense_resize_short_side = int(
getattr(args, "vjepa2_dense_resize_short_side", 292))
self.vjepa2_dense_crop_size = int(
getattr(args, "vjepa2_dense_crop_size", 256))
self.vjepa2_dense_gradient_checkpointing = bool(
getattr(args, "vjepa2_dense_gradient_checkpointing", True))
if any(layer < 0 for layer in self.vjepa2_dense_layers):
raise ValueError(
"V-JEPA2 dense layer indices must be non-negative")
if self.vjepa2_dense_num_frames <= 0:
raise ValueError("vjepa2_dense_num_frames must be positive")
if self.vjepa2_dense_frame_sampling not in {
"center_contiguous",
"random_contiguous_per_video",
}:
raise ValueError(
"vjepa2_dense_frame_sampling must be center_contiguous or "
"random_contiguous_per_video")
if self.vjepa2_student_frame_sampling not in {
"center_contiguous",
"random_contiguous_per_video",
"last_contiguous",
}:
raise ValueError(
"vjepa2_student_frame_sampling must be center_contiguous, "
"random_contiguous_per_video, or last_contiguous")
if (
self.vjepa2_student_frame_sampling
!= self.vjepa2_dense_frame_sampling
and self.vjepa2_student_frame_sampling != "last_contiguous"
):
raise ValueError(
"only last_contiguous may intentionally differ from the "
"frozen-reference frame sampling")
if (
self.vjepa2_student_frame_sampling == "last_contiguous"
and self.vjepa2_dense_frame_sampling != "center_contiguous"
):
raise ValueError("last_contiguous requires a center64 reference")
if (
self.vjepa2_student_source_num_frames
< self.vjepa2_dense_num_frames
):
raise ValueError(
"vjepa2_student_source_num_frames must be at least "
"vjepa2_dense_num_frames")
if self.vjepa2_student_frame_sampling == "last_contiguous" and (
self.vjepa2_dense_num_frames != 64
or self.vjepa2_student_source_num_frames != 81
):
raise ValueError(
"last_contiguous is the strict 81-frame last64 contract and "
"requires vjepa2_dense_num_frames=64 plus "
"vjepa2_student_source_num_frames=81")
if self.vjepa2_dense_source_num_frames < self.vjepa2_dense_num_frames:
raise ValueError(
"vjepa2_dense_source_num_frames must be at least "
"vjepa2_dense_num_frames")
if not self.vjepa2_dense_window_seed:
raise ValueError(
"vjepa2_dense_window_seed must be a non-empty string")
if (
self.vjepa2_student_frame_sampling
== "random_contiguous_per_video"
and self.mmd_estimator != "nystrom_exact_repulsion"
):
raise ValueError(
"random V-JEPA2 temporal windows require "
"wan_mmd_estimator=nystrom_exact_repulsion")
if self.vjepa2_dense_num_tokens <= 1:
raise ValueError("vjepa2_dense_num_tokens must be > 1")
if (
self.vjepa2_dense_crop_size <= 0
or self.vjepa2_dense_resize_short_side
< self.vjepa2_dense_crop_size
):
raise ValueError(
"V-JEPA2 resize_short_side must be >= positive crop_size")
adapter_config = {
"name": "vjepa2_dense",
"model_id": self.vjepa2_model_load_path,
"input_frames": self.vjepa2_dense_num_frames,
"dense_num_frames": self.vjepa2_dense_num_frames,
"input_size": self.vjepa2_dense_crop_size,
"resize_short_side": self.vjepa2_dense_resize_short_side,
"crop_mode": "center",
"dense_only": True,
"dense_layer_index": self.vjepa2_dense_layer,
}
self.vjepa2_encoder = VJEPA2Adapter(adapter_config)
self.vjepa2_encoder.to(device=device, dtype=torch.float32)
self.vjepa2_encoder.eval().requires_grad_(False)
actual_geometry = (
int(self.vjepa2_encoder.dense_layer_index),
int(self.vjepa2_encoder.dense_num_frames),
int(self.vjepa2_encoder.resize_short_side),
int(self.vjepa2_encoder.input_size),
int(self.vjepa2_encoder.retained_dense_blocks),
)
expected_geometry = (
self.vjepa2_dense_layer,
self.vjepa2_dense_num_frames,
self.vjepa2_dense_resize_short_side,
self.vjepa2_dense_crop_size,
self.vjepa2_dense_layer + 1,
)
if actual_geometry != expected_geometry:
raise RuntimeError(
"loaded V-JEPA2 adapter geometry does not match the requested "
"dense-prefix configuration: "
f"actual={actual_geometry}, expected={expected_geometry}")
self.vjepa2_dense_raw_tokens = int(
self.vjepa2_encoder.dense_raw_tokens)
self.vjepa2_dense_feature_dim = int(
self.vjepa2_encoder.dense_feature_dim)
if self.vjepa2_dense_num_tokens > self.vjepa2_dense_raw_tokens:
raise ValueError(
"vjepa2_dense_num_tokens cannot exceed the full dense grid: "
f"{self.vjepa2_dense_num_tokens} > "
f"{self.vjepa2_dense_raw_tokens}")
self._bind_dense_runtime_aliases()
def _initialize_motionformer_features(self, args, device) -> None:
"""Build the optional frozen MotionFormer dense-prefix extractor."""
from video_fd.encoders.motionformer_adapter import (
MotionFormerAdapter,
SSV2_MOTIONFORMER_224_16X4_SHA256,
)
configured_path = str(getattr(
args, "motionformer_checkpoint_path", "")).strip()
checkpoint_path = os.path.realpath(
os.path.expanduser(configured_path)) if configured_path else ""
if not checkpoint_path or not os.path.isfile(checkpoint_path):
raise FileNotFoundError(
"wan_feature_type=motionformer_dense_latent requires "
"motionformer_checkpoint_path; got "
f"{checkpoint_path!r}")
checkpoint_sha256 = str(getattr(
args, "motionformer_checkpoint_sha256", "")).strip().lower()
if (
len(checkpoint_sha256) != 64
or any(c not in "0123456789abcdef" for c in checkpoint_sha256)
):
raise ValueError(
"motionformer_checkpoint_sha256 must be a lowercase SHA-256")
if checkpoint_sha256 != SSV2_MOTIONFORMER_224_16X4_SHA256:
raise ValueError(
"motionformer_checkpoint_sha256 must identify the official "
"SSv2 Base 16x4 checkpoint")
self.motionformer_checkpoint_path = checkpoint_path
self.motionformer_checkpoint_sha256 = checkpoint_sha256
self.motionformer_dense_layer = int(getattr(
args, "motionformer_dense_layer", 11))
self.motionformer_dense_num_frames = int(getattr(
args, "motionformer_dense_num_frames", 16))
self.motionformer_dense_num_tokens = int(getattr(
args, "motionformer_dense_num_tokens", 128))
self.motionformer_dense_resize_short_side = int(getattr(
args, "motionformer_dense_resize_short_side", 224))
self.motionformer_dense_crop_size = int(getattr(
args, "motionformer_dense_crop_size", 224))
self.motionformer_dense_gradient_checkpointing = bool(getattr(
args, "motionformer_dense_gradient_checkpointing", True))
if self.motionformer_dense_layer != 11:
raise ValueError(
"the supported SSv2 MotionFormer feature contract fixes "
"motionformer_dense_layer=11")
if self.motionformer_dense_num_frames != 16:
raise ValueError(
"the supported SSv2 MotionFormer feature contract fixes "
"motionformer_dense_num_frames=16")
if (
self.motionformer_dense_resize_short_side != 224
or self.motionformer_dense_crop_size != 224
):
raise ValueError(
"the supported SSv2 MotionFormer preprocessing contract fixes "
"resize_short_side=crop_size=224")
if self.motionformer_dense_num_tokens <= 1:
raise ValueError("motionformer_dense_num_tokens must be > 1")
adapter_config = {
"name": "motionformer_dense",
"checkpoint_path": checkpoint_path,
"checkpoint_sha256": checkpoint_sha256,
"input_frames": self.motionformer_dense_num_frames,
"dense_num_frames": self.motionformer_dense_num_frames,
"input_size": self.motionformer_dense_crop_size,
"resize_short_side": self.motionformer_dense_resize_short_side,
"crop_mode": "center",
"dense_only": True,
"dense_layer_index": self.motionformer_dense_layer,
"use_original_trajectory_attention": True,
}
self.motionformer_encoder = MotionFormerAdapter(adapter_config)
self.motionformer_encoder.to(device=device, dtype=torch.float32)
self.motionformer_encoder.eval().requires_grad_(False)
actual_geometry = (
int(self.motionformer_encoder.dense_layer_index),
int(self.motionformer_encoder.dense_num_frames),
int(self.motionformer_encoder.input_size),
int(self.motionformer_encoder.retained_dense_blocks),
)
expected_geometry = (
self.motionformer_dense_layer,
self.motionformer_dense_num_frames,
self.motionformer_dense_crop_size,
self.motionformer_dense_layer + 1,
)
if actual_geometry != expected_geometry:
raise RuntimeError(
"loaded MotionFormer adapter geometry does not match the "
"requested dense-prefix configuration: "
f"actual={actual_geometry}, expected={expected_geometry}")
self.motionformer_dense_raw_tokens = int(
self.motionformer_encoder.dense_raw_tokens)
self.motionformer_dense_feature_dim = int(
self.motionformer_encoder.dense_feature_dim)
if self.motionformer_dense_raw_tokens != 1568:
raise RuntimeError(
"SSv2 MotionFormer must expose 1568 non-CLS dense tokens, got "
f"{self.motionformer_dense_raw_tokens}")
if self.motionformer_dense_feature_dim != 768:
raise RuntimeError(
"SSv2 MotionFormer must expose 768-dimensional features, got "
f"{self.motionformer_dense_feature_dim}")
if (
self.motionformer_dense_num_tokens
> self.motionformer_dense_raw_tokens
):
raise ValueError(
"motionformer_dense_num_tokens cannot exceed the full dense "
f"grid: {self.motionformer_dense_num_tokens} > "
f"{self.motionformer_dense_raw_tokens}")
# The replay/MMD implementation below deliberately consumes one common
# dense-encoder contract. These private aliases keep the already
# validated V-JEPA2 implementation and its legacy tests byte-compatible;
# public generic aliases are what the trainer uses.
self.vjepa2_model_id = checkpoint_path
self.vjepa2_dense_layer = self.motionformer_dense_layer
self.vjepa2_dense_layers = (self.motionformer_dense_layer,)
self.vjepa2_multilayer_enabled = False
self.vjepa2_dense_num_frames = self.motionformer_dense_num_frames
# MotionFormer receives the complete decoded video and performs its
# official 16-segment midpoint sampling inside the adapter. Mark this
# as non-random so the V-JEPA2-only contiguous-window machinery stays
# dormant.
self.vjepa2_dense_frame_sampling = "center_contiguous"
self.vjepa2_dense_source_num_frames = (
self.motionformer_dense_num_frames)
self.vjepa2_dense_window_seed = ""
self.vjepa2_dense_num_tokens = self.motionformer_dense_num_tokens
self.vjepa2_dense_resize_short_side = (
self.motionformer_dense_resize_short_side)
self.vjepa2_dense_crop_size = self.motionformer_dense_crop_size
self.vjepa2_dense_gradient_checkpointing = (
self.motionformer_dense_gradient_checkpointing)
self.vjepa2_encoder = self.motionformer_encoder
self.vjepa2_dense_raw_tokens = self.motionformer_dense_raw_tokens
self.vjepa2_dense_feature_dim = self.motionformer_dense_feature_dim
self._bind_dense_runtime_aliases()
def _bind_dense_runtime_aliases(self) -> None:
"""Publish the encoder-neutral runtime interface used by DistributionMatchingTrainer."""
self.dense_encoder = self.vjepa2_encoder
self.dense_layer = self.vjepa2_dense_layer
self.dense_num_frames = self.vjepa2_dense_num_frames
self.dense_num_tokens = self.vjepa2_dense_num_tokens
self.dense_resize_short_side = self.vjepa2_dense_resize_short_side
self.dense_crop_size = self.vjepa2_dense_crop_size
self.dense_gradient_checkpointing = (
self.vjepa2_dense_gradient_checkpointing)
self.dense_raw_tokens = self.vjepa2_dense_raw_tokens
self.dense_feature_dim = self.vjepa2_dense_feature_dim
def _initialize_dual_dinov3_vjepa2_features(
self,
args,
device,
) -> None:
"""Build only the frozen DINOv3 and V-JEPA2 prefixes."""
self.fresh_video_total_samples = int(getattr(
args, "total_batch_size", 0))
if self.fresh_video_total_samples <= 0:
raise ValueError(
"DINOv3+V-JEPA2 MMD requires positive total_batch_size")
self._initialize_vjepa2_features(args, device)
expected_vjepa = {
"layers": (15,),
"frames": 64,
"source_frames": 81,
"student_sampling": "last_contiguous",
"tokens": 1024,
"feature_dim": 1024,
}
actual_vjepa = {
"layers": tuple(self.vjepa2_dense_layers),
"frames": int(self.vjepa2_dense_num_frames),
"source_frames": int(self.vjepa2_student_source_num_frames),
"student_sampling": str(self.vjepa2_student_frame_sampling),
"tokens": int(self.vjepa2_dense_num_tokens),
"feature_dim": int(self.vjepa2_dense_feature_dim),
}
if actual_vjepa != expected_vjepa:
raise ValueError(
"dual DINOv3+V-JEPA2 contract fixes V-JEPA2 layer15, "
"frames17..80, K=1024 and D=1024: "
f"actual={actual_vjepa}, expected={expected_vjepa}")
self._initialize_dinov3_features(args, device)
actual_dinov3 = {
"geometry": self.dinov3_dense_geometry,
"source_frames": self.dinov3_dense_source_num_frames,
"sample_shape": (
self.dinov3_dense_num_tokens,
self.dinov3_dense_feature_dim,
),
}
expected_dinov3 = {
"geometry": "temporal_mean5_full256",
"source_frames": 81,
"sample_shape": (1024, 1024),
}
if actual_dinov3 != expected_dinov3:
raise ValueError(
"dual DINOv3+V-JEPA2 contract fixes DINOv3 to 20 frames, "
"mean5, K=1024 and D=1024: "
f"actual={actual_dinov3}, expected={expected_dinov3}")
self.dual_branch_registry = {
"dinov3": {
"encoder_attribute": "dinov3_encoder",
"source_frame_indices": list(
self.dinov3_dense_frame_indices),
"sample_shape": (1024, 1024),
"tokens_per_temporal_group": 256,
"temporal_groups": 4,
"model_id": self.dinov3_model_id,
"source_commit": self.dinov3_source_commit,
"checkpoint_sha256": getattr(
self.dinov3_encoder, "checkpoint_sha256", ""),
},
"vjepa2": {
"encoder_attribute": "vjepa2_encoder",
"layer": 15,
"source_frame_range": [17, 80],
"sample_shape": (1024, 1024),
"tokens_per_segment": 1024,
"segments": 1,
"model_id": self.vjepa2_reference_model_id,
"model_sha256": self.vjepa2_model_sha256,
},
}
def _replace_with_dual_dinov3_vjepa2_nystrom_objective(
self, args, device
) -> None:
"""Bind two Wan-video references and sum normalized branch MMDs."""
from losses.multi_encoder_mmd import (
MultiEncoderMMD,
)
from losses.video_nystrom_mmd import (
VideoNystromMMD,
load_reference_pack,
)
self.fresh_video_gradient_global_samples = (
self._configured_current_teacher_global_samples(args))
if not self.uses_fresh_video_gradcache:
raise ValueError(
"DINOv3+V-JEPA2 MMD requires nystrom_exact_repulsion")
if not self.latent_self_normalize:
raise ValueError(
"DINOv3+V-JEPA2 MMD requires self normalization")
if (
self.nystrom_attraction_ema_enabled
or self.nystrom_repulsion_fifo_enabled
):
raise ValueError(
"DINOv3+V-JEPA2 MMD requires EMA and FIFO disabled")
if self.current_teacher_attraction_enabled:
if (
self.nystrom_attraction_weight != 2.0
or self.current_teacher_attraction_weight != 1.0
):
raise ValueError(
"DINOv3+V-JEPA2 fixed/random teacher weights must be 2:1")
if self.expected_current_teacher_samples != 128:
raise ValueError(
"DINOv3+V-JEPA2 current-teacher mode requires 128 "
"matched teachers")
else:
if self.current_teacher_source != "none":
raise ValueError(
"fixed-only DINOv3+V-JEPA2 requires "
"current_teacher_source=none")
if self.nystrom_attraction_weight != 1.0:
raise ValueError(
"fixed-only DINOv3+V-JEPA2 requires fixed attraction "
"weight 1.0")
if self.current_teacher_attraction_weight != 0.0:
raise ValueError(
"fixed-only DINOv3+V-JEPA2 requires current-teacher "
"weight 0.0")
if self.expected_current_teacher_samples != 0:
raise ValueError(
"fixed-only DINOv3+V-JEPA2 requires zero expected "
"current-teacher samples")
if (
self.vjepa2_reference_frame_sampling != "center_contiguous"
or self.vjepa2_reference_token_contract
!= "legacy_uniform_implicit_v1"
):
raise ValueError(
"fixed-only OpenVid V-JEPA2 requires the approved "
"center64 legacy_uniform_implicit_v1 reference contract")
def strict_sha256(value, label):
normalized = str(value).strip().lower()
if (
len(normalized) != 64
or any(c not in "0123456789abcdef" for c in normalized)
):
raise ValueError(f"{label} must be a lowercase SHA-256")
return normalized
def checked_reference_path(path_value, sha_value, label):
path = os.path.realpath(os.path.expanduser(str(path_value)))
if not os.path.isfile(path):
raise FileNotFoundError(
f"DINOv3+V-JEPA2 {label} reference missing: {path!r}")
expected_sha = strict_sha256(sha_value, f"{label} reference SHA-256")
actual_sha = self._distributed_file_sha256(path)
if actual_sha != expected_sha:
raise ValueError(
f"{label} reference SHA-256 mismatch: "
f"{actual_sha} != {expected_sha}")
return path, expected_sha, load_reference_pack(
path, map_location="cpu")
# Each encoder owns its reference summary; the wrapper combines normalized losses.
vjepa_objective = self.latent_mmd
if not isinstance(vjepa_objective, VideoNystromMMD):
raise TypeError(
"dual bootstrap V-JEPA2 objective must be VideoNystromMMD")
vjepa_path = self.vjepa2_nystrom_reference_path
vjepa_file_sha = strict_sha256(
self._dense_config_value(
args, "nystrom_reference_sha256", ""),
"V-JEPA2 reference SHA-256",
)
if self._distributed_file_sha256(vjepa_path) != vjepa_file_sha:
raise ValueError(
"dual V-JEPA2 reference file SHA-256 mismatch")
dinov3_path, dinov3_file_sha, dinov3_pack = checked_reference_path(
getattr(args, "dinov3_nystrom_reference_path", ""),
getattr(args, "dinov3_nystrom_reference_sha256", ""),
"DINOv3",
)
dinov3_objective = VideoNystromMMD(
dinov3_pack,
expected_metadata={
"feature": self._dinov3_feature_metadata(),
"nystrom": {
"num_landmarks": int(getattr(
args, "dinov3_nystrom_landmarks", 256)),
"seed": int(getattr(args, "dinov3_nystrom_seed", 0)),
},
},
kernel_chunk_size=int(getattr(
args, "dinov3_nystrom_kernel_chunk_size", 32)),
attraction_weight=self.nystrom_attraction_weight,
current_teacher_attraction_enabled=(
self.current_teacher_attraction_enabled),
current_teacher_attraction_weight=(
self.current_teacher_attraction_weight),
attraction_ema_enabled=False,
repulsion_fifo_size=0,
).to(device=device)
objectives = {
"dinov3": dinov3_objective,
"vjepa2": vjepa_objective,
}
expected_shapes = {
"dinov3": (1024, 1024),
"vjepa2": (1024, 1024),
}
actual_shapes = {
name: tuple(objective.sample_shape)
for name, objective in objectives.items()
}
if actual_shapes != expected_shapes:
raise ValueError(
"dual reference sample-shape mismatch: "
f"actual={actual_shapes}, expected={expected_shapes}")
if self.current_teacher_attraction_enabled:
configured_reference_identity = strict_sha256(
getattr(args, "dinov3_vjepa2_teacher_bank_content_hash", ""),
"dinov3_vjepa2_teacher_bank_content_hash",
)
expected_manifest_hash = strict_sha256(
getattr(args, "matched_manifest_sha256", ""),
"matched_manifest_sha256",
)
for name, objective in objectives.items():
source = objective.reference_metadata.get(
"reference", {}).get("source", {})
if (
source.get("dinov3_vjepa2_teacher_bank_content_hash")
!= configured_reference_identity
or source.get("source_manifest_sha256")
!= expected_manifest_hash
or int(source.get("selected_samples", -1)) != 5000
or source.get("branch_name") != name
):
raise ValueError(
f"{name} reference is not bound to the configured "
"frozen 5000-Wan-video DINOv3+V-JEPA2 bank")
self.dinov3_vjepa2_teacher_bank_content_hash = (
configured_reference_identity)
else:
bundle_path = os.path.realpath(os.path.expanduser(str(getattr(
args, "dinov3_vjepa2_reference_bundle_manifest", ""))))
if not os.path.isfile(bundle_path):
raise FileNotFoundError(
"fixed-only OpenVid reference bundle is missing: "
f"{bundle_path!r}")
configured_reference_identity = strict_sha256(
getattr(
args,
"dinov3_vjepa2_reference_bundle_manifest_sha256",
"",
),
"dinov3_vjepa2_reference_bundle_manifest_sha256",
)
actual_bundle_sha = self._distributed_file_sha256(bundle_path)
if actual_bundle_sha != configured_reference_identity:
raise ValueError(
"OpenVid dual reference bundle SHA-256 mismatch: "
f"{actual_bundle_sha} != {configured_reference_identity}")
with open(bundle_path, "r", encoding="utf-8") as handle:
bundle = json.load(handle)
expected_count = int(getattr(
args, "openvid_reference_count", 77615))
expected_sequence = strict_sha256(
getattr(args, "openvid_video_name_sequence_sha256", ""),
"openvid_video_name_sequence_sha256",
)
if (
bundle.get("kind")
!= "openvid_dual_nystrom_reference_bundle"
or int(bundle.get("schema_version", -1)) != 1
or int(bundle.get("reference_count", -1)) != expected_count
or bundle.get("video_name_sequence_sha256")
!= expected_sequence
or set(bundle.get("branches", {}))
!= {"dinov3", "vjepa2"}
):
raise ValueError(
"OpenVid dual reference bundle identity/schema mismatch")
bridge = bundle.get("legacy_vjepa_provenance_bridge", {})
if (
bridge.get("accepted") is not True
or bridge.get("limitation")
!= "legacy_pack_has_no_embedded_row_name_sequence"
):
raise ValueError(
"OpenVid bundle must explicitly attest the accepted legacy "
"V-JEPA provenance limitation")
expected_files = {
"dinov3": dinov3_file_sha,
"vjepa2": vjepa_file_sha,
}
for name, objective in objectives.items():
entry = bundle["branches"].get(name, {})
nystrom = objective.reference_metadata.get("nystrom", {})
if (
entry.get("file_sha256") != expected_files[name]
or entry.get("content_hash") != objective.reference_hash
or entry.get("feature")
!= objective.reference_metadata.get("feature")
or int(entry.get("reference_count", -1))
!= expected_count
or int(nystrom.get("reference_count", -1))
!= expected_count
):
raise ValueError(
f"OpenVid bundle does not bind the loaded {name} "
"reference pack")
self.dinov3_vjepa2_reference_bundle_manifest = bundle_path
self.dinov3_vjepa2_reference_bundle_manifest_sha256 = (
configured_reference_identity)
self.openvid_video_name_sequence_sha256 = expected_sequence
# Paper Eq. (3) motivates encoder weighting; this release also uses detached-scale normalization.
branch_weights = {
"dinov3": float(getattr(
args, "dinov3_vjepa2_dinov3_weight", 10.0)),
"vjepa2": float(getattr(
args, "dinov3_vjepa2_vjepa2_weight", 1.0)),
}
if branch_weights != {"dinov3": 10.0, "vjepa2": 1.0}:
raise ValueError(
"DINOv3+V-JEPA2 representation weights must be exactly 10:1")
self.latent_mmd = MultiEncoderMMD(
objectives,
weights=branch_weights,
normalization_eps=self.latent_norm_eps,
).to(device=device)
self.dinov3_nystrom_reference_path = dinov3_path
self.dinov3_nystrom_reference_hash = dinov3_objective.reference_hash
self.dual_teacher_bank_content_hash = configured_reference_identity
reference_files = {
"dinov3": dinov3_file_sha,
"vjepa2": vjepa_file_sha,
}
reference_paths = {
"dinov3": dinov3_path,
"vjepa2": vjepa_path,
}
for name, objective in objectives.items():
self.dual_branch_registry[name].update({
"reference_path": reference_paths[name],
"reference_file_sha256": reference_files[name],
"reference_hash": objective.reference_hash,
"nystrom_landmarks": int(objective.landmarks.shape[0]),
})
def _initialize_multi_encoder_features(
self,
args,
device,
) -> None:
"""Build the frozen feature encoders and their video/token geometry.
The released 14B recipe uses all three encoders. The explicit list also
supports ablations; saved attribute names stay compatible."""
self.dinov3_reference_paths = dict(getattr(args, "dinov3_reference_paths", {}))
self.triple_active_branches = active_mmd_branches(
getattr(args, "triple_active_branches", None))
self.fresh_video_total_samples = int(getattr(
args, "total_batch_size", 0))
if self.fresh_video_total_samples <= 0:
raise ValueError(
"triple video MMD requires positive total_batch_size")
self._initialize_vjepa2_features(args, device)
vjepa_attribute_names = (
"vjepa2_model_load_path",
"vjepa2_reference_model_id",
"vjepa2_model_sha256",
"vjepa2_model_id",
"vjepa2_dense_layers",
"vjepa2_multilayer_enabled",
"vjepa2_dense_layer",
"vjepa2_dense_num_frames",
"vjepa2_dense_frame_sampling",
"vjepa2_reference_frame_sampling",
"vjepa2_reference_token_contract",
"vjepa2_dense_source_num_frames",
"vjepa2_student_frame_sampling",
"vjepa2_student_source_num_frames",
"vjepa2_dense_window_seed",
"vjepa2_dense_num_tokens",
"vjepa2_dense_resize_short_side",
"vjepa2_dense_crop_size",
"vjepa2_dense_gradient_checkpointing",
"vjepa2_dense_raw_tokens",
"vjepa2_dense_feature_dim",
)
vjepa_state = {
name: getattr(self, name) for name in vjepa_attribute_names
}
vjepa_encoder = self.vjepa2_encoder
expected_vjepa = {
"layers": (15,),
"frames": 64,
"source_frames": 81,
"student_sampling": "last_contiguous",
"tokens": 1024,
"feature_dim": 1024,
}
actual_vjepa = {
"layers": tuple(self.vjepa2_dense_layers),
"frames": int(self.vjepa2_dense_num_frames),
"source_frames": int(self.vjepa2_student_source_num_frames),
"student_sampling": str(self.vjepa2_student_frame_sampling),
"tokens": int(self.vjepa2_dense_num_tokens),
"feature_dim": int(self.vjepa2_dense_feature_dim),
}
if actual_vjepa != expected_vjepa:
raise ValueError(
"triple V-JEPA2 contract is fixed to layer15, frames17..80, "
"K=1024 and D=1024: "
f"actual={actual_vjepa}, expected={expected_vjepa}")
self._initialize_videomae_v2_features(args, device)
expected_videomae = {
"layers": (15,),
"segments": 5,
"skip": 1,
"frames_per_segment": 16,
"source_frames": 81,
"tokens_per_segment": 256,
"feature_dim": 1024,
}
actual_videomae = {
"layers": tuple(self.videomae_v2_dense_layers),
"segments": int(self.videomae_v2_encoder_count),
"skip": int(self.videomae_v2_skip_leading_frames),
"frames_per_segment": int(self.videomae_v2_segment_num_frames),
"source_frames": int(self.videomae_v2_source_num_frames),
"tokens_per_segment": int(self.videomae_v2_dense_num_tokens),
"feature_dim": int(self.videomae_v2_encoder.dense_feature_dim),
}
if actual_videomae != expected_videomae:
raise ValueError(
"triple VideoMAE-v2 contract is fixed to layer15, frames1..80 "
"as 5x16, K=256 per segment and D=1024: "
f"actual={actual_videomae}, expected={expected_videomae}")
for name, value in vjepa_state.items():
setattr(self, name, value)
self.vjepa2_encoder = vjepa_encoder
self.dense_feature_segment_count = 1
self._bind_dense_runtime_aliases()
self.dual_branch_registry = {}
if "dinov3" in self.triple_active_branches:
self._initialize_dinov3_features(args, device)
actual_dinov3 = {
"geometry": self.dinov3_dense_geometry,
"source_frames": self.dinov3_dense_source_num_frames,
"sample_shape": (
self.dinov3_dense_num_tokens,
self.dinov3_dense_feature_dim,
),
}
expected_dinov3 = {
"geometry": "temporal_mean5_full256",
"source_frames": 81,
"sample_shape": (1024, 1024),
}
if actual_dinov3 != expected_dinov3:
raise ValueError(
"triple DINOv3 contract is fixed to 20 frames, mean-pool "
"consecutive groups of 5, K=1024 and D=1024: "
f"actual={actual_dinov3}, expected={expected_dinov3}")
self.dual_branch_registry["dinov3"] = {
"encoder_attribute": "dinov3_encoder",
"source_frame_indices": list(
self.dinov3_dense_frame_indices),
"sample_shape": (1024, 1024),
"tokens_per_temporal_group": 256,
"temporal_groups": 4,
"model_id": self.dinov3_model_id,
"source_commit": self.dinov3_source_commit,
"checkpoint_sha256": getattr(
self.dinov3_encoder, "checkpoint_sha256", ""),
}
self.dual_branch_registry.update({
"vjepa2": {
"encoder_attribute": "vjepa2_encoder",
"layer": 15,
"source_frame_range": [17, 80],
"sample_shape": (1024, 1024),
"tokens_per_segment": 1024,
"segments": 1,
"model_id": self.vjepa2_reference_model_id,
"model_sha256": self.vjepa2_model_sha256,
},
"videomae_v2": {
"encoder_attribute": "videomae_v2_encoder",
"layer": 15,
"source_frame_range": [1, 80],
"sample_shape": (1280, 1024),
"tokens_per_segment": 256,
"segments": 5,
"model_id": self.videomae_v2_model_id,
"model_revision": str(getattr(
args, "videomae_v2_model_revision", "")),
"download_manifest_content_hash": (
self.videomae_v2_download_manifest_content_hash),
},
})
def _build_multi_encoder_objective(self, args, device) -> None:
"""Bind each encoder to its fixed reference summary and combine its loss.
The hybrid reference uses both Nyström statistics and a sampled reference
minibatch. Encoder weights follow the release's detached-scale normalization."""
active_branches = active_mmd_branches(
getattr(args, "triple_active_branches", None))
from losses.multi_encoder_mmd import (
MultiEncoderMMD,
)
from losses.video_nystrom_mmd import (
VideoNystromMMD,
load_reference_pack,
)
from video_fd.encoders.videomae_v2_dense_metadata import (
canonical_videomae_v2_dense_feature_metadata,
uniform_segment_token_indices,
)
if not self.uses_fresh_video_gradcache:
raise ValueError(
"triple video MMD requires nystrom_exact_repulsion")
if not self.latent_self_normalize:
raise ValueError(
"triple video MMD requires wan_kv_self_normalize=true")
if (
self.nystrom_attraction_ema_enabled
or self.nystrom_repulsion_fifo_enabled
):
raise ValueError(
"triple video MMD requires EMA and FIFO disabled")
if not self.current_teacher_attraction_enabled:
raise ValueError(
"triple video MMD requires exact matched teacher MMD")
if (
self.nystrom_attraction_weight != 2.0
or self.current_teacher_attraction_weight != 1.0
):
raise ValueError(
"triple fixed/current teacher weights must be exactly 2:1")
if self.expected_current_teacher_samples != 128:
raise ValueError(
"triple objective requires exactly 128 matched teachers")
def strict_sha256(value, label):
normalized = str(value).strip().lower()
if (
len(normalized) != 64
or any(c not in "0123456789abcdef" for c in normalized)
):
raise ValueError(f"{label} must be a lowercase SHA-256")
return normalized
def checked_reference_path(path_value, sha_value, label):
path = os.path.realpath(os.path.expanduser(str(path_value)))
if not os.path.isfile(path):
raise FileNotFoundError(
f"triple {label} reference pack is missing: {path!r}")
expected_sha = strict_sha256(sha_value, f"{label} reference SHA-256")
actual_sha = self._distributed_file_sha256(path)
if actual_sha != expected_sha:
raise ValueError(
f"triple {label} reference file SHA-256 mismatch: "
f"{actual_sha} != {expected_sha}")
return path, expected_sha, load_reference_pack(
path, map_location="cpu")
# Each encoder owns its reference summary; the wrapper combines normalized losses.
vjepa_objective = self.latent_mmd
if not isinstance(vjepa_objective, VideoNystromMMD):
raise TypeError(
"triple bootstrap V-JEPA2 objective must be VideoNystromMMD")
vjepa_path = self.vjepa2_nystrom_reference_path
configured_vjepa_reference_sha = strict_sha256(
self._dense_config_value(
args, "nystrom_reference_sha256", ""),
"V-JEPA2 reference SHA-256",
)
if self._distributed_file_sha256(
vjepa_path
) != configured_vjepa_reference_sha:
raise ValueError(
"triple V-JEPA2 reference file SHA-256 mismatch")
objectives = {}
reference_files = {}
reference_paths = {}
if "dinov3" in active_branches:
dinov3_path, dinov3_file_sha, dinov3_pack = checked_reference_path(
getattr(args, "dinov3_nystrom_reference_path", ""),
getattr(args, "dinov3_nystrom_reference_sha256", ""),
"DINOv3",
)
dinov3_objective = VideoNystromMMD(
dinov3_pack,
expected_metadata={
"feature": self._dinov3_feature_metadata(),
"nystrom": {
"num_landmarks": int(getattr(
args, "dinov3_nystrom_landmarks", 256)),
"seed": int(getattr(args, "dinov3_nystrom_seed", 0)),
},
},
kernel_chunk_size=int(getattr(
args, "dinov3_nystrom_kernel_chunk_size", 32)),
attraction_weight=2.0,
current_teacher_attraction_enabled=True,
current_teacher_attraction_weight=1.0,
attraction_ema_enabled=False,
repulsion_fifo_size=0,
).to(device=device)
objectives["dinov3"] = dinov3_objective
reference_files["dinov3"] = dinov3_file_sha
reference_paths["dinov3"] = dinov3_path
self.dinov3_nystrom_reference_path = dinov3_path
self.dinov3_nystrom_reference_hash = dinov3_objective.reference_hash
videomae_path, videomae_file_sha, videomae_pack = checked_reference_path(
getattr(args, "videomae_v2_nystrom_reference_path", ""),
getattr(args, "videomae_v2_nystrom_reference_sha256", ""),
"VideoMAE-v2",
)
video_tokens = uniform_segment_token_indices(
self.videomae_v2_encoder.dense_raw_tokens,
self.videomae_v2_dense_num_tokens,
)
video_feature_metadata = canonical_videomae_v2_dense_feature_metadata(
model_id=self.videomae_v2_reference_model_id,
model_id_is_reference=True,
layer_index=15,
num_tokens=256,
token_indices=video_tokens,
num_segments=5,
frames_per_segment=16,
raw_tokens_per_segment=(
self.videomae_v2_encoder.dense_raw_tokens),
feature_dim=self.videomae_v2_encoder.dense_feature_dim,
resize_short_side=224,
crop_size=224,
skip_first_frame=True,
)
videomae_objective = VideoNystromMMD(
videomae_pack,
expected_metadata={
"feature": video_feature_metadata,
"nystrom": {
"num_landmarks": int(getattr(
args, "videomae_v2_nystrom_landmarks", 256)),
"seed": int(getattr(
args, "videomae_v2_nystrom_seed", 0)),
},
},
kernel_chunk_size=int(getattr(
args, "videomae_v2_nystrom_kernel_chunk_size", 32)),
attraction_weight=2.0,
current_teacher_attraction_enabled=True,
current_teacher_attraction_weight=1.0,
attraction_ema_enabled=False,
repulsion_fifo_size=0,
).to(device=device)
objectives.update({
"vjepa2": vjepa_objective,
"videomae_v2": videomae_objective,
})
expected_shapes = {
"dinov3": (1024, 1024),
"vjepa2": (1024, 1024),
"videomae_v2": (1280, 1024),
}
expected_shapes = {name: expected_shapes[name] for name in active_branches}
actual_shapes = {
name: tuple(objective.sample_shape)
for name, objective in objectives.items()
}
if actual_shapes != expected_shapes:
raise ValueError(
"triple reference sample-shape mismatch: "
f"actual={actual_shapes}, expected={expected_shapes}")
configured_bank_hash = strict_sha256(
getattr(args, "triple_teacher_bank_content_hash", ""),
"triple_teacher_bank_content_hash",
)
expected_manifest_hash = strict_sha256(
getattr(args, "matched_manifest_sha256", ""),
"matched_manifest_sha256",
)
expected_reference_samples = int(getattr(
args, "matched_manifest_samples", 5000))
if expected_reference_samples <= 0:
raise ValueError("matched_manifest_samples must be positive")
sources = {
name: objective.reference_metadata.get(
"reference", {}).get("source", {})
for name, objective in objectives.items()
}
for name, source in sources.items():
if (
source.get("triple_teacher_bank_content_hash")
!= configured_bank_hash
or source.get("source_manifest_sha256")
!= expected_manifest_hash
or int(source.get("selected_samples", -1))
!= expected_reference_samples
or source.get("branch_name") != name
):
raise ValueError(
f"{name} reference is not bound to the configured frozen "
f"{expected_reference_samples}-video triple teacher bank")
# Paper Eq. (3) motivates encoder weighting; this release also uses detached-scale normalization.
branch_weights = {
"dinov3": float(getattr(args, "triple_dinov3_weight", 10.0)),
"vjepa2": float(getattr(args, "triple_vjepa2_weight", 1.0)),
"videomae_v2": float(getattr(
args, "triple_videomae_v2_weight", 1.0)),
}
branch_weights = {name: branch_weights[name] for name in active_branches}
expected_weights = {
"dinov3": 10.0,
"vjepa2": 1.0,
"videomae_v2": 1.0,
}
if branch_weights != {name: expected_weights[name] for name in active_branches}:
raise ValueError(
"active representation weights must retain their original values")
aggregation_divisor = float(getattr(
args, "triple_aggregation_divisor", 3.0))
if aggregation_divisor != 3.0:
raise ValueError(
"triple representation aggregation divisor must be exactly 3")
self.latent_mmd = MultiEncoderMMD(
objectives,
weights=branch_weights,
normalization_eps=self.latent_norm_eps,
aggregation_divisor=aggregation_divisor,
).to(device=device)
self.videomae_v2_nystrom_reference_path = videomae_path
self.videomae_v2_nystrom_reference_hash = (
videomae_objective.reference_hash)
self.triple_teacher_bank_content_hash = configured_bank_hash
# Compatibility aliases are internal only; public metadata is triple.
self.dual_teacher_bank_content_hash = configured_bank_hash
reference_files.update({
"vjepa2": configured_vjepa_reference_sha,
"videomae_v2": videomae_file_sha,
})
reference_paths.update({
"vjepa2": vjepa_path,
"videomae_v2": videomae_path,
})
for name, objective in objectives.items():
self.dual_branch_registry[name].update({
"reference_path": reference_paths[name],
"reference_file_sha256": reference_files[name],
"reference_hash": objective.reference_hash,
"nystrom_landmarks": int(objective.landmarks.shape[0]),
})
def _initialize_videomae_v2_features(self, args, device) -> None:
"""Build the fixed five-replica VideoMAE-v2 Large feature map.
Public state is VideoMAE-namespaced. A small set of historical
``vjepa2_*`` aliases is retained only inside this class and its trainer
so the already validated GradCache/VAE replay implementation can be
reused without changing the distribution-loss formula.
"""
from video_fd.encoders.segmented_videomae_v2 import (
SegmentedVideoMAEv2Ensemble,
)
configured_model_id = str(getattr(
args,
"videomae_v2_model_id",
"assets/models/VideoMAEv2-Large",
))
expanded_model_id = os.path.expanduser(configured_model_id)
self.videomae_v2_model_id = (
os.path.realpath(expanded_model_id)
if os.path.exists(expanded_model_id)
else configured_model_id
)
# Keep frozen metadata identity separate from the model's load location.
# The local preparation script reads this identity from the feature bank.
self.videomae_v2_reference_model_id = str(getattr(
args, "videomae_v2_reference_model_id", self.videomae_v2_model_id))
self.videomae_v2_local_files_only = bool(getattr(
args, "videomae_v2_local_files_only", True))
if (
self.videomae_v2_local_files_only
and not os.path.isdir(self.videomae_v2_model_id)
):
raise FileNotFoundError(
"VideoMAE-v2 training requires the pinned local checkpoint "
"directory; prepare the local VideoMAEv2-Large files first: "
f"{self.videomae_v2_model_id}")
self.videomae_v2_model_revision = str(getattr(
args, "videomae_v2_model_revision", ""))
self.videomae_v2_download_manifest_content_hash = str(getattr(
args, "videomae_v2_download_manifest_content_hash", ""))
if self.dual_video_mmd_enabled:
expected_revision = (
"9981a9c8f77118c421e5228e1b219468a4b0238d")
if self.videomae_v2_model_revision != expected_revision:
raise ValueError(
"VideoMAE-v2 revision must be pinned to "
f"{expected_revision}")
download_manifest_path = os.path.join(
self.videomae_v2_model_id, "download_manifest.json")
if not os.path.isfile(download_manifest_path):
raise FileNotFoundError(
"VideoMAE-v2 download_manifest.json is required")
with open(download_manifest_path, "r", encoding="utf-8") as handle:
download_manifest = json.load(handle)
saved_content_hash = download_manifest.get("content_hash")
manifest_payload = dict(download_manifest)
manifest_payload.pop("content_hash", None)
if (
download_manifest.get("revision") != expected_revision
or saved_content_hash
!= self._canonical_sha256(manifest_payload)
or self.videomae_v2_download_manifest_content_hash
!= saved_content_hash
):
raise ValueError(
"VideoMAE-v2 download manifest identity mismatch")
for file_identity in download_manifest.get("files", []):
relative = str(file_identity.get("path", ""))
path = os.path.realpath(os.path.join(
self.videomae_v2_model_id, relative))
if (
not relative
or not path.startswith(self.videomae_v2_model_id + os.sep)
or not os.path.isfile(path)
or os.path.getsize(path) != int(
file_identity.get("size_bytes", -1))
or self._distributed_file_sha256(path)
!= file_identity.get("sha256")
):
raise ValueError(
"VideoMAE-v2 downloaded file identity mismatch: "
f"{relative}")
configured_dense_layers = getattr(
args, "videomae_v2_dense_layers", None)
if configured_dense_layers is None:
dense_layers = (
int(getattr(args, "videomae_v2_dense_layer", 15)),
)
else:
if isinstance(configured_dense_layers, (str, bytes)):
raise TypeError(
"videomae_v2_dense_layers must be a sequence of integers")
dense_layers = tuple(
int(layer) for layer in configured_dense_layers)
if not dense_layers:
raise ValueError(
"videomae_v2_dense_layers must not be empty")
if len(set(dense_layers)) != len(dense_layers):
raise ValueError(
"videomae_v2_dense_layers must contain unique indices")
if tuple(sorted(dense_layers)) != dense_layers:
raise ValueError(
"videomae_v2_dense_layers must be sorted")
if any(layer < 0 or layer >= 24 for layer in dense_layers):
raise ValueError(
"VideoMAE-v2 Large dense layers use zero-based indices in "
"[0,24)")
self.videomae_v2_dense_layers = dense_layers
self.videomae_v2_multilayer_enabled = len(dense_layers) > 1
self.videomae_v2_dense_layer = dense_layers[-1]
self.videomae_v2_encoder_count = int(getattr(
args, "videomae_v2_encoder_count", 5))
self.videomae_v2_share_encoder_weights = bool(getattr(
args, "videomae_v2_share_encoder_weights", False))
self.videomae_v2_skip_leading_frames = int(getattr(
args, "videomae_v2_skip_leading_frames", 1))
self.videomae_v2_segment_num_frames = int(getattr(
args, "videomae_v2_segment_num_frames", 16))
derived_source_num_frames = (
self.videomae_v2_skip_leading_frames
+ self.videomae_v2_encoder_count
* self.videomae_v2_segment_num_frames
)
self.videomae_v2_source_num_frames = int(getattr(
args,
"videomae_v2_source_num_frames",
derived_source_num_frames,
))
self.videomae_v2_dense_num_tokens = int(getattr(
args, "videomae_v2_dense_num_tokens", 128))
self.videomae_v2_dense_resize_short_side = int(getattr(
args, "videomae_v2_dense_resize_short_side", 224))
self.videomae_v2_dense_crop_size = int(getattr(
args, "videomae_v2_dense_crop_size", 224))
self.videomae_v2_dense_gradient_checkpointing = bool(getattr(
args, "videomae_v2_dense_gradient_checkpointing", True))
fixed_geometry = (
self.videomae_v2_encoder_count,
self.videomae_v2_skip_leading_frames,
self.videomae_v2_segment_num_frames,
self.videomae_v2_source_num_frames,
self.videomae_v2_dense_resize_short_side,
self.videomae_v2_dense_crop_size,
)
expected_geometry = (5, 1, 16, 81, 224, 224)
if fixed_geometry != expected_geometry:
raise ValueError(
"VideoMAE-v2 whole-video geometry is fixed to five physical "
"16-frame encoders over decoded frames [1:81]: "
f"actual={fixed_geometry}, expected={expected_geometry}")
if self.videomae_v2_dense_num_tokens <= 1:
raise ValueError(
"videomae_v2_dense_num_tokens must be > 1 per segment")
adapter_config = {
"name": "videomae_v2_five_segment_dense",
"model_id": self.videomae_v2_model_id,
"encoder_count": self.videomae_v2_encoder_count,
"share_encoder_weights": (
self.videomae_v2_share_encoder_weights),
"skip_leading_frames": self.videomae_v2_skip_leading_frames,
"segment_num_frames": self.videomae_v2_segment_num_frames,
"source_num_frames": self.videomae_v2_source_num_frames,
"input_frames": self.videomae_v2_segment_num_frames,
"dense_num_frames": self.videomae_v2_segment_num_frames,
"input_size": self.videomae_v2_dense_crop_size,
"resize_short_side": (
self.videomae_v2_dense_resize_short_side),
"crop_mode": "center",
"dense_only": True,
# ``15`` means the 16th block and captures its post-residual
# dense state, before pooling/fc_norm.
"dense_layer_index": self.videomae_v2_dense_layer,
"local_files_only": self.videomae_v2_local_files_only,
}
if self.videomae_v2_model_revision:
adapter_config["revision"] = self.videomae_v2_model_revision
self.videomae_v2_encoder = SegmentedVideoMAEv2Ensemble(
adapter_config)
self.videomae_v2_encoder.to(device=device, dtype=torch.float32)
self.videomae_v2_encoder.eval().requires_grad_(False)
actual_adapter_geometry = (
int(self.videomae_v2_encoder.dense_layer_index),
int(self.videomae_v2_encoder.dense_num_frames),
int(self.videomae_v2_encoder.resize_short_side),
int(self.videomae_v2_encoder.input_size),
int(self.videomae_v2_encoder.retained_dense_blocks),
int(self.videomae_v2_encoder.dense_raw_tokens),
int(self.videomae_v2_encoder.dense_feature_dim),
len(self.videomae_v2_encoder.encoders),
)
expected_adapter_geometry = (
self.videomae_v2_dense_layer,
16,
224,
224,
self.videomae_v2_dense_layer + 1,
1568,
1024,
1 if self.videomae_v2_share_encoder_weights else 5,
)
if actual_adapter_geometry != expected_adapter_geometry:
raise RuntimeError(
"loaded VideoMAE-v2 Large ensemble does not match the fixed "
"dense-prefix geometry: "
f"actual={actual_adapter_geometry}, "
f"expected={expected_adapter_geometry}")
configured_depths = {
int(getattr(encoder, "_configured_depth", -1))
for encoder in self.videomae_v2_encoder.encoders
}
if configured_depths != {24}:
raise RuntimeError(
"all five encoders must be VideoMAE-v2 Large with 24 blocks; "
f"got depths={sorted(configured_depths)}")
# Historical internal aliases. Public metadata, config, logs, and
# checkpoints are translated back to ``videomae_v2_*``.
self.dense_feature_segment_count = 5
self.vjepa2_model_id = self.videomae_v2_model_id
self.vjepa2_dense_layers = self.videomae_v2_dense_layers
self.vjepa2_multilayer_enabled = (
self.videomae_v2_multilayer_enabled)
self.vjepa2_dense_layer = self.videomae_v2_dense_layer
self.vjepa2_dense_num_frames = 80
self.vjepa2_dense_source_num_frames = 81
self.vjepa2_dense_frame_sampling = "center_contiguous"
self.vjepa2_dense_window_seed = "fixed-five-segment-videomae-v2"
self.vjepa2_dense_num_tokens = (
self.videomae_v2_dense_num_tokens)
self.vjepa2_dense_resize_short_side = (
self.videomae_v2_dense_resize_short_side)
self.vjepa2_dense_crop_size = self.videomae_v2_dense_crop_size
self.vjepa2_dense_gradient_checkpointing = (
self.videomae_v2_dense_gradient_checkpointing)
self.vjepa2_encoder = self.videomae_v2_encoder
self.vjepa2_dense_raw_tokens = int(
self.videomae_v2_encoder.dense_raw_tokens)
self.vjepa2_dense_feature_dim = int(
self.videomae_v2_encoder.dense_feature_dim)
if self.vjepa2_dense_num_tokens > self.vjepa2_dense_raw_tokens:
raise ValueError(
"videomae_v2_dense_num_tokens cannot exceed the native "
"per-segment token grid: "
f"{self.vjepa2_dense_num_tokens} > "
f"{self.vjepa2_dense_raw_tokens}")
def _initialize_dinov3_features(self, args, device) -> None:
"""Load the independent frozen DINOv3 dense-image backend.
The compatibility geometry consumes sixteen fixed frames and retains a
row-major 8x8 spatial patch subset from each frame. The optional
``temporal_mean5_full256`` geometry consumes twenty fixed frames,
averages every five consecutive frame-feature grids, and retains the
complete 16x16 patch grid for each of the four temporal groups. Both
geometries produce one aligned [1024, 1024] matrix per video; their
adapter metadata keeps references and checkpoints mutually exclusive.
"""
compatibility_frames = (
0, 5, 11, 16, 21, 27, 32, 37,
43, 48, 53, 59, 64, 69, 75, 80,
)
temporal_pool_frames = (
0, 4, 8, 13, 17, 21, 25, 29, 34, 38,
42, 46, 51, 55, 59, 63, 67, 72, 76, 80,
)
compatibility_spatial_axis = (0, 2, 4, 6, 9, 11, 13, 15)
full_spatial_axis = tuple(range(16))
initialization_error = None
try:
geometry = str(getattr(
args, "dinov3_dense_geometry", "f16x64")).strip()
if geometry == "f16x64":
from video_fd.encoders.dinov3_adapter import (
DINOv3DenseAdapter as Adapter,
)
canonical_frames = compatibility_frames
canonical_spatial_axis = compatibility_spatial_axis
elif geometry == "temporal_mean5_full256":
from video_fd.encoders.dinov3_temporal_pool_adapter import (
DINOv3TemporalPoolAdapter as Adapter,
)
canonical_frames = temporal_pool_frames
canonical_spatial_axis = full_spatial_axis
else:
raise ValueError(
"dinov3_dense_geometry must be 'f16x64' or "
"'temporal_mean5_full256', got "
f"{geometry!r}")
configured_frames = tuple(int(value) for value in getattr(
args, "dinov3_dense_frame_indices", canonical_frames))
configured_spatial_axis = tuple(int(value) for value in getattr(
args, "dinov3_dense_spatial_axis_indices",
canonical_spatial_axis))
adapter_config = {
"repo_path": str(getattr(args, "dinov3_repo_path", "")),
"weight_path": str(getattr(args, "dinov3_weight_path", "")),
"source_commit": str(getattr(
args, "dinov3_source_commit", "")),
"source_num_frames": int(getattr(
args, "dinov3_dense_source_num_frames", 81)),
"frame_indices": configured_frames,
"input_size": int(getattr(
args, "dinov3_dense_input_size", 256)),
"patch_size": int(getattr(
args, "dinov3_dense_patch_size", 16)),
"spatial_axis_indices": configured_spatial_axis,
"forward_chunk_frames": int(getattr(
args, "dinov3_dense_forward_chunk_frames", 4)),
}
if geometry == "temporal_mean5_full256":
adapter_config.update({
"geometry": "temporal_mean5_full256",
"temporal_groups": 4,
"temporal_pool_frames": 5,
})
configured_checkpoint_sha256 = str(getattr(
args, "dinov3_checkpoint_sha256", "")).strip()
if configured_checkpoint_sha256:
adapter_config["checkpoint_sha256"] = (
configured_checkpoint_sha256)
self.dinov3_encoder = Adapter(adapter_config)
self.dinov3_encoder.to(device=device, dtype=torch.float32)
self.dinov3_encoder.eval().requires_grad_(False)
self.dinov3_dense_geometry = geometry
self.dinov3_model_id = str(self.dinov3_encoder.model_id)
self.dinov3_repo_path = str(self.dinov3_encoder.repo_path)
self.dinov3_weight_path = str(self.dinov3_encoder.weight_path)
self.dinov3_source_commit = str(
self.dinov3_encoder.source_commit)
self.dinov3_dense_source_num_frames = int(
self.dinov3_encoder.source_num_frames)
self.dinov3_dense_frame_indices = tuple(
int(value) for value in self.dinov3_encoder.frame_indices)
self.dinov3_dense_num_frames = int(
self.dinov3_encoder.dense_num_frames)
self.dinov3_dense_input_size = int(
self.dinov3_encoder.input_size)
self.dinov3_dense_patch_size = int(
self.dinov3_encoder.patch_size)
self.dinov3_dense_spatial_axis_indices = tuple(
int(value) for value in
self.dinov3_encoder.spatial_axis_indices)
self.dinov3_dense_forward_chunk_frames = int(
self.dinov3_encoder.forward_chunk_frames)
self.dinov3_dense_raw_tokens = int(
self.dinov3_encoder.dense_raw_tokens)
self.dinov3_dense_num_tokens = int(
self.dinov3_encoder.dense_num_tokens)
self.dinov3_dense_feature_dim = int(
self.dinov3_encoder.dense_feature_dim)
self.dinov3_dense_gradient_checkpointing = bool(getattr(
args, "dinov3_dense_gradient_checkpointing", False))
if geometry == "temporal_mean5_full256":
self.dinov3_dense_temporal_groups = int(
self.dinov3_encoder.temporal_groups)
self.dinov3_dense_temporal_pool_size = int(
self.dinov3_encoder.temporal_pool_frames)
self.dinov3_dense_tokens_per_group = int(
self.dinov3_encoder.per_frame_tokens)
actual_contract = {
"model_id": self.dinov3_model_id,
"source_num_frames": self.dinov3_dense_source_num_frames,
"frame_indices": self.dinov3_dense_frame_indices,
"num_frames": self.dinov3_dense_num_frames,
"input_size": self.dinov3_dense_input_size,
"patch_size": self.dinov3_dense_patch_size,
"spatial_axis_indices": (
self.dinov3_dense_spatial_axis_indices),
"forward_chunk_frames": (
self.dinov3_dense_forward_chunk_frames),
"raw_tokens": self.dinov3_dense_raw_tokens,
"num_tokens": self.dinov3_dense_num_tokens,
"feature_dim": self.dinov3_dense_feature_dim,
}
if geometry == "temporal_mean5_full256":
actual_contract.update({
"geometry": str(self.dinov3_encoder.geometry),
"temporal_groups": (
self.dinov3_dense_temporal_groups),
"temporal_pool_size": (
self.dinov3_dense_temporal_pool_size),
"tokens_per_group": (
self.dinov3_dense_tokens_per_group),
})
expected_contract = {
"model_id": "dinov3_vitl16",
"source_num_frames": 81,
"frame_indices": canonical_frames,
"num_frames": 20,
"input_size": 256,
"patch_size": 16,
"spatial_axis_indices": canonical_spatial_axis,
"forward_chunk_frames": 4,
"raw_tokens": 5120,
"num_tokens": 1024,
"feature_dim": 1024,
"geometry": "temporal_mean5_full256",
"temporal_groups": 4,
"temporal_pool_size": 5,
"tokens_per_group": 256,
}
else:
expected_contract = {
"model_id": "dinov3_vitl16",
"source_num_frames": 81,
"frame_indices": canonical_frames,
"num_frames": 16,
"input_size": 256,
"patch_size": 16,
"spatial_axis_indices": canonical_spatial_axis,
"forward_chunk_frames": 4,
"raw_tokens": 4096,
"num_tokens": 1024,
"feature_dim": 1024,
}
if actual_contract != expected_contract:
raise ValueError(
"loaded DINOv3 adapter does not satisfy the public dense "
f"feature contract: actual={actual_contract}, "
f"expected={expected_contract}")
except BaseException as exc:
initialization_error = exc
self._synchronize_dinov3_local_failure(
initialization_error,
device,
operation="DINOv3 adapter initialization failed",
)
def _dinov3_feature_metadata(self) -> dict:
metadata = self.dinov3_encoder.feature_metadata()
if not isinstance(metadata, Mapping):
raise TypeError("DINOv3 feature_metadata() must return a mapping")
metadata = dict(metadata)
required_identity = {
"feature_type": "dinov3_dense_latent",
"model_id": self.dinov3_model_id,
"raw_tokens": self.dinov3_dense_raw_tokens,
"num_tokens": self.dinov3_dense_num_tokens,
"feature_dim": self.dinov3_dense_feature_dim,
"matrix_shape": [
self.dinov3_dense_num_tokens,
self.dinov3_dense_feature_dim,
],
}
mismatched = {
key: {"saved": metadata.get(key), "runtime": value}
for key, value in required_identity.items()
if metadata.get(key) != value
}
if mismatched:
raise ValueError(
"DINOv3 adapter metadata violates the runtime feature "
f"contract: {mismatched}")
# The frozen bank may record its original asset locations. Use those
# strings only as metadata identities; encoder I/O uses relocated paths.
reference_paths = getattr(self, "dinov3_reference_paths", {})
if reference_paths:
for key in ("repo_path", "weight_path"):
metadata[key] = reference_paths[key]
metadata.pop("feature_contract_sha256", None)
payload = json.dumps(
metadata, sort_keys=True, separators=(",", ":"),
ensure_ascii=True, allow_nan=False).encode("utf-8")
metadata["feature_contract_sha256"] = hashlib.sha256(payload).hexdigest()
return metadata
def _dinov3_descriptor_frame_indices(
self,
replay_descriptor: Mapping,
*,
device: torch.device,
) -> torch.Tensor:
saved = replay_descriptor.get("dinov3_frame_indices")
if not isinstance(saved, torch.Tensor):
raise TypeError("DINOv3 replay frame indices must be a tensor")
saved = saved.to(device=device, dtype=torch.long)
expected = torch.tensor(
self.dinov3_dense_frame_indices,
device=device,
dtype=torch.long,
)
if saved.ndim != 1 or not torch.equal(saved, expected):
raise ValueError(
"DINOv3 replay frame indices changed from the fixed public "
"sampling contract")
return saved
def _extract_dinov3_dense(self, video01: torch.Tensor) -> torch.Tensor:
if (
video01.ndim != 5
or int(video01.shape[1])
!= self.dinov3_dense_source_num_frames
or int(video01.shape[2]) != 3
):
raise ValueError(
"DINOv3 dense extraction requires full decoded videos with "
f"shape [B,{self.dinov3_dense_source_num_frames},3,H,W], "
f"got {tuple(video01.shape)}")
extract = (
self.dinov3_encoder.forward_dense_no_grad
if not torch.is_grad_enabled()
else self.dinov3_encoder.forward_dense
)
features = extract(
video01,
gradient_checkpointing=(
self.dinov3_dense_gradient_checkpointing),
)
expected_shape = (
int(video01.shape[0]),
self.dinov3_dense_num_tokens,
self.dinov3_dense_feature_dim,
)
if features.ndim != 3 or tuple(features.shape) != expected_shape:
raise ValueError(
"frozen DINOv3 returned an invalid dense feature matrix: "
f"got {tuple(features.shape)}, expected {expected_shape}")
return features
def _replay_dinov3_dense_to_pixels(
self,
video01: torch.Tensor,
*,
expected_features: torch.Tensor,
feature_cotangent: torch.Tensor,
replay_atol: float,
replay_rtol: float,
) -> Tuple[torch.Tensor, torch.Tensor]:
replay_features, video_cotangent = (
self.dinov3_encoder.replay_dense_vjp(
video01.detach().float(),
feature_cotangent.detach().float(),
expected_features=expected_features.detach().float(),
gradient_checkpointing=(
self.dinov3_dense_gradient_checkpointing),
replay_atol=float(replay_atol),
replay_rtol=float(replay_rtol),
)
)
expected_feature_shape = tuple(expected_features.shape)
if tuple(replay_features.shape) != expected_feature_shape:
raise RuntimeError(
"DINOv3 feature replay changed matrix shape: "
f"{tuple(replay_features.shape)} != "
f"{expected_feature_shape}")
if tuple(video_cotangent.shape) != tuple(video01.shape):
raise RuntimeError(
"DINOv3 replay returned an invalid full-video pixel "
f"cotangent: {tuple(video_cotangent.shape)} != "
f"{tuple(video01.shape)}")
if not bool(torch.isfinite(video_cotangent).all().item()):
raise FloatingPointError(
"DINOv3 replay returned a non-finite pixel cotangent")
replay_max_abs = (
replay_features.detach().float()
- expected_features.detach().float()
).abs().max()
return video_cotangent.detach().float(), replay_max_abs.detach()
def _dense_metric_prefix(self) -> str:
return (
"dinov3_dense"
if self._uses_dinov3_dense_backend()
else "vjepa2_dense"
)
def _uses_dinov3_dense_backend(self) -> bool:
"""Support legacy/test instances created without the new init flags."""
return bool(getattr(
self,
"is_dinov3_dense",
getattr(self, "feature_type", None) == "dinov3_dense_latent",
))
def _token_indices(self, latent: torch.Tensor) -> torch.Tensor:
patch = self.latent_patch_size
tokens = (
(latent.shape[1] // int(patch[0]))
* (latent.shape[3] // int(patch[1]))
* (latent.shape[4] // int(patch[2]))
)
n = min(tokens, self.latent_num_tokens)
return torch.linspace(
0, tokens - 1, steps=n, device=latent.device).round().long()
def _extract(self, latent, conditional_dict, token_indices):
timestep = latent.new_full(
(latent.shape[0], latent.shape[1]),
self.latent_timestep,
dtype=torch.float32,
)
features = self.real_score(
noisy_image_or_video=latent,
conditional_dict=conditional_dict,
timestep=timestep,
return_latent_features=True,
latent_feature_layer=self.latent_layer,
latent_token_indices=token_indices,
)
expected_shape = (
latent.shape[0], token_indices.numel(), self.latent_feature_dim)
if features.ndim != 3 or tuple(features.shape) != expected_shape:
raise ValueError(
"frozen Wan returned an invalid post-block latent shape: "
f"got {tuple(features.shape)}, expected {expected_shape}")
return features
def _vjepa2_token_indices(self, device: torch.device) -> torch.Tensor:
return uniform_dense_token_indices(
self.vjepa2_dense_raw_tokens,
self.vjepa2_dense_num_tokens,
device=device,
)
def _vjepa2_feature_metadata(
self,
token_indices: Optional[torch.Tensor] = None,
*,
layer_index: Optional[int] = None,
) -> dict:
resolved_layer = (
(
self.motionformer_dense_layer
if self._dense_encoder_kind() == "motionformer"
else self.vjepa2_dense_layer
)
if layer_index is None
else int(layer_index)
)
if self._dense_encoder_kind() == "motionformer":
if resolved_layer != self.motionformer_dense_layer:
raise ValueError(
"requested feature metadata for an inactive MotionFormer "
f"layer: {resolved_layer}")
from video_fd.encoders.motionformer_dense_metadata import (
canonical_motionformer_dense_feature_metadata,
)
return canonical_motionformer_dense_feature_metadata(
checkpoint_path=self.motionformer_checkpoint_path,
checkpoint_sha256=self.motionformer_checkpoint_sha256,
layer_index=self.motionformer_dense_layer,
num_frames=self.motionformer_dense_num_frames,
raw_tokens=self.motionformer_dense_raw_tokens,
num_tokens=self.motionformer_dense_num_tokens,
feature_dim=self.motionformer_dense_feature_dim,
token_indices=token_indices,
)
if resolved_layer not in getattr(
self, "vjepa2_dense_layers", (self.vjepa2_dense_layer,)
):
raise ValueError(
"requested feature metadata for an inactive V-JEPA2 layer: "
f"{resolved_layer}")
if (
token_indices is None
and self.dense_state_prefix in {
"dual", "triple", "dinov3_vjepa2"
}
and getattr(
self,
"vjepa2_reference_token_contract",
"explicit_uniform_v2",
) != "legacy_uniform_implicit_v1"
):
# Multi-encoder Wan banks serialize the exact uniform subset so
# the reference and replay contracts attest row order explicitly.
token_indices = uniform_dense_token_indices(
self.vjepa2_dense_raw_tokens,
self.vjepa2_dense_num_tokens,
)
metadata_kwargs = {
"model_id": getattr(
self, "vjepa2_reference_model_id", self.vjepa2_model_id),
"layer_index": resolved_layer,
"num_frames": self.vjepa2_dense_num_frames,
"resize_short_side": self.vjepa2_dense_resize_short_side,
"crop_size": self.vjepa2_dense_crop_size,
"raw_tokens": self.vjepa2_dense_raw_tokens,
"num_tokens": self.vjepa2_dense_num_tokens,
"feature_dim": self.vjepa2_dense_feature_dim,
"token_indices": token_indices,
}
default_reference_sampling = getattr(
self,
"vjepa2_dense_frame_sampling",
"center_contiguous",
)
if (
not hasattr(self, "vjepa2_reference_frame_sampling")
and self.dense_state_prefix in {
"dual", "triple", "dinov3_vjepa2"
}
):
# Preserve pre-existing checkpoint/test fixtures that predate the
# explicit reference/student split: multi-encoder references were
# last64 unless an initialized model now says otherwise.
default_reference_sampling = "last_contiguous"
frame_sampling = getattr(
self,
"vjepa2_reference_frame_sampling",
default_reference_sampling,
)
if frame_sampling == "last_contiguous":
metadata_kwargs.update({
"frame_sampling": frame_sampling,
"source_num_frames": self.vjepa2_dense_source_num_frames,
})
elif frame_sampling == "random_contiguous_per_video":
metadata_kwargs.update({
"frame_sampling": frame_sampling,
"source_num_frames": self.vjepa2_dense_source_num_frames,
"window_seed": self.vjepa2_dense_window_seed,
})
return canonical_vjepa2_dense_feature_metadata(**metadata_kwargs)
def _dense_feature_metadata(
self,
token_indices: Optional[torch.Tensor] = None,
*,
layer_index: Optional[int] = None,
) -> dict:
"""Encoder-neutral alias for strict dense feature identity."""
return self._vjepa2_feature_metadata(
token_indices, layer_index=layer_index)
def _vjepa2_temporal_window_indices(
self,
sample_keys,
*,
batch_size: int,
device: torch.device,
) -> Optional[torch.Tensor]:
sampling = getattr(
self,
"vjepa2_student_frame_sampling",
getattr(self, "vjepa2_dense_frame_sampling", "center_contiguous"),
)
if sampling == "center_contiguous":
if sample_keys is not None:
raise ValueError(
"window sample keys are invalid for center sampling")
return None
if sampling == "last_contiguous":
if sample_keys is not None:
raise ValueError(
"window sample keys are invalid for last sampling")
start = (
int(self.vjepa2_student_source_num_frames)
- int(self.vjepa2_dense_num_frames)
)
offsets = torch.arange(
self.vjepa2_dense_num_frames,
device=device,
dtype=torch.long,
)
return (offsets + start).unsqueeze(0).expand(
int(batch_size), -1).clone()
if sample_keys is None:
raise ValueError(
"random V-JEPA2 windows require one sample key per video")
if isinstance(sample_keys, torch.Tensor):
if sample_keys.ndim != 1:
raise ValueError("window sample keys must have shape [B]")
keys = sample_keys.detach().cpu().tolist()
else:
keys = list(sample_keys)
if len(keys) != int(batch_size):
raise ValueError(
"window sample key count does not match the video batch: "
f"{len(keys)} != {int(batch_size)}")
starts = [
stateless_temporal_window_start(
self.vjepa2_dense_window_seed,
"student",
int(key),
source_num_frames=getattr(
self, "vjepa2_student_source_num_frames",
self.vjepa2_dense_source_num_frames),
window_num_frames=self.vjepa2_dense_num_frames,
)
for key in keys
]
start_tensor = torch.tensor(
starts, device=device, dtype=torch.long)
offsets = torch.arange(
self.vjepa2_dense_num_frames,
device=device,
dtype=torch.long,
)
return start_tensor[:, None] + offsets[None, :]
def _vjepa2_descriptor_window_indices(
self,
replay_descriptor: dict,
*,
device: torch.device,
) -> Optional[torch.Tensor]:
if getattr(
self,
"vjepa2_student_frame_sampling",
getattr(self, "vjepa2_dense_frame_sampling", "center_contiguous"),
) == "center_contiguous":
return None
return replay_descriptor["vjepa2_frame_indices"].to(
device=device, dtype=torch.long)
def _extract_vjepa2_dense(
self,
video01: torch.Tensor,
token_indices: torch.Tensor,
*,
gradient_checkpointing: bool,
temporal_window_indices: Optional[torch.Tensor] = None,
) -> torch.Tensor:
if self._dense_encoder_kind() == "motionformer":
if temporal_window_indices is not None:
raise ValueError(
"MotionFormer performs fixed segment-midpoint sampling "
"and does not accept V-JEPA2 temporal windows")
features = self.motionformer_encoder.forward_dense(
video01,
layer_index=self.motionformer_dense_layer,
token_indices=token_indices,
gradient_checkpointing=gradient_checkpointing,
)
expected_shape = (
video01.shape[0],
token_indices.numel(),
self.motionformer_dense_feature_dim,
)
if features.ndim != 3 or tuple(features.shape) != expected_shape:
raise ValueError(
"frozen MotionFormer returned an invalid intermediate "
f"dense shape: got {tuple(features.shape)}, expected "
f"{expected_shape}")
return features
dense_layers = getattr(
self, "vjepa2_dense_layers", (self.vjepa2_dense_layer,))
if len(dense_layers) == 1:
features_by_layer = {
dense_layers[0]: self.vjepa2_encoder.forward_dense(
video01,
layer_index=dense_layers[0],
token_indices=token_indices,
gradient_checkpointing=gradient_checkpointing,
temporal_window_indices=temporal_window_indices,
)
}
else:
features_by_layer = self.vjepa2_encoder.forward_dense_layers(
video01,
layer_indices=dense_layers,
token_indices=token_indices,
gradient_checkpointing=gradient_checkpointing,
temporal_window_indices=temporal_window_indices,
)
expected_shape = (
video01.shape[0],
token_indices.numel(),
self.vjepa2_dense_feature_dim,
)
ordered_features = []
for layer in dense_layers:
features = features_by_layer[layer]
if (
features.ndim != 3
or tuple(features.shape) != expected_shape
):
raise ValueError(
"frozen V-JEPA2 returned an invalid intermediate dense "
f"shape at layer {layer}: got {tuple(features.shape)}, "
f"expected {expected_shape}")
ordered_features.append(features)
# The GradCache transports one tensor. The loss module splits this
# layer-major concatenation and evaluates independent kernels.
return (
ordered_features[0]
if len(ordered_features) == 1
else torch.cat(ordered_features, dim=1)
)
def _replay_dense_encoder_vjp(
self,
video01: torch.Tensor,
token_indices: torch.Tensor,
expected_features: torch.Tensor,
feature_cotangent: torch.Tensor,
*,
gradient_checkpointing: bool,
temporal_window_indices: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Replay frozen V-JEPA2 and return its features and pixel VJP."""
if expected_features.shape != feature_cotangent.shape:
raise ValueError(
"dense encoder replay feature/cotangent shapes differ: "
f"{tuple(expected_features.shape)} != "
f"{tuple(feature_cotangent.shape)}")
student_video_leaf = video01.detach().float().requires_grad_(True)
replay_kwargs = {
"gradient_checkpointing": gradient_checkpointing,
}
if temporal_window_indices is not None:
replay_kwargs["temporal_window_indices"] = temporal_window_indices
replay_features = self._extract_vjepa2_dense(
student_video_leaf, token_indices, **replay_kwargs).float()
encoder_surrogate = (replay_features * feature_cotangent).sum()
(video_cotangent,) = torch.autograd.grad(
encoder_surrogate, student_video_leaf,
retain_graph=False, create_graph=False)
replay_features = replay_features.detach().float()
video_cotangent = video_cotangent.detach().float()
del encoder_surrogate, student_video_leaf
return replay_features, video_cotangent
def _decode_video01(self, latent: torch.Tensor) -> torch.Tensor:
pixels = self.vae.decode_to_pixel(latent.detach())
if pixels.ndim != 5 or pixels.shape[2] != 3:
raise ValueError(
"Wan VAE returned an invalid video shape: expected "
f"[B,T,3,H,W], got {tuple(pixels.shape)}")
if (
self.is_triple_dense
or getattr(self, "is_dinov3_vjepa2_dense", False)
or self._uses_dinov3_dense_backend()
):
if int(pixels.shape[1]) != 81:
raise ValueError(
"DINOv3/triple dense features require exactly 81 "
f"decoded Wan frames; got {int(pixels.shape[1])}")
elif self.dense_state_prefix == "videomae_v2":
if int(pixels.shape[1]) != 81:
raise ValueError(
"segmented VideoMAE-v2 requires exactly 81 decoded "
f"frames; got {int(pixels.shape[1])}")
else:
if pixels.shape[1] < self.vjepa2_dense_num_frames:
raise ValueError(
"decoded video is too short for the dense-video clip")
student_sampling = getattr(
self, "vjepa2_student_frame_sampling",
getattr(self, "vjepa2_dense_frame_sampling", "center_contiguous"))
if (
student_sampling in {"random_contiguous_per_video", "last_contiguous"}
and int(pixels.shape[1]) != self.vjepa2_student_source_num_frames
):
raise ValueError(
f"{student_sampling} V-JEPA2 sampling requires "
f"{self.vjepa2_student_source_num_frames} frames")
return ((pixels + 1.0) * 0.5).clamp(0.0, 1.0)
def _capture_generation_rng(self) -> dict:
return {
"cpu": torch.get_rng_state().clone(),
"cuda": torch.cuda.get_rng_state(self.device).clone(),
"numpy": np.random.get_state(),
"python": random.getstate(),
}
@contextmanager
def _replay_generation_rng(self, rng_state: dict):
if set(rng_state) != {"cpu", "cuda", "numpy", "python"}:
raise ValueError(
"invalid fresh-video replay RNG descriptor")
# fork_rng restores the ambient stream afterwards. Consequently the
# second differentiable pass does not consume new training randomness.
ambient_numpy = np.random.get_state()
ambient_python = random.getstate()
try:
with torch.random.fork_rng(devices=[self.device], enabled=True):
torch.set_rng_state(rng_state["cpu"])
torch.cuda.set_rng_state(rng_state["cuda"], self.device)
np.random.set_state(rng_state["numpy"])
random.setstate(rng_state["python"])
yield
finally:
np.random.set_state(ambient_numpy)
random.setstate(ambient_python)
def _generate_student_latent(
self,
*,
image_or_video_shape,
conditional_dict: dict,
unconditional_dict: dict,
initial_latent: Optional[torch.Tensor] = None,
generation_descriptor: Optional[dict] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
if self.causal_generator:
pred, gradient_mask, _, _ = self._run_generator(
image_or_video_shape=image_or_video_shape,
conditional_dict=dict(conditional_dict),
initial_latent=initial_latent,
generation_descriptor=generation_descriptor,
)
return pred, gradient_mask
if initial_latent is not None:
raise NotImplementedError(
"fresh V-JEPA2 GradCache currently supports T2V only")
pred = self._run_few_step_generator(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
)
return pred, None
def _validate_current_teacher_feature_tensor(
self,
features: torch.Tensor,
*,
student_latent: torch.Tensor,
token_indices: torch.Tensor,
source: str,
) -> torch.Tensor:
"""Return one frozen FP32 teacher matrix with exact student geometry."""
if not isinstance(features, torch.Tensor):
raise TypeError(f"{source} must be a torch.Tensor")
if not features.is_floating_point():
raise TypeError(f"{source} must be floating point")
expected_shape = (
int(student_latent.shape[0]),
int(token_indices.numel()),
int(self._dense_attr("feature_dim")),
)
if features.ndim != 3 or tuple(features.shape) != expected_shape:
raise ValueError(
f"{source} must have exact [B,N,D] shape "
f"{expected_shape}, got {tuple(features.shape)}")
if features.device != student_latent.device:
raise ValueError(
f"{source} and student latent must share a device")
frozen = features.detach()
if not bool(torch.isfinite(frozen).all().item()):
raise FloatingPointError(f"{source} contains non-finite values")
return frozen.float()
def _current_teacher_features_for_fresh_video(
self,
*,
student_latent: torch.Tensor,
token_indices: torch.Tensor,
extract_kwargs: Mapping[str, object],
current_teacher_features: Optional[torch.Tensor],
current_teacher_video01: Optional[torch.Tensor],
current_teacher_latent: Optional[torch.Tensor],
) -> Optional[torch.Tensor]:
"""Resolve the mutually exclusive matched-teacher input contract."""
candidates = {
"current_teacher_features": current_teacher_features,
"current_teacher_video01": current_teacher_video01,
"current_teacher_latent": current_teacher_latent,
}
supplied = [
name for name, value in candidates.items() if value is not None
]
if not getattr(self, "current_teacher_attraction_enabled", False):
if supplied:
raise ValueError(
f"{', '.join(supplied)} provided while exact "
"current-teacher attraction is disabled")
return None
if len(supplied) != 1:
raise ValueError(
"exactly one of current_teacher_features, "
"current_teacher_video01, or current_teacher_latent must be "
f"provided; got {supplied}")
source = supplied[0]
del candidates
if source == "current_teacher_features":
return self._validate_current_teacher_feature_tensor(
current_teacher_features,
student_latent=student_latent,
token_indices=token_indices,
source=source,
)
if source == "current_teacher_video01":
teacher_video01 = current_teacher_video01
if not isinstance(teacher_video01, torch.Tensor):
raise TypeError(
"current_teacher_video01 must be a torch.Tensor")
if not teacher_video01.is_floating_point():
raise TypeError(
"current_teacher_video01 must be floating point")
if (
teacher_video01.ndim != 5
or int(teacher_video01.shape[0])
!= int(student_latent.shape[0])
or int(teacher_video01.shape[2]) != 3
or int(teacher_video01.shape[1])
< int(self._dense_attr("num_frames"))
or int(teacher_video01.shape[3]) <= 0
or int(teacher_video01.shape[4]) <= 0
):
raise ValueError(
"current_teacher_video01 must have shape "
f"[B,T>={int(self._dense_attr('num_frames'))},3,H,W] "
"with the student batch size; got "
f"{tuple(teacher_video01.shape)}")
student_sampling = getattr(
self,
"vjepa2_student_frame_sampling",
getattr(
self, "vjepa2_dense_frame_sampling", "center_contiguous"),
)
if (
student_sampling == "last_contiguous"
and int(teacher_video01.shape[1]) not in {
int(self.vjepa2_dense_num_frames),
int(self.vjepa2_student_source_num_frames),
}
):
raise ValueError(
"last_contiguous teacher video must be either the exact "
"64-frame contract clip or its complete 81-frame source")
if teacher_video01.device != student_latent.device:
raise ValueError(
"current_teacher_video01 and student latent must share "
"a device")
frozen_video01 = teacher_video01.detach()
if not bool(torch.isfinite(frozen_video01).all().item()):
raise FloatingPointError(
"current_teacher_video01 contains non-finite values")
if (
float(frozen_video01.min().item()) < 0.0
or float(frozen_video01.max().item()) > 1.0
):
raise ValueError(
"current_teacher_video01 must be normalized to [0,1]")
extracted = self._extract_vjepa2_dense(
frozen_video01,
token_indices,
**extract_kwargs,
)
del current_teacher_video01, frozen_video01, teacher_video01
else:
teacher_latent = current_teacher_latent
if not isinstance(teacher_latent, torch.Tensor):
raise TypeError(
"current_teacher_latent must be a torch.Tensor")
if not teacher_latent.is_floating_point():
raise TypeError(
"current_teacher_latent must be floating point")
if tuple(teacher_latent.shape) != tuple(student_latent.shape):
raise ValueError(
"current teacher/student latent shapes must match: "
f"{tuple(teacher_latent.shape)} != "
f"{tuple(student_latent.shape)}")
if teacher_latent.device != student_latent.device:
raise ValueError(
"current teacher/student latents must share a device")
frozen_latent = teacher_latent.detach()
if not bool(torch.isfinite(frozen_latent).all().item()):
raise FloatingPointError(
"current teacher latent contains non-finite values")
teacher_video01 = self._decode_video01(frozen_latent)
extracted = self._extract_vjepa2_dense(
teacher_video01,
token_indices,
**extract_kwargs,
)
del current_teacher_latent, teacher_latent, frozen_latent, teacher_video01
return self._validate_current_teacher_feature_tensor(
extracted,
student_latent=student_latent,
token_indices=token_indices,
source=f"V-JEPA2 output for {source}",
)
@property
def dual_video_mmd_enabled(self) -> bool:
"""Compatibility name for heterogeneous multi-encoder MMD."""
return getattr(self, "feature_type", None) in {
"dual_vjepa2_videomae_v2_dense_latent",
"dual_dinov3_vjepa2_dense_latent",
"triple_dinov3_vjepa2_videomae_v2_dense_latent",
}
def _dual_token_indices(
self,
device: torch.device,
) -> dict[str, torch.Tensor]:
indices = {
"vjepa2": uniform_dense_token_indices(
self.vjepa2_dense_raw_tokens, 1024, device=device),
}
if "dinov3" in self.dual_branch_registry:
indices["dinov3"] = torch.tensor(
self.dinov3_dense_frame_indices,
device=device,
dtype=torch.long,
)
if "videomae_v2" in self.dual_branch_registry:
from video_fd.encoders.videomae_v2_dense_metadata import (
uniform_segment_token_indices,
)
indices["videomae_v2"] = uniform_segment_token_indices(
self.videomae_v2_encoder.dense_raw_tokens,
256,
device=device,
)
return indices
def _validate_dual_feature_mapping(
self,
features: Mapping[str, torch.Tensor],
*,
batch_size: int,
device: torch.device,
label: str,
) -> dict[str, torch.Tensor]:
expected_keys = tuple(self.dual_branch_registry)
if not isinstance(features, Mapping) or set(features) != set(expected_keys):
raise ValueError(
f"{label} must contain exactly branches {expected_keys}")
result = {}
for name in expected_keys:
tensor = features[name]
expected_shape = (
batch_size,
*self.dual_branch_registry[name]["sample_shape"],
)
if (
not isinstance(tensor, torch.Tensor)
or not tensor.is_floating_point()
or tuple(tensor.shape) != expected_shape
or tensor.device != device
):
raise ValueError(
f"{label}[{name!r}] must be floating {expected_shape} "
f"on {device}; got {getattr(tensor, 'shape', None)}")
frozen = tensor.detach().float()
if not bool(torch.isfinite(frozen).all().item()):
raise FloatingPointError(f"{label}[{name!r}] is non-finite")
result[name] = frozen
return result
def _extract_multi_encoder_features(
self,
video01: torch.Tensor,
token_indices: Mapping[str, torch.Tensor],
*,
gradient_checkpointing: bool,
) -> dict[str, torch.Tensor]:
if int(video01.shape[1]) != 81:
raise ValueError(
"multi-encoder video feature extraction requires 81 frames")
temporal_indices = torch.arange(
17, 81, device=video01.device, dtype=torch.long
).unsqueeze(0).expand(int(video01.shape[0]), -1)
features = {}
if "dinov3" in self.dual_branch_registry:
features["dinov3"] = self._extract_dinov3_dense(video01)
features["vjepa2"] = self._extract_vjepa2_dense(
video01,
token_indices["vjepa2"],
gradient_checkpointing=gradient_checkpointing,
temporal_window_indices=temporal_indices,
)
if "videomae_v2" in self.dual_branch_registry:
features["videomae_v2"] = (
self.videomae_v2_encoder.forward_dense(
video01,
layer_index=15,
token_indices=token_indices["videomae_v2"],
gradient_checkpointing=gradient_checkpointing,
)
)
return self._validate_dual_feature_mapping(
features,
batch_size=int(video01.shape[0]),
device=video01.device,
label="multi-encoder output",
)
@torch.no_grad()
def _collect_multi_encoder_rollout_features(
self,
*,
image_or_video_shape,
conditional_dict: dict,
unconditional_dict: dict,
initial_latent: Optional[torch.Tensor],
current_teacher_features: Optional[Mapping[str, torch.Tensor]],
current_teacher_video01: Optional[torch.Tensor],
current_teacher_latent: Optional[torch.Tensor],
require_current_teacher: bool,
) -> Tuple[Mapping[str, torch.Tensor], dict]:
if current_teacher_video01 is not None or current_teacher_latent is not None:
raise ValueError(
"dual training reads frozen teacher features from the bank; "
"online teacher video/latent decoding is forbidden")
if require_current_teacher != (current_teacher_features is not None):
raise ValueError(
"selected dual suffix rows require exactly one bank feature mapping")
if not self.fresh_video_prepared_replay_enabled:
raise ValueError(
"dual video MMD requires prepared replay so both encoder VJPs "
"share one decoded pixel tensor and one VAE VJP")
generation_descriptor = self._sample_generator_input_descriptor(
image_or_video_shape, initial_latent=initial_latent)
saved_generation_noise = generation_descriptor["noise"].detach().clone()
rng_state = self._capture_generation_rng()
student_latent, _ = self._generate_student_latent(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
initial_latent=initial_latent,
generation_descriptor=generation_descriptor,
)
token_indices = self._dual_token_indices(student_latent.device)
teacher = None
if require_current_teacher:
teacher = self._validate_dual_feature_mapping(
current_teacher_features,
batch_size=int(student_latent.shape[0]),
device=student_latent.device,
label="dual teacher bank features",
)
student_video01 = self._decode_video01(student_latent)
if int(student_video01.shape[1]) != 81:
raise ValueError("dual student decode must produce exactly 81 frames")
features = self._extract_multi_encoder_features(
student_video01,
token_indices,
gradient_checkpointing=False,
)
descriptor = {
"rng_state": rng_state,
"latent_shape": tuple(int(value) for value in student_latent.shape),
"generation_descriptor": {
"version": int(generation_descriptor["version"]),
"num_generated_blocks": int(
generation_descriptor["num_generated_blocks"]),
"noise": saved_generation_noise,
**({
"trajectory_seeds": generation_descriptor[
"trajectory_seeds"].detach().clone(),
} if "trajectory_seeds" in generation_descriptor else {}),
},
"student_latent": student_latent.detach().clone(),
}
if teacher is not None:
descriptor["current_teacher_features"] = teacher
cached_video01 = student_video01.detach()
if self.fresh_video_pixel_cache_device == "cpu":
cached_video01 = cached_video01.to(
device="cpu", dtype=torch.float32, copy=True)
descriptor["cached_student_video01"] = cached_video01
return features, descriptor
def _prepare_multi_encoder_latent_gradients(
self,
*,
replay_descriptor: dict,
expected_features: Mapping[str, torch.Tensor],
feature_cotangent: Mapping[str, torch.Tensor],
replay_atol: float,
replay_rtol: float,
) -> dict:
required = {
"rng_state",
"latent_shape",
"generation_descriptor",
"student_latent",
"cached_student_video01",
}
if not isinstance(replay_descriptor, dict) or set(replay_descriptor) != required:
raise ValueError("invalid cached triple-video replay descriptor")
student_latent = replay_descriptor["student_latent"]
cached = replay_descriptor.pop("cached_student_video01")
student_video01 = cached.to(
device=student_latent.device,
dtype=torch.float32,
non_blocking=bool(cached.is_pinned()),
)
batch_size = int(student_latent.shape[0])
# The finalized global GradCache is intentionally offloaded before
# encoder/VAE replay. Stage only this sample's cached features and
# cotangents back to the active rank; the strict validator below still
# enforces shape, dtype, finiteness, and the destination device.
def _stage_replay_mapping(
mapping: Mapping[str, torch.Tensor],
) -> Mapping[str, torch.Tensor]:
if not isinstance(mapping, Mapping):
return mapping
return {
name: (
value.to(
device=student_latent.device,
non_blocking=bool(value.is_pinned()),
)
if isinstance(value, torch.Tensor)
else value
)
for name, value in mapping.items()
}
expected_features = _stage_replay_mapping(expected_features)
feature_cotangent = _stage_replay_mapping(feature_cotangent)
expected = self._validate_dual_feature_mapping(
expected_features,
batch_size=batch_size,
device=student_latent.device,
label="cached triple student features",
)
cotangent = self._validate_dual_feature_mapping(
feature_cotangent,
batch_size=batch_size,
device=student_latent.device,
label="triple feature cotangent",
)
tokens = self._dual_token_indices(student_latent.device)
temporal_indices = torch.arange(
17, 81, device=student_latent.device, dtype=torch.long
).unsqueeze(0).expand(batch_size, -1)
combined_pixel = None
pixel_shape = None
pixel_norms = {}
replay_maxima = {}
if "dinov3" in self.dual_branch_registry:
with torch.enable_grad():
pixel_dino, dino_max_abs = self._replay_dinov3_dense_to_pixels(
student_video01,
expected_features=expected["dinov3"],
feature_cotangent=cotangent["dinov3"],
replay_atol=replay_atol,
replay_rtol=replay_rtol,
)
combined_pixel, pixel_shape, pixel_norms["dinov3"] = (
_accumulate_fp32_pixel_cotangent(
combined_pixel,
pixel_dino,
pixel_shape,
branch_name="dinov3",
)
)
replay_maxima["dinov3"] = dino_max_abs
del pixel_dino
with torch.enable_grad():
replay_vj, pixel_vj = self._replay_dense_encoder_vjp(
student_video01,
tokens["vjepa2"],
expected["vjepa2"],
cotangent["vjepa2"],
gradient_checkpointing=(
self.vjepa2_dense_gradient_checkpointing),
temporal_window_indices=temporal_indices,
)
if not torch.allclose(
replay_vj, expected["vjepa2"],
atol=float(replay_atol), rtol=float(replay_rtol),
):
raise RuntimeError("triple V-JEPA2 replay changed cached features")
combined_pixel, pixel_shape, pixel_norms["vjepa2"] = (
_accumulate_fp32_pixel_cotangent(
combined_pixel,
pixel_vj,
pixel_shape,
branch_name="vjepa2",
)
)
replay_maxima["vjepa2"] = (
replay_vj - expected["vjepa2"]).abs().max().detach()
del replay_vj, pixel_vj
if "videomae_v2" in self.dual_branch_registry:
with torch.enable_grad():
replay_vm, pixel_vm = self.videomae_v2_encoder.replay_dense_vjp(
student_video01.detach().float(),
layer_indices=(15,),
token_indices=tokens["videomae_v2"],
expected_features=expected["videomae_v2"],
feature_cotangent=cotangent["videomae_v2"],
gradient_checkpointing=(
self.videomae_v2_dense_gradient_checkpointing),
)
if not torch.allclose(
replay_vm, expected["videomae_v2"],
atol=float(replay_atol), rtol=float(replay_rtol),
):
raise RuntimeError(
"VideoMAE-v2 replay changed cached features")
combined_pixel, pixel_shape, pixel_norms["videomae_v2"] = (
_accumulate_fp32_pixel_cotangent(
combined_pixel,
pixel_vm,
pixel_shape,
branch_name="videomae_v2",
)
)
replay_maxima["videomae_v2"] = (
replay_vm - expected["videomae_v2"]).abs().max().detach()
del replay_vm, pixel_vm
del student_video01
if set(pixel_norms) != set(self.dual_branch_registry):
raise RuntimeError(
"triple encoder replay did not visit every branch")
if not bool(torch.isfinite(combined_pixel).all().item()):
raise FloatingPointError(
"combined triple pixel cotangent is non-finite")
latent_cotangent = replay_decoder_vjp(
self.vae,
student_latent.detach(),
combined_pixel,
independent_first_frame=self.independent_first_frame,
).detach().float()
if latent_cotangent.shape != student_latent.shape:
raise ValueError(
"triple Wan VAE VJP returned an invalid latent shape")
if not bool(torch.isfinite(latent_cotangent).all().item()):
raise FloatingPointError(
"triple Wan VAE VJP returned non-finite values")
prefix = self.dense_log_prefix
feature_norm = torch.sqrt(torch.stack([
value.norm().float().square() for value in cotangent.values()
]).sum())
replay_max_abs = torch.stack([
value.float() for value in replay_maxima.values()
]).max()
replay_log = {
f"{prefix}_feature_grad_norm": feature_norm.detach(),
f"{prefix}_video_grad_norm": combined_pixel.norm().detach(),
f"{prefix}_latent_grad_norm": latent_cotangent.norm().detach(),
f"{prefix}_replay_max_abs": replay_max_abs.detach(),
"combined_latent_grad_norm": latent_cotangent.norm().detach(),
"fresh_video_prepared_vae_vjp": latent_cotangent.new_ones(()),
f"{prefix}_encoder_vjp_count": latent_cotangent.new_tensor(
len(pixel_norms), dtype=torch.long),
f"{prefix}_vae_vjp_count": latent_cotangent.new_tensor(
1, dtype=torch.long),
}
for name in self.dual_branch_registry:
replay_log[f"{name}_dense_feature_grad_norm"] = (
cotangent[name].norm().detach())
replay_log[f"{name}_dense_video_grad_norm"] = (
pixel_norms[name])
replay_log[f"{name}_dense_replay_max_abs"] = (
replay_maxima[name].detach())
return {
"latent_cotangent": latent_cotangent.detach().to(
device="cpu",
dtype=torch.float32,
non_blocking=False,
).contiguous(),
"replay_log": replay_log,
}
@torch.no_grad()
def collect_rollout_features(
self,
*,
image_or_video_shape,
conditional_dict: dict,
unconditional_dict: dict,
initial_latent: Optional[torch.Tensor] = None,
current_teacher_features: Optional[torch.Tensor] = None,
current_teacher_video01: Optional[torch.Tensor] = None,
current_teacher_latent: Optional[torch.Tensor] = None,
require_current_teacher: bool = True,
vjepa2_window_sample_keys=None,
) -> Tuple[torch.Tensor, dict]:
"""First GradCache pass: generate and encode one fresh microbatch."""
if not self.uses_fresh_video_gradcache:
raise RuntimeError(
"collect_rollout_features requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if self.dual_video_mmd_enabled:
return self._collect_multi_encoder_rollout_features(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
initial_latent=initial_latent,
current_teacher_features=current_teacher_features,
current_teacher_video01=current_teacher_video01,
current_teacher_latent=current_teacher_latent,
require_current_teacher=require_current_teacher,
)
if type(require_current_teacher) is not bool:
raise TypeError("require_current_teacher must be a bool")
supplied_teacher_inputs = [
name for name, value in {
"current_teacher_features": current_teacher_features,
"current_teacher_video01": current_teacher_video01,
"current_teacher_latent": current_teacher_latent,
}.items() if value is not None
]
if not require_current_teacher and supplied_teacher_inputs:
raise ValueError(
"require_current_teacher=false rejects all teacher inputs; "
f"got {supplied_teacher_inputs}")
first_pass_error = None
try:
generation_descriptor = self._sample_generator_input_descriptor(
image_or_video_shape,
initial_latent=initial_latent,
)
saved_generation_noise = (
generation_descriptor["noise"].detach().clone())
# Initial Gaussian noise and the block count are explicit. The
# saved state begins *after* sampling them and drives any
# stochastic denoise/renoise choices inside the rollout pipeline.
rng_state = self._capture_generation_rng()
student_latent, _ = self._generate_student_latent(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
initial_latent=initial_latent,
generation_descriptor=generation_descriptor,
)
matched_teacher_features = None
teacher_extract_seconds = None
student_video01 = self._decode_video01(student_latent)
token_indices = None
temporal_window_indices = None
if self._uses_dinov3_dense_backend():
if vjepa2_window_sample_keys is not None:
raise ValueError(
"DINOv3 fixed-frame sampling rejects V-JEPA2 keys")
features = self._extract_dinov3_dense(
student_video01).detach().float()
if require_current_teacher:
if (
current_teacher_video01 is not None
or current_teacher_latent is not None
or not isinstance(current_teacher_features, torch.Tensor)
):
raise ValueError(
"DINOv3 current teacher must be detached features")
matched_teacher_features = (
current_teacher_features.detach().float())
if tuple(matched_teacher_features.shape) != tuple(features.shape):
raise ValueError(
"DINOv3 teacher/student feature shapes differ")
else:
token_indices = self._vjepa2_token_indices(
student_latent.device)
temporal_window_indices = (
self._vjepa2_temporal_window_indices(
vjepa2_window_sample_keys,
batch_size=int(student_latent.shape[0]),
device=student_latent.device,
)
)
extract_kwargs = {"gradient_checkpointing": False}
if temporal_window_indices is not None:
extract_kwargs["temporal_window_indices"] = (
temporal_window_indices)
# A live-video cache miss supplies an already selected 64-frame
# clip. A latent or complete 81-frame video uses the student's
# explicit temporal indices.
teacher_extract_kwargs = dict(extract_kwargs)
if (
current_teacher_video01 is not None
and temporal_window_indices is not None
and int(current_teacher_video01.shape[1])
== int(self.vjepa2_dense_num_frames)
):
teacher_extract_kwargs.pop("temporal_window_indices", None)
teacher_requires_extraction = bool(
require_current_teacher
and (
current_teacher_video01 is not None
or current_teacher_latent is not None
)
)
if teacher_requires_extraction and student_latent.is_cuda:
torch.cuda.synchronize(student_latent.device)
teacher_extract_started = time.perf_counter()
matched_teacher_features = (
self._current_teacher_features_for_fresh_video(
student_latent=student_latent,
token_indices=token_indices,
extract_kwargs=teacher_extract_kwargs,
current_teacher_features=current_teacher_features,
current_teacher_video01=current_teacher_video01,
current_teacher_latent=current_teacher_latent,
)
if require_current_teacher
else None
)
if teacher_requires_extraction and student_latent.is_cuda:
torch.cuda.synchronize(student_latent.device)
teacher_extract_seconds = (
time.perf_counter() - teacher_extract_started
if teacher_requires_extraction else None
)
# The trainer transfers ownership with dict.pop(). Drop the three
# input aliases now so an uncached live video can be reclaimed
# before student VAE decode/V-JEPA2 extraction begins.
current_teacher_features = None
current_teacher_video01 = None
current_teacher_latent = None
student_video01 = self._decode_video01(student_latent)
features = self._extract_vjepa2_dense(
student_video01,
token_indices,
**extract_kwargs,
).detach().float()
if (
matched_teacher_features is not None
and tuple(matched_teacher_features.shape)
!= tuple(features.shape)
):
raise ValueError(
"matched teacher/student V-JEPA2 feature shapes must "
"match exactly: "
f"{tuple(matched_teacher_features.shape)} != "
f"{tuple(features.shape)}")
except BaseException as exc:
first_pass_error = exc
if not self._all_ranks_true(
first_pass_error is None, self.device
):
message = (
f": {type(first_pass_error).__name__}: {first_pass_error}"
if first_pass_error is not None
else " on another rank"
)
raise RuntimeError(
"fresh video generation/VAE/dense-encoder first pass failed"
+ message
) from first_pass_error
local_features_finite = bool(torch.isfinite(features).all().item())
if not self._all_ranks_true(
local_features_finite, features.device
):
raise FloatingPointError(
"non-finite dense feature in fresh GradCache first pass "
"on at least one rank")
if matched_teacher_features is not None:
local_teacher_features_finite = bool(
torch.isfinite(matched_teacher_features).all().item())
if not self._all_ranks_true(
local_teacher_features_finite,
matched_teacher_features.device,
):
raise FloatingPointError(
"non-finite matched teacher feature in fresh GradCache "
"first pass on at least one rank")
descriptor = {
"rng_state": rng_state,
"latent_shape": tuple(int(v) for v in student_latent.shape),
"generation_descriptor": {
"version": int(generation_descriptor["version"]),
"num_generated_blocks": int(
generation_descriptor["num_generated_blocks"]),
"noise": saved_generation_noise,
**({
"trajectory_seeds": generation_descriptor[
"trajectory_seeds"].detach().clone(),
} if "trajectory_seeds" in generation_descriptor else {}),
},
"student_latent": student_latent.detach().clone(),
}
if matched_teacher_features is not None:
# The trainer moves this detached value into the update-local
# GradCache immediately; teacher latents/pixels are never replayed.
descriptor["current_teacher_features"] = (
matched_teacher_features)
if teacher_extract_seconds is not None:
descriptor["current_teacher_extract_seconds"] = float(
teacher_extract_seconds)
if temporal_window_indices is not None:
descriptor["vjepa2_frame_indices"] = (
temporal_window_indices.detach().clone())
if self._uses_dinov3_dense_backend():
descriptor["dinov3_frame_indices"] = torch.tensor(
self.dinov3_dense_frame_indices,
device=student_latent.device,
dtype=torch.long,
)
if self.fresh_video_prepared_replay_enabled:
cache_error = None
try:
# Keep the exact first-pass FP32 pixels until update-wide
# feature cotangents are available. They are consumed before
# any differentiable generator replay, so this storage never
# overlaps the generator graph peak.
cached_video01 = student_video01.detach()
if self.fresh_video_pixel_cache_device == "cpu":
cached_video01 = cached_video01.to(
device="cpu", dtype=torch.float32, copy=True)
descriptor["cached_student_video01"] = cached_video01
except BaseException as exc:
cache_error = exc
if not self._all_ranks_true(
cache_error is None, student_latent.device
):
message = (
f": {type(cache_error).__name__}: {cache_error}"
if cache_error is not None
else " on another rank"
)
raise RuntimeError(
"fresh-video pixel caching failed" + message
) from cache_error
return features, descriptor
def prepare_latent_gradients(
self,
*,
replay_descriptor: dict,
expected_features: torch.Tensor,
feature_cotangent: torch.Tensor,
replay_atol: float = 1e-5,
replay_rtol: float = 1e-4,
) -> dict:
"""Replay frozen encoders and prepare a detached latent cotangent."""
if self.dual_video_mmd_enabled:
return self._prepare_multi_encoder_latent_gradients(
replay_descriptor=replay_descriptor,
expected_features=expected_features,
feature_cotangent=feature_cotangent,
replay_atol=replay_atol,
replay_rtol=replay_rtol,
)
if (
not self.fresh_video_prepared_replay_enabled
or not self.uses_fresh_video_gradcache
):
raise RuntimeError(
"prepared replay is unavailable for this fresh-video path")
prepare_error = None
prepared = None
try:
required_descriptor_keys = {
"rng_state",
"latent_shape",
"generation_descriptor",
"student_latent",
"cached_student_video01",
}
if getattr(
self, "vjepa2_student_frame_sampling",
getattr(self, "vjepa2_dense_frame_sampling", "center_contiguous"),
) != "center_contiguous":
required_descriptor_keys.add("vjepa2_frame_indices")
if self._uses_dinov3_dense_backend():
required_descriptor_keys.add("dinov3_frame_indices")
if (
not isinstance(replay_descriptor, dict)
or set(replay_descriptor) != required_descriptor_keys
):
raise ValueError(
"invalid cached fresh-video replay descriptor")
cached_student_video01 = replay_descriptor.pop(
"cached_student_video01")
student_latent = replay_descriptor["student_latent"]
if (
not isinstance(student_latent, torch.Tensor)
or tuple(student_latent.shape)
!= tuple(replay_descriptor["latent_shape"])
):
raise ValueError(
"cached first-pass latent has an invalid shape")
if not isinstance(cached_student_video01, torch.Tensor):
raise TypeError("cached first-pass pixels must be a tensor")
student_video01 = cached_student_video01.to(
device=student_latent.device,
dtype=torch.float32,
non_blocking=bool(cached_student_video01.is_pinned()),
)
del cached_student_video01
if (
student_video01.ndim != 5
or student_video01.shape[0] != student_latent.shape[0]
or student_video01.shape[2] != 3
):
raise ValueError(
"cached first-pass pixels have an invalid shape")
if not bool(torch.isfinite(student_video01).all().item()):
raise FloatingPointError(
"cached first-pass pixels are non-finite")
temporal_window_indices = None
token_indices = None
if self._uses_dinov3_dense_backend():
self._dinov3_descriptor_frame_indices(
replay_descriptor, device=student_latent.device)
else:
temporal_window_indices = (
self._vjepa2_descriptor_window_indices(
replay_descriptor, device=student_latent.device)
)
token_indices = self._vjepa2_token_indices(
student_latent.device)
expected_features = expected_features.to(
device=student_latent.device, dtype=torch.float32)
feature_cotangent = feature_cotangent.to(
device=student_latent.device, dtype=torch.float32)
if feature_cotangent.shape != expected_features.shape:
raise ValueError(
"feature cotangent shape does not match cached features: "
f"{tuple(feature_cotangent.shape)} != "
f"{tuple(expected_features.shape)}")
if not bool(torch.isfinite(feature_cotangent).all().item()):
raise FloatingPointError(
"non-finite fresh dense feature cotangent")
layer_feature_grad_norms = {}
if getattr(self, "vjepa2_multilayer_enabled", False):
expected_transport_tokens = (
len(self.vjepa2_dense_layers)
* self.vjepa2_dense_num_tokens
)
if int(feature_cotangent.shape[1]) != expected_transport_tokens:
raise ValueError(
"multi-layer feature cotangent has an invalid "
"transport token count")
layer_feature_grad_norms = {
f"vjepa2_dense_l{layer}_feature_grad_norm": (
part.norm().detach())
for layer, part in zip(
self.vjepa2_dense_layers,
feature_cotangent.split(
self.vjepa2_dense_num_tokens, dim=1),
)
}
if self._uses_dinov3_dense_backend():
video_cotangent, replay_max_abs = (
self._replay_dinov3_dense_to_pixels(
student_video01,
expected_features=expected_features,
feature_cotangent=feature_cotangent,
replay_atol=float(replay_atol),
replay_rtol=float(replay_rtol),
)
)
else:
with torch.enable_grad():
student_video_leaf = (
student_video01.detach().requires_grad_(True))
replay_extract_kwargs = {
"gradient_checkpointing": (
self.vjepa2_dense_gradient_checkpointing),
}
if temporal_window_indices is not None:
replay_extract_kwargs["temporal_window_indices"] = (
temporal_window_indices)
replay_features = self._extract_vjepa2_dense(
student_video_leaf,
token_indices,
**replay_extract_kwargs,
).float()
if replay_features.shape != expected_features.shape:
raise RuntimeError(
"fresh feature replay changed matrix shape: "
f"{tuple(replay_features.shape)} != "
f"{tuple(expected_features.shape)}")
replay_max_abs = (
replay_features.detach()
- expected_features).abs().max()
if not bool(torch.allclose(
replay_features.detach(),
expected_features,
atol=float(replay_atol),
rtol=float(replay_rtol),
)):
raise RuntimeError(
"cached pixels changed V-JEPA2 features "
f"(max_abs={float(replay_max_abs):.6g})")
encoder_surrogate = (
replay_features * feature_cotangent).sum()
(video_cotangent,) = torch.autograd.grad(
encoder_surrogate,
student_video_leaf,
retain_graph=False,
create_graph=False,
)
del encoder_surrogate, student_video_leaf, replay_features
video_cotangent = video_cotangent.detach().float()
if not bool(torch.isfinite(video_cotangent).all().item()):
raise FloatingPointError(
"non-finite fresh dense-encoder pixel cotangent")
video_grad_norm = video_cotangent.norm().detach()
del student_video01
latent_cotangent = replay_decoder_vjp(
self.vae,
student_latent.detach(),
video_cotangent,
independent_first_frame=self.independent_first_frame,
).detach().float()
del video_cotangent
if latent_cotangent.shape != student_latent.shape:
raise ValueError(
"Wan VAE VJP returned an invalid latent shape")
if not bool(torch.isfinite(latent_cotangent).all().item()):
raise FloatingPointError(
"Wan VAE VJP returned a non-finite cotangent")
replay_log = {
self._dense_key("feature_grad_norm"): (
feature_cotangent.norm().detach()),
self._dense_key("video_grad_norm"): video_grad_norm,
self._dense_key("latent_grad_norm"): (
latent_cotangent.norm().detach()),
"combined_latent_grad_norm": (
latent_cotangent.norm().detach()),
self._dense_key("replay_max_abs"): replay_max_abs.detach(),
"fresh_video_prepared_vae_vjp": (
latent_cotangent.new_ones(())),
}
replay_log.update(layer_feature_grad_norms)
prepared = {
"latent_cotangent": latent_cotangent.detach().to(
device="cpu",
dtype=torch.float32,
non_blocking=False,
).contiguous(),
"replay_log": replay_log,
}
except BaseException as exc:
prepare_error = exc
prepare_ok = self._all_ranks_true(
prepare_error is None, self.device)
if not prepare_ok:
all_errors_are_nonfinite = self._all_ranks_true(
prepare_error is None
or isinstance(prepare_error, FloatingPointError),
self.device,
)
message = (
f": {type(prepare_error).__name__}: {prepare_error}"
if prepare_error is not None
else " on another rank"
)
if all_errors_are_nonfinite:
raise FloatingPointError(
"fresh-video prepared replay produced a non-finite value"
+ message
) from prepare_error
raise RuntimeError(
"fresh-video replay preparation failed" + message
) from prepare_error
return prepared
def replay_generator_gradients(
self,
*,
replay_descriptor: dict,
expected_features: torch.Tensor,
feature_cotangent: torch.Tensor,
image_or_video_shape,
conditional_dict: dict,
unconditional_dict: dict,
initial_latent: Optional[torch.Tensor] = None,
prepared_replay: Optional[dict] = None,
replay_atol: float = 1e-5,
replay_rtol: float = 1e-4,
) -> Tuple[torch.Tensor, dict]:
"""Second GradCache pass: replay one video microbatch and encoder/VAE VJP."""
if not self.uses_fresh_video_gradcache:
raise RuntimeError(
"replay_generator_gradients requires "
"wan_mmd_estimator=nystrom_exact_repulsion")
if self.dual_video_mmd_enabled and prepared_replay is None:
raise RuntimeError("dual video MMD requires prepared replay")
required_descriptor_keys = {
"rng_state",
"latent_shape",
"generation_descriptor",
"student_latent",
}
# Prepared multi-encoder replay has already consumed encoder-specific
# frame fields. Generator replay retains only the common identity keys.
if not self.dual_video_mmd_enabled:
if getattr(
self, "vjepa2_student_frame_sampling",
getattr(self, "vjepa2_dense_frame_sampling", "center_contiguous"),
) != "center_contiguous":
required_descriptor_keys.add("vjepa2_frame_indices")
if self._uses_dinov3_dense_backend():
required_descriptor_keys.add("dinov3_frame_indices")
if (
not isinstance(replay_descriptor, dict)
or set(replay_descriptor) != required_descriptor_keys
):
raise ValueError("invalid fresh-video replay descriptor")
generator_replay_error = None
try:
with self._replay_generation_rng(replay_descriptor["rng_state"]):
activation_context = (
torch.autograd.graph.save_on_cpu(pin_memory=True)
if getattr(
self, "generator_replay_activation_cpu_offload", False)
else nullcontext()
)
with activation_context:
student_latent, gradient_mask = self._generate_student_latent(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
initial_latent=initial_latent,
generation_descriptor=replay_descriptor[
"generation_descriptor"],
)
except BaseException as exc:
generator_replay_error = exc
if not self._all_ranks_true(
generator_replay_error is None, self.device
):
message = (
f": {type(generator_replay_error).__name__}: "
f"{generator_replay_error}"
if generator_replay_error is not None
else " on another rank"
)
raise RuntimeError(
"fresh generator replay failed" + message
) from generator_replay_error
expected_latent_shape = tuple(replay_descriptor["latent_shape"])
local_latent_shape_ok = (
tuple(student_latent.shape) == expected_latent_shape)
if not self._all_ranks_true(
local_latent_shape_ok, student_latent.device
):
raise RuntimeError(
"fresh generator replay changed latent shape on at least one "
f"rank; local={tuple(student_latent.shape)}, "
f"expected={expected_latent_shape}")
expected_student_latent = replay_descriptor["student_latent"].to(
device=student_latent.device, dtype=student_latent.dtype)
latent_replay_max_abs = (
student_latent.detach() - expected_student_latent
).abs().max()
local_latent_replay_matches = bool(torch.allclose(
student_latent.detach(),
expected_student_latent,
atol=float(replay_atol),
rtol=float(replay_rtol),
))
if not self._all_ranks_true(
local_latent_replay_matches, student_latent.device
):
raise RuntimeError(
"fresh generator replay changed the generated latent on at "
"least one rank "
f"(local max_abs={float(latent_replay_max_abs):.6g})")
student_latent = self._apply_gradient_mask(
student_latent, gradient_mask)
if prepared_replay is not None:
# The detached decoder VJP was evaluated at the exact first-pass
# latent. Unlike the legacy value-side replay, an allclose-only
# match is insufficient because J_D(z) changes with z.
local_prepared_latent_exact = bool(torch.equal(
student_latent.detach(), expected_student_latent))
if not self._all_ranks_true(
local_prepared_latent_exact, student_latent.device
):
raise RuntimeError(
"prepared fresh-video replay requires bitwise-identical generator "
"latents on every rank "
f"(local max_abs={float(latent_replay_max_abs):.6g})")
prepared_error = None
latent_cotangent = None
replay_log = None
try:
prepared_enabled = self.fresh_video_prepared_replay_enabled
if not prepared_enabled:
raise RuntimeError(
"prepared replay was supplied while P0 is disabled")
if (
not isinstance(prepared_replay, dict)
or set(prepared_replay)
!= {"latent_cotangent", "replay_log"}
or not isinstance(prepared_replay.get("replay_log"), dict)
):
raise ValueError(
"invalid prepared fresh-video replay payload")
latent_cotangent = prepared_replay["latent_cotangent"]
if (
not isinstance(latent_cotangent, torch.Tensor)
or latent_cotangent.requires_grad
or latent_cotangent.grad_fn is not None
or latent_cotangent.shape != student_latent.shape
):
raise ValueError(
"prepared fresh-video latent cotangent has invalid structure")
latent_cotangent = latent_cotangent.to(
device=student_latent.device, dtype=torch.float32)
if not bool(torch.isfinite(
latent_cotangent).all().item()
):
raise FloatingPointError(
"prepared fresh-video latent cotangent is non-finite")
replay_log = dict(prepared_replay["replay_log"])
except BaseException as exc:
prepared_error = exc
prepared_ok = self._all_ranks_true(
prepared_error is None, student_latent.device)
if not prepared_ok:
all_errors_are_nonfinite = self._all_ranks_true(
prepared_error is None
or isinstance(prepared_error, FloatingPointError),
student_latent.device,
)
message = (
f": {type(prepared_error).__name__}: {prepared_error}"
if prepared_error is not None
else " on another rank"
)
if all_errors_are_nonfinite:
raise FloatingPointError(
"prepared fresh-video replay produced a non-finite value"
+ message
) from prepared_error
raise RuntimeError(
"prepared fresh-video replay validation failed" + message
) from prepared_error
replay_surrogate = (
student_latent.float() * latent_cotangent).sum()
loss = replay_surrogate - replay_surrogate.detach()
dense_prefix = self._dense_metric_prefix()
replay_log.update({
self._dense_key("latent_replay_max_abs"): (
latent_replay_max_abs.detach()),
"fresh_video_prepared_replay": (
latent_cotangent.new_ones(())),
})
return loss, replay_log
token_indices = None
temporal_window_indices = None
if not self._uses_dinov3_dense_backend():
token_indices = self._vjepa2_token_indices(
student_latent.device)
temporal_window_indices = (
self._vjepa2_descriptor_window_indices(
replay_descriptor, device=student_latent.device)
)
# Recreate the value-side VAE/V-JEPA2 path and prove that the replayed
# generator sample is exactly the sample scored in the first pass.
with torch.no_grad():
student_video01 = self._decode_video01(student_latent)
expected_features = expected_features.to(
device=student_latent.device, dtype=torch.float32)
feature_cotangent = feature_cotangent.to(
device=student_latent.device, dtype=torch.float32)
local_cotangent_shape_ok = (
feature_cotangent.shape == expected_features.shape)
if not self._all_ranks_true(
local_cotangent_shape_ok, student_latent.device
):
raise ValueError(
"feature cotangent shape does not match the cached video "
"matrix on at least one rank: "
f"{tuple(feature_cotangent.shape)} != "
f"{tuple(expected_features.shape)}")
local_cotangent_finite = bool(
torch.isfinite(feature_cotangent).all().item())
if not self._all_ranks_true(
local_cotangent_finite, student_latent.device
):
raise FloatingPointError(
"non-finite fresh dense feature cotangent on at least one "
"rank")
# Frozen encoder VJP to decoded pixels. No rank enters a subsequent
# collective until every locally fallible encoder/autograd operation
# has either completed or been captured, preventing a one-rank replay
# exception from stranding peers in an all-reduce.
encoder_replay_error = None
try:
if self._uses_dinov3_dense_backend():
self._dinov3_descriptor_frame_indices(
replay_descriptor, device=student_latent.device)
video_cotangent, replay_max_abs = (
self._replay_dinov3_dense_to_pixels(
student_video01,
expected_features=expected_features,
feature_cotangent=feature_cotangent,
replay_atol=float(replay_atol),
replay_rtol=float(replay_rtol),
)
)
else:
with torch.enable_grad():
student_video_leaf = (
student_video01.detach().float().requires_grad_(True))
replay_extract_kwargs = {
"gradient_checkpointing": (
self.vjepa2_dense_gradient_checkpointing),
}
if temporal_window_indices is not None:
replay_extract_kwargs["temporal_window_indices"] = (
temporal_window_indices)
replay_features = self._extract_vjepa2_dense(
student_video_leaf,
token_indices,
**replay_extract_kwargs,
).float()
if replay_features.shape != expected_features.shape:
raise RuntimeError(
"fresh feature replay changed matrix shape: "
f"{tuple(replay_features.shape)} != "
f"{tuple(expected_features.shape)}")
replay_max_abs = (
replay_features.detach()
- expected_features).abs().max()
if not bool(torch.allclose(
replay_features.detach(),
expected_features,
atol=float(replay_atol),
rtol=float(replay_rtol),
)):
raise RuntimeError(
"fresh generator replay is not deterministic in "
"V-JEPA2 space "
f"(max_abs={float(replay_max_abs):.6g})")
encoder_surrogate = (
replay_features * feature_cotangent).sum()
(video_cotangent,) = torch.autograd.grad(
encoder_surrogate,
student_video_leaf,
retain_graph=False,
create_graph=False,
)
del encoder_surrogate, student_video_leaf, replay_features
except BaseException as exc:
encoder_replay_error = exc
if not self._all_ranks_true(
encoder_replay_error is None, student_latent.device
):
message = (
f": {type(encoder_replay_error).__name__}: "
f"{encoder_replay_error}"
if encoder_replay_error is not None
else " on another rank"
)
raise RuntimeError(
"frozen dense encoder replay failed" + message
) from encoder_replay_error
video_cotangent = video_cotangent.detach().float()
local_video_finite = bool(
torch.isfinite(video_cotangent).all().item())
if not self._all_ranks_true(
local_video_finite, video_cotangent.device
):
raise FloatingPointError(
"non-finite fresh dense-encoder pixel cotangent on at least one "
"rank")
mmd_video_grad_norm = video_cotangent.norm().detach()
# ``encoder_surrogate`` is the autograd root and therefore keeps the
# leaf (and its full decoded-video storage) alive even after
# ``autograd.grad`` has consumed the graph. Drop the already-consumed
# root together with the leaf so ``student_video01 = None`` below can
# actually release that storage before the frame VAE VJP. No tensor
# operation or derivative changes: all three values are dead here.
# Frozen causal Wan VAE VJP to the generated latent, with the same
# rank-consensus exception boundary as the encoder replay above.
vae_replay_error = None
try:
mmd_latent_cotangent = replay_decoder_vjp(
self.vae,
student_latent.detach(),
video_cotangent,
independent_first_frame=self.independent_first_frame,
).detach().float()
if mmd_latent_cotangent.shape != student_latent.shape:
raise ValueError(
"Wan VAE decoder VJP returned an invalid latent shape: "
f"{tuple(mmd_latent_cotangent.shape)} != "
f"{tuple(student_latent.shape)}")
except BaseException as exc:
vae_replay_error = exc
if not self._all_ranks_true(
vae_replay_error is None, student_latent.device
):
message = (
f": {type(vae_replay_error).__name__}: {vae_replay_error}"
if vae_replay_error is not None
else " on another rank"
)
raise RuntimeError(
"frozen Wan VAE replay failed" + message
) from vae_replay_error
local_latent_finite = bool(
torch.isfinite(mmd_latent_cotangent).all().item())
if not self._all_ranks_true(
local_latent_finite, mmd_latent_cotangent.device
):
raise FloatingPointError(
"non-finite fresh dense-feature latent cotangent on at least one "
"rank")
del video_cotangent
del student_video01
latent_cotangent = mmd_latent_cotangent
# The global scalar value is logged from FreshVideoGradCache. This
# zero-valued surrogate carries only its exact replayed derivative.
replay_surrogate = (
student_latent.float() * latent_cotangent).sum()
loss = replay_surrogate - replay_surrogate.detach()
dense_prefix = self._dense_metric_prefix()
return loss, {
f"{dense_prefix}_feature_grad_norm": (
feature_cotangent.norm().detach()),
self._dense_key("video_grad_norm"): (
mmd_video_grad_norm),
self._dense_key("latent_grad_norm"): (
mmd_latent_cotangent.norm().detach()),
"combined_latent_grad_norm": (
latent_cotangent.norm().detach()),
self._dense_key("replay_max_abs"): replay_max_abs.detach(),
self._dense_key("latent_replay_max_abs"): (
latent_replay_max_abs.detach()),
}
def compute_latent_mmd_loss(
self,
student_latent: torch.Tensor,
teacher_latent: torch.Tensor,
conditional_dict: dict,
gradient_mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, dict]:
if self.uses_fresh_video_gradcache:
raise RuntimeError(
"nystrom_exact_repulsion must be evaluated through the "
"trainer's full fresh-video GradCache batch")
student_latent = self._apply_gradient_mask(student_latent, gradient_mask)
teacher_latent = teacher_latent.to(
device=student_latent.device, dtype=student_latent.dtype)
if teacher_latent.shape != student_latent.shape:
raise ValueError(
f"teacher latent {tuple(teacher_latent.shape)} != "
f"student latent {tuple(student_latent.shape)}")
if self.feature_type == "post_block_latent":
return self._compute_wan_latent_mmd_loss(
student_latent, teacher_latent, conditional_dict)
return self._compute_vjepa2_dense_mmd_loss(
student_latent, teacher_latent)
def _compute_wan_latent_mmd_loss(
self,
student_latent: torch.Tensor,
teacher_latent: torch.Tensor,
conditional_dict: dict,
) -> Tuple[torch.Tensor, dict]:
indices = self._token_indices(student_latent)
# Teacher first: its no-grad temporaries are released before the student
# checkpoint graph is constructed.
with torch.no_grad():
teacher_features = self._extract(
teacher_latent, conditional_dict, indices)
student_features = self._extract(
student_latent, conditional_dict, indices)
mmd, mmd_meta = self.latent_mmd(
student_features, teacher_features, stage=True)
normalized_mmd = (
mmd / (mmd.detach() + self.latent_norm_eps)
if self.latent_self_normalize else mmd)
loss = self.latent_loss_weight * normalized_mmd
return loss, {
"dmdtrain_gradient_norm": loss.new_zeros(()),
"wan_latent_mmd": mmd.detach(),
"wan_latent_loss_normalized": normalized_mmd.detach(),
"wan_latent_bandwidth": mmd_meta["bandwidth"],
"wan_latent_history_updates": mmd_meta["history_updates"],
"wan_latent_current_coefficient": mmd_meta["current_coefficient"],
"wan_latent_tokens": loss.new_tensor(student_features.shape[1]),
"wan_latent_feature_dim": loss.new_tensor(
student_features.shape[2]),
"wan_latent_prefix_blocks": loss.new_tensor(
self.latent_layer + 1),
}
def _compute_vjepa2_dense_mmd_loss(
self,
student_latent: torch.Tensor,
teacher_latent: torch.Tensor,
) -> Tuple[torch.Tensor, dict]:
token_indices = self._vjepa2_token_indices(student_latent.device)
# Stage A: decode and extract both sides without retaining either the
# causal VAE or the V-JEPA2 graph. Teacher is processed first and its
# large decoded video is released before the student decode.
with torch.no_grad():
teacher_video01 = self._decode_video01(teacher_latent)
teacher_features = self._extract_vjepa2_dense(
teacher_video01,
token_indices,
gradient_checkpointing=False,
).detach().float()
del teacher_video01
student_video01 = self._decode_video01(student_latent)
student_features_detached = self._extract_vjepa2_dense(
student_video01,
token_indices,
gradient_checkpointing=False,
).detach().float()
# Stage A.2: calculate the MMD and its cotangent only on a small dense
# feature leaf. EMARBFMMD detaches historical kernel means and teacher
# features, so only this latest student leaf receives a gradient.
with torch.enable_grad():
student_features_leaf = (
student_features_detached.detach().requires_grad_(True))
mmd, mmd_meta = self.latent_mmd(
student_features_leaf, teacher_features, stage=True)
normalized_mmd = (
mmd / (mmd.detach() + self.latent_norm_eps)
if self.latent_self_normalize else mmd)
objective = self.latent_loss_weight * normalized_mmd
(feature_cotangent,) = torch.autograd.grad(
objective,
student_features_leaf,
retain_graph=False,
create_graph=False,
)
feature_cotangent = feature_cotangent.detach().float()
if not torch.isfinite(feature_cotangent).all():
raise FloatingPointError(
"non-finite V-JEPA2 dense-feature MMD cotangent")
# Stage B.1: replay only the frozen FP32 V-JEPA2 prefix. The adapter
# repeats the exact deterministic center-frame/resize/crop/normalize
# pipeline used above; non-reentrant block checkpointing bounds memory.
with torch.enable_grad():
student_video_leaf = (
student_video01.detach().float().requires_grad_(True))
replay_features = self._extract_vjepa2_dense(
student_video_leaf,
token_indices,
gradient_checkpointing=(
self.vjepa2_dense_gradient_checkpointing),
).float()
encoder_surrogate = (
replay_features * feature_cotangent).sum()
(video_cotangent,) = torch.autograd.grad(
encoder_surrogate,
student_video_leaf,
retain_graph=False,
create_graph=False,
)
video_cotangent = video_cotangent.detach().float()
if not torch.isfinite(video_cotangent).all():
raise FloatingPointError(
"non-finite V-JEPA2 replay pixel cotangent")
del encoder_surrogate, student_video_leaf, replay_features, student_video01
# Stage B.2: replay the frozen stateful Wan VAE decoder one latent frame
# at a time. Its temporal cache is carried by value and detached between
# frames, matching the repository's validated bounded-memory replay.
latent_cotangent = replay_decoder_vjp(
self.vae,
student_latent.detach(),
video_cotangent,
independent_first_frame=self.independent_first_frame,
).detach().float()
if latent_cotangent.shape != student_latent.shape:
raise ValueError(
"Wan VAE decoder VJP returned an invalid latent shape: "
f"got {tuple(latent_cotangent.shape)}, expected "
f"{tuple(student_latent.shape)}")
if not torch.isfinite(latent_cotangent).all():
raise FloatingPointError(
"non-finite V-JEPA2 replay latent cotangent")
# Preserve the true objective as the scalar value reported by the
# trainer while replacing its derivative with the replayed latent VJP.
replay_surrogate = (
student_latent.float() * latent_cotangent).sum()
loss = replay_surrogate + (
objective.detach() - replay_surrogate.detach())
return loss, {
"dmdtrain_gradient_norm": latent_cotangent.norm().detach(),
self._dense_key("mmd"): mmd.detach(),
self._dense_key("loss_normalized"): normalized_mmd.detach(),
self._dense_key("bandwidth"): mmd_meta["bandwidth"],
self._dense_key("history_updates"): mmd_meta["history_updates"],
self._dense_key("current_coefficient"): (
mmd_meta["current_coefficient"]),
"vjepa2_dense_raw_tokens": loss.new_tensor(
self.vjepa2_dense_raw_tokens),
"vjepa2_dense_sampled_tokens": loss.new_tensor(
student_features_detached.shape[1]),
self._dense_key("feature_dim"): loss.new_tensor(
student_features_detached.shape[2]),
self._dense_key("local_video_samples"): mmd_meta["local_samples"],
self._dense_key("global_video_samples"): mmd_meta["global_samples"],
self._dense_key("num_frames"): loss.new_tensor(
self.vjepa2_dense_num_frames),
self._dense_key("layer"): loss.new_tensor(
self.vjepa2_dense_layer),
self._dense_key("prefix_blocks"): loss.new_tensor(
self.vjepa2_dense_layer + 1),
self._dense_key("feature_grad_norm"): (
feature_cotangent.norm().detach()),
self._dense_key("video_grad_norm"): (
video_cotangent.norm().detach()),
self._dense_key("latent_grad_norm"): (
latent_cotangent.norm().detach()),
}
def distribution_state_pending(self) -> bool:
latent_mmd = getattr(self, "latent_mmd", None)
return bool(
getattr(self, "uses_fresh_video_gradcache", False)
and (
getattr(latent_mmd, "attraction_ema_pending", False)
or getattr(latent_mmd, "repulsion_fifo_pending", False)
)
)
def prepare_distribution_state(self):
"""Validate staged Nyström state before optimizer mutation."""
latent_mmd = getattr(self, "latent_mmd", None)
if (
getattr(self, "uses_fresh_video_gradcache", False)
and (
getattr(latent_mmd, "attraction_ema_enabled", False)
or getattr(latent_mmd, "repulsion_fifo_enabled", False)
)
):
latent_mmd.prepare_commit()
def commit_distribution_state(self) -> None:
if not self.uses_fresh_video_gradcache:
self.latent_mmd.commit()
return
latent_mmd = getattr(self, "latent_mmd", None)
if (
getattr(latent_mmd, "attraction_ema_enabled", False)
or getattr(latent_mmd, "repulsion_fifo_enabled", False)
):
latent_mmd.commit()
def discard_distribution_state(self) -> None:
if not self.uses_fresh_video_gradcache:
self.latent_mmd.discard()
return
latent_mmd = getattr(self, "latent_mmd", None)
if (
getattr(latent_mmd, "attraction_ema_enabled", False)
or getattr(latent_mmd, "repulsion_fifo_enabled", False)
):
latent_mmd.discard()
def generator_loss(
self,
image_or_video_shape,
conditional_dict: dict,
unconditional_dict: dict,
clean_latent: torch.Tensor,
initial_latent: torch.Tensor = None,
):
if self.uses_fresh_video_gradcache:
raise RuntimeError(
"nystrom_exact_repulsion generator_loss requires "
"FreshVideoGradCache orchestration in DistributionMatchingTrainer")
if clean_latent is None:
raise ValueError(
"wan_kv_mmd needs aligned teacher latents; configure "
"teacher_latent_data_path")
if self.causal_generator:
pred, gradient_mask, _, _ = self._run_generator(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
initial_latent=initial_latent,
)
else:
pred = self._run_few_step_generator(
image_or_video_shape=image_or_video_shape,
conditional_dict=conditional_dict,
unconditional_dict=unconditional_dict,
)
gradient_mask = None
return self.compute_latent_mmd_loss(
pred, clean_latent, conditional_dict, gradient_mask=gradient_mask)
def _fd_metadata(self) -> dict:
if self.feature_type == "dinov3_dense_latent":
return self._dinov3_feature_metadata()
if self.feature_type in self._DENSE_VIDEO_FEATURE_TYPES:
if self.dual_video_mmd_enabled:
branches = {}
for name, registry in self.dual_branch_registry.items():
branches[name] = {
"reference_path": registry["reference_path"],
"reference_hash": registry["reference_hash"],
"sample_shape": list(registry["sample_shape"]),
}
if "vjepa2" in branches:
branches["vjepa2"]["feature"] = (
self._vjepa2_feature_metadata())
if "dinov3" in branches:
branches["dinov3"]["feature"] = (
self._dinov3_feature_metadata())
if "videomae_v2" in branches:
from video_fd.encoders.videomae_v2_dense_metadata import (
canonical_videomae_v2_dense_feature_metadata,
uniform_segment_token_indices,
)
video_indices = uniform_segment_token_indices(
self.videomae_v2_encoder.dense_raw_tokens, 256)
branches["videomae_v2"]["feature"] = (
canonical_videomae_v2_dense_feature_metadata(
model_id=self.videomae_v2_reference_model_id,
model_id_is_reference=True,
layer_index=15,
num_tokens=256,
token_indices=video_indices,
num_segments=5,
frames_per_segment=16,
raw_tokens_per_segment=(
self.videomae_v2_encoder.dense_raw_tokens),
feature_dim=(
self.videomae_v2_encoder.dense_feature_dim),
resize_short_side=224,
crop_size=224,
skip_first_frame=True,
))
branch_weights = {
name: float(self.latent_mmd.branch_weights[name])
for name in sorted(branches)
}
teacher_bank_content_hash = (
self.triple_teacher_bank_content_hash
if self.feature_type
== "triple_dinov3_vjepa2_videomae_v2_dense_latent"
else self.dual_teacher_bank_content_hash
)
aggregation_divisor = float(
self.latent_mmd.aggregation_divisor)
combination = {
"operation": "sum",
"branch_weights": branch_weights,
"divide_by_branch_count": (
aggregation_divisor == float(len(branches))),
"normalization": (
"raw_div_stop_gradient_raw_plus_epsilon"),
"normalization_epsilon": self.latent_norm_eps,
}
if aggregation_divisor != 1.0:
combination["aggregation_divisor"] = aggregation_divisor
current_enabled = bool(
self.current_teacher_attraction_enabled)
forward_samples = int(self.fresh_video_total_samples)
gradient_samples = int(
self.expected_current_teacher_samples
if current_enabled
else getattr(
self,
"fresh_video_gradient_global_samples",
forward_samples,
)
)
teacher_samples = (
gradient_samples if current_enabled else 0)
result = {
"feature_type": self.feature_type,
"branches": branches,
"teacher_bank_content_hash": teacher_bank_content_hash,
"teacher_mixture": {
"fixed_reference_weight": (
self.nystrom_attraction_weight),
"current_teacher_weight": (
self.current_teacher_attraction_weight
if current_enabled else 0.0),
"normalization": (
"divide_by_weight_sum"
if current_enabled else "fixed_reference_only"),
},
"combination": combination,
"partial_gradient": {
"forward_global_samples": forward_samples,
"gradient_global_samples": gradient_samples,
"expected_teacher_global_samples": teacher_samples,
"full_student_population": True,
"replay_cotangent_compensation": (
float(forward_samples) / float(gradient_samples)),
"denominators": {
"kss": forward_samples * forward_samples,
"fixed_attraction": forward_samples,
"teacher_cross": (
forward_samples * teacher_samples),
"teacher_self": teacher_samples * teacher_samples,
},
},
}
if hasattr(
self, "dinov3_vjepa2_reference_bundle_manifest_sha256"
):
result["reference_bundle"] = {
"path": (
self.dinov3_vjepa2_reference_bundle_manifest),
"sha256": (
self.dinov3_vjepa2_reference_bundle_manifest_sha256),
"video_name_sequence_sha256": (
self.openvid_video_name_sequence_sha256),
"legacy_vjepa_provenance_bridge": True,
}
return result
if getattr(self, "vjepa2_multilayer_enabled", False):
return {
"feature_type": "vjepa2_dense_multilayer_latent",
"features": [
self._vjepa2_feature_metadata(
layer_index=layer)
for layer in self.vjepa2_dense_layers
],
"combination": {
"operation": "sum",
"per_layer_objective": (
"nystrom_exact_repulsion"),
"normalization": (
"mmd_over_abs_detached_mmd_plus_epsilon"
if self.latent_self_normalize
else "none"
),
"normalization_epsilon": self.latent_norm_eps,
"layer_weights": [
1.0 for _ in self.vjepa2_dense_layers
],
},
}
metadata = self._vjepa2_feature_metadata()
reference_sampling = getattr(
self, "vjepa2_dense_frame_sampling", "center_contiguous")
student_sampling = getattr(
self,
"vjepa2_student_frame_sampling",
reference_sampling,
)
if student_sampling != reference_sampling:
student_start = (
int(self.vjepa2_student_source_num_frames)
- int(self.vjepa2_dense_num_frames)
)
metadata = dict(metadata)
metadata["student_temporal_sampling"] = {
"frame_sampling": student_sampling,
"source_num_frames": int(
self.vjepa2_student_source_num_frames),
"selected_frame_indices": [
student_start,
student_start + int(self.vjepa2_dense_num_frames) - 1,
],
"reference_frame_sampling": (
reference_sampling),
}
if getattr(self, "nystrom_attraction_weight", 1.0) != 1.0:
metadata = dict(metadata)
metadata["nystrom_attraction_weight"] = (
self.nystrom_attraction_weight)
if getattr(
self, "current_teacher_attraction_enabled", False
):
metadata = dict(metadata)
metadata["nystrom_current_teacher_attraction"] = {
"enabled": True,
"estimator": "exact_biased_gaussian_mmd",
"fixed_weight": self.nystrom_attraction_weight,
"current_weight": (
self.current_teacher_attraction_weight),
"normalization": "divide_by_group_weight_sum",
"expected_global_samples": (
self.expected_current_teacher_samples),
"ema_gradient_mode": (
"straight_through_full_current_mix"
if self.nystrom_attraction_ema_enabled
else "direct_full_current_mix"),
}
if self.current_teacher_source == "matched_manifest_video":
metadata[
"nystrom_current_teacher_attraction"
]["source"] = "matched_manifest_video"
# Preserve the tuple used by legacy v2 checkpoints. The new
# canonical reference metadata stores JSON-like lists instead.
if getattr(self, "mmd_estimator", "ema_rff") == "ema_rff":
metadata = dict(metadata)
metadata.pop("feature_metadata_version", None)
metadata.pop("vae_id", None)
metadata.pop("token_indices_sha256", None)
metadata.pop("kernel", None)
metadata["matrix_shape"] = tuple(metadata["matrix_shape"])
return metadata
return {
"feature_type": self.feature_type,
"layer_index": self.latent_layer,
"prefix_blocks": self.latent_layer + 1,
"num_tokens": self.latent_num_tokens,
"feature_dim": self.latent_feature_dim,
"timestep": self.latent_timestep,
"patch_size": self.latent_patch_size,
}
def _nystrom_attraction_ema_active(self) -> bool:
return bool(
getattr(self, "uses_fresh_video_gradcache", False)
and getattr(
getattr(self, "latent_mmd", None),
"attraction_ema_enabled",
False,
)
)
def _nystrom_repulsion_fifo_active(self) -> bool:
return bool(
getattr(self, "uses_fresh_video_gradcache", False)
and getattr(
getattr(self, "latent_mmd", None),
"repulsion_fifo_enabled",
False,
)
)
def _nystrom_fd_state_version(self) -> int:
if getattr(self, "is_triple_dense", False):
base_version = 10
elif self.dual_video_mmd_enabled:
base_version = 9
elif getattr(self, "vjepa2_multilayer_enabled", False):
base_version = 4
else:
base_version = 1
if self._nystrom_repulsion_fifo_active():
if base_version != 1 or self._nystrom_attraction_ema_active():
raise ValueError(
"repulsion FIFO requires the single-layer fixed-reference "
"Nyström state without attraction EMA")
return 8
if not self._nystrom_attraction_ema_active():
return base_version
enabled_versions = {1: 5, 4: 7}
if base_version not in enabled_versions:
raise ValueError(
"attraction EMA is incompatible with this Nyström state "
f"variant v{base_version}")
return enabled_versions[base_version]
def _with_nystrom_attraction_ema_state(self, state: dict) -> dict:
if self._nystrom_attraction_ema_active():
state["attraction_ema"] = (
self.latent_mmd.attraction_ema_state_dict())
return state
def _with_nystrom_distribution_state(self, state: dict) -> dict:
state = self._with_nystrom_attraction_ema_state(state)
if self._nystrom_repulsion_fifo_active():
state["repulsion_fifo"] = (
self.latent_mmd.repulsion_fifo_state_dict())
return state
def fd_state_dict(self) -> dict:
nystrom_version_key = self._dense_nystrom_version_key()
if getattr(self, "uses_fresh_video_gradcache", False):
if self.distribution_state_pending():
raise RuntimeError(
"refusing to checkpoint pending distribution state")
if self._uses_dinov3_dense_backend():
return {
"dinov3_dense_nystrom_mmd_version": 1,
"metadata": self._fd_metadata(),
"reference_path": self.dinov3_nystrom_reference_path,
"reference_hash": self.dinov3_nystrom_reference_hash,
"teacher_feature_bank_hash": (
self.dinov3_teacher_feature_bank_hash),
"estimator": self.mmd_estimator,
}
if getattr(self, "vjepa2_multilayer_enabled", False):
return self._with_nystrom_distribution_state({
"vjepa2_dense_nystrom_mmd_version": (
self._nystrom_fd_state_version()),
"metadata": self._fd_metadata(),
"reference_paths": list(
self.vjepa2_nystrom_reference_paths),
"reference_hashes": list(
self.vjepa2_nystrom_reference_hashes),
"teacher_feature_bank_hashes": list(
self.vjepa2_teacher_feature_bank_hashes),
"estimator": self.mmd_estimator,
})
if self.dual_video_mmd_enabled:
return {
self.dense_nystrom_version_key: (
self._nystrom_fd_state_version()),
"metadata": self._fd_metadata(),
"references": {
name: {
"path": branch["reference_path"],
"hash": branch["reference_hash"],
"landmarks": branch["nystrom_landmarks"],
}
for name, branch in self.dual_branch_registry.items()
},
"teacher_bank_content_hash": (
self.triple_teacher_bank_content_hash
if self.is_triple_dense
else self.dual_teacher_bank_content_hash),
"estimator": self.mmd_estimator,
}
return self._with_nystrom_distribution_state({
"vjepa2_dense_nystrom_mmd_version": (
self._nystrom_fd_state_version()),
"metadata": self._fd_metadata(),
"reference_path": self.vjepa2_nystrom_reference_path,
"reference_hash": self.vjepa2_nystrom_reference_hash,
"teacher_feature_bank_hash": (
self.vjepa2_teacher_feature_bank_hash),
"estimator": self.mmd_estimator,
})
if self.feature_type == "vjepa2_dense_latent":
return {
"vjepa2_dense_mmd_version": 2,
"metadata": self._fd_metadata(),
"vjepa2_dense_mmd": self.latent_mmd.state_dict(),
}
return {
"wan_kv_mmd_version": 3,
"metadata": self._fd_metadata(),
"wan_latent_mmd": self.latent_mmd.state_dict(),
}
def load_fd_state_dict(self, state_dict: dict) -> None:
if self._uses_dinov3_dense_backend():
if not isinstance(state_dict, dict):
raise TypeError("DINOv3 distribution state must be a mapping")
if any(key in state_dict for key in (
"wan_kv_mmd_version",
"vjepa2_dense_mmd_version",
"vjepa2_dense_nystrom_mmd_version",
)):
raise ValueError(
"Wan/V-JEPA2 distribution state cannot be loaded into "
"the DINOv3 dense-latent feature space")
version = state_dict.get(
"dinov3_dense_nystrom_mmd_version")
if version != 1:
raise ValueError(
"resume checkpoint has no compatible DINOv3 dense "
f"Nyström state v1 (got {version!r})")
expected = self.fd_state_dict()
if set(state_dict) != set(expected):
raise ValueError(
"DINOv3 Nyström checkpoint/reference keys mismatch: "
f"saved={sorted(state_dict)}, "
f"current={sorted(expected)}")
if state_dict != expected:
raise ValueError(
"DINOv3 Nyström checkpoint/reference identity mismatch: "
f"saved={state_dict}, current={expected}")
return
dense_version_key = self._dense_ema_version_key()
dense_state_key = self._dense_ema_state_key()
nystrom_version_key = self._dense_nystrom_version_key()
foreign_dense_version_keys = {
"vjepa2_dense_mmd_version",
"motionformer_dense_mmd_version",
"vjepa2_dense_nystrom_mmd_version",
"motionformer_dense_nystrom_mmd_version",
"dual_dense_mmd_version",
"dual_dense_nystrom_mmd_version",
"triple_dense_nystrom_mmd_version",
} - {dense_version_key, nystrom_version_key}
if getattr(self, "uses_fresh_video_gradcache", False):
present_foreign = sorted(
foreign_dense_version_keys.intersection(state_dict))
if present_foreign:
raise ValueError(
"checkpoint belongs to another dense feature namespace: "
f"{present_foreign}")
if "dinov3_dense_nystrom_mmd_version" in state_dict:
raise ValueError(
"DINOv3 distribution state cannot be loaded into the "
"V-JEPA2 dense-latent feature space")
if (
"wan_kv_mmd_version" in state_dict
or dense_version_key in state_dict
):
raise ValueError(
"EMA/RFF distribution history cannot be loaded into the "
"fresh Nyström exact-repulsion estimator")
version = state_dict.get(nystrom_version_key)
expected_version = self._nystrom_fd_state_version()
if version != expected_version:
raise ValueError(
"resume checkpoint has no compatible dense feature "
f"Nyström state v{expected_version} for "
f"{nystrom_version_key} (got {version!r})")
validated_attraction_ema = None
if self._nystrom_attraction_ema_active():
if "attraction_ema" not in state_dict:
raise ValueError(
"resume checkpoint is missing attraction EMA state")
validated_attraction_ema = (
self.latent_mmd.validate_attraction_ema_state_dict(
state_dict["attraction_ema"])
)
validated_repulsion_fifo = None
if self._nystrom_repulsion_fifo_active():
if "repulsion_fifo" not in state_dict:
raise ValueError(
"resume checkpoint is missing repulsion FIFO state")
validated_repulsion_fifo = (
self.latent_mmd.validate_repulsion_fifo_state_dict(
state_dict["repulsion_fifo"])
)
expected = self.fd_state_dict()
if set(state_dict) != set(expected):
raise ValueError(
"V-JEPA2 Nyström checkpoint/reference keys mismatch: "
f"saved={sorted(state_dict)}, "
f"current={sorted(expected)}")
identity_keys = set(expected)
identity_keys.discard("attraction_ema")
identity_keys.discard("repulsion_fifo")
saved_identity = {
key: state_dict.get(key) for key in identity_keys}
expected_identity = {
key: expected.get(key) for key in identity_keys}
# Runtime live-teacher batch size is not frozen-reference identity.
saved_identity = copy.deepcopy(saved_identity)
expected_identity = copy.deepcopy(expected_identity)
for identity in (saved_identity, expected_identity):
current_teacher = identity.get("metadata", {}).get(
"nystrom_current_teacher_attraction", {})
current_teacher.pop("expected_global_samples", None)
saved_identity = _canonicalize_shared_asset_paths(saved_identity)
expected_identity = _canonicalize_shared_asset_paths(
expected_identity)
if saved_identity != expected_identity:
raise ValueError(
"V-JEPA2 Nyström checkpoint/reference mismatch: "
f"saved={saved_identity}, current={expected_identity}")
if validated_attraction_ema is not None:
self.latent_mmd.load_attraction_ema_state_dict(
validated_attraction_ema)
if validated_repulsion_fifo is not None:
self.latent_mmd.load_repulsion_fifo_state_dict(
validated_repulsion_fifo)
return
if self.feature_type == "vjepa2_dense_latent":
if "dinov3_dense_nystrom_mmd_version" in state_dict:
raise ValueError(
"DINOv3 distribution state cannot be loaded into the "
"V-JEPA2 dense-latent feature space")
if "wan_kv_mmd_version" in state_dict:
raise ValueError(
"Wan post-block latent MMD history cannot be loaded into "
"the V-JEPA2 dense-latent feature space")
version = state_dict.get("vjepa2_dense_mmd_version")
if version != 2:
detail = (
" V-JEPA2 dense MMD v1 treated individual tokens as "
"distribution samples and is intentionally incompatible."
if version == 1 else ""
)
raise ValueError(
"resume checkpoint has no compatible V-JEPA2 dense "
f"latent MMD v2 state (got version {version!r})."
f"{detail}")
if "vjepa2_dense_mmd" not in state_dict:
raise ValueError(
"resume checkpoint is missing fd.vjepa2_dense_mmd history")
expected = self._fd_metadata()
saved = state_dict.get("metadata")
if saved != expected:
raise ValueError(
"V-JEPA2 dense latent checkpoint/config mismatch: "
f"saved metadata={saved}, current={expected}")
self.latent_mmd.load_state_dict(
state_dict["vjepa2_dense_mmd"], strict=True)
return
if "dinov3_dense_nystrom_mmd_version" in state_dict:
raise ValueError(
"DINOv3 distribution state cannot be loaded into the Wan "
"post-block latent feature space")
version = state_dict.get("wan_kv_mmd_version")
if version != 3:
detail = (
" Wan KV MMD v2 history is intentionally incompatible."
if version == 2 else "")
raise ValueError(
"resume checkpoint has no compatible Wan post-block latent "
f"MMD v3 state.{detail}")
if "wan_latent_mmd" not in state_dict:
raise ValueError(
"resume checkpoint is missing fd.wan_latent_mmd history")
expected = self._fd_metadata()
saved = state_dict.get("metadata")
if saved != expected:
raise ValueError(
"Wan post-block latent checkpoint/config mismatch: "
f"saved metadata={saved}, current={expected}. "
"KV EMA checkpoints are intentionally incompatible.")
self.latent_mmd.load_state_dict(
state_dict["wan_latent_mmd"], strict=True)
def can_load_initialization_fd_state(self, state_dict: dict) -> bool:
"""Whether an initialization-only checkpoint carries our estimator."""
if not isinstance(state_dict, dict):
return False
if self._uses_dinov3_dense_backend():
return state_dict.get(
"dinov3_dense_nystrom_mmd_version") == 1
if getattr(self, "uses_fresh_video_gradcache", False):
return (
state_dict.get(self._dense_nystrom_version_key())
== self._nystrom_fd_state_version()
)
if self.feature_type == "vjepa2_dense_latent":
return state_dict.get("vjepa2_dense_mmd_version") == 2
return state_dict.get("wan_kv_mmd_version") == 3
# Historical entry points remain aliases for external callers.
fresh_video_gradcache_prepare_replay = prepare_latent_gradients
fresh_video_gradcache_replay = replay_generator_gradients
fresh_video_gradcache_forward = collect_rollout_features
_initialize_triple_dinov3_vjepa2_videomae_v2_features = _initialize_multi_encoder_features
_replace_with_triple_nystrom_objective = _build_multi_encoder_objective
_extract_dual_video_features = _extract_multi_encoder_features
_fresh_video_dual_gradcache_forward = _collect_multi_encoder_rollout_features
_dual_gradcache_prepare_replay = _prepare_multi_encoder_latent_gradients
# Old import/class spelling remains valid for existing callers.
WanKVMMD = DistributionMatchingModel
|