File size: 362,761 Bytes
5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 5d5776f b55fe02 | 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 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 | diff --git a/HF_DATASETS.md b/HF_DATASETS.md
index 01d4e8f..d29c68d 100644
--- a/HF_DATASETS.md
+++ b/HF_DATASETS.md
@@ -1,345 +1,239 @@
-# Hugging Face datasets
-
-This guide covers prepared dataset snapshots.
-For trained weights, see [Hugging Face model checkpoints](HF_MODEL_CHECKPOINTS.md).
-For source downloads and rendering, see the [dataset guide](datasets/README.md).
-
-The public [PartProbe3D preprocessed dataset](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed)
-publishes saved observations, calibration, target grids, completion markers, and split policies.
-The full extent bundles also contain posed geometry.
-The FoundationPose bundle contains an export for training without meshes.
-The dataset card lists archive availability and links RGB/mask/GLB previews.
-The Hugging Face viewer exposes the per-view metadata indices.
-
-| Dataset | Training views | Test views | Local root after restoration |
-| --- | ---: | ---: | --- |
-| 3D-FRONT | 39,930 | 10,066 | `datasets/3dfront/extent/point_cloud` |
-| YCB-V | 0 | 900 | `datasets/ycbv/extent/point_cloud` |
-| SAGE-10k | 17,456 | 1,952 | `datasets/sage/extent/point_cloud` |
-| FoundationPose | 42,256 | 4,692 | `datasets/foundationpose/extent/point_cloud` |
-
-YCB-V is evaluation only. SAGE's complete 64³ point-cloud extent contains 19,408
-views across 9,931 rooms.
-Of the 20,000 calibrated captures, 592 did not have enough visible prompts for training targets. Its layout-level SHA-256 split keeps
-all rooms/views of a layout together, with no validation split. The Hub card
-records archive upload progress separately from source preparation completion.
-FoundationPose retains 46,948 accepted captures from a budget of 50,000.
-Target preparation excluded 3,052 captures and reported zero processing errors.
-All 1,000 sampled views passed validation. This run skipped full validation by user request.
-Diagnostic subsets, raw archives, model weights, and model-specific feature caches are not in this upload.
-
-Install the project's preprocessing dependencies, including `huggingface-hub` and `requests`.
-From the repository root on another server, download and restore with:
+# Hugging Face reproduction data
-```bash
-python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset 3dfront
-python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset ycbv
-python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --cleanup
-```
-
-Use `--revision <Hub commit>` to pin a snapshot. Downloads resume after an interruption.
-The downloader checks each archive against its SHA-256 checksum.
-Restoration refuses to replace different existing data.
-Each dataset transfers one file at a time through sequential HTTP requests.
-Interrupted transfers retain their partial bytes. Different dataset commands can run concurrently.
-The downloader records progress in `datasets/<dataset>/archives/huggingface/<bundle-root>/<dataset>/download-status.json`.
-The downloader caches archives in `datasets/<dataset>/archives/huggingface/`.
-Allow space for both archives and extracted files. Source manifests retain
-historical absolute paths as provenance, but the loaders use manifest-relative
-sample, camera and saved geometry paths, so raw sources are unnecessary.
-Prepare model-specific feature caches on the destination server using the
-existing SS or SLAT preparation commands.
-
-Use `download --cleanup` to restore one archive at a time and remove it only
-after verification and successful extraction. This limits temporary archive
-storage to one shard while keeping the extracted dataset and small indices.
-The mixed training config `slat_segvigen/configs/one_hot_sum_flow_front3d_sage_32_nora_ray_pool.json`
-consumes these SAGE and 3D-FRONT roots, computing image features and pooling the
-saved 64³ grids to 32³ online.
-
-## Exports for training without meshes
-
-Training can use saved observations and targets without original datasets or mesh files.
-The export preserves the source manifest, split definitions, sample bytes, and checksums.
-Historical geometry paths remain provenance entries, but training does not open those paths.
-
-Create a local export from a complete extent:
-
-```bash
-python -m preprocess.training_export \
- --dataset datasets/3dfront/extent/point_cloud \
- --output datasets/3dfront/training/point_cloud
-```
-
-The exporter uses hard links on the same filesystem and copies files when necessary.
-The destination contains ordinary files and does not depend on source paths.
-It includes complete GT occlusion relations when they exist.
-It excludes mesh geometry and model-specific feature caches.
-The separate `training_export.json` records completion without changing the source manifest.
-
-Create transferable archives without an intermediate dataset copy:
-
-```bash
-python -m preprocess.huggingface pack \
- --dataset 3dfront=datasets/3dfront/extent/point_cloud \
- --artifact-kind extent-training \
- --output outputs/huggingface/training_only
-```
-
-The existing archive downloader also restores these archives.
-Use a separate packaging directory to avoid mixing full and training exports.
-The archive index records `artifact_kind=extent-training` and `geometry_included=false`.
-The source dataset remains unchanged.
-
-SS with object attention also needs its matching GT occlusion cache.
-SLAT shape training needs encoded targets and conditioning caches in addition to dataset metadata.
-Mesh-based evaluation and new SLAT shape encoding require a full extent export.
+The public [dataset repository](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) separates training data, required evaluation data, optional components, and deprecated uploads.
+The default download supports SS, generative SLAT segmentation, and 32³ SLAT shape training.
Model weights remain separate artifacts.
+See [model checkpoints](HF_MODEL_CHECKPOINTS.md) and [pretrained assets](ASSETS.md).
-## FoundationPose on another server
-
-Use [code revision `92ca3ee`](https://github.com/cube-c/PartProbe3D/commit/92ca3eea1dbec6e162e246858eb7bdb7f7fd0701) or a compatible later revision on `slat-shape`.
-The FoundationPose bundle preserves original RGB, depth, visible masks, cameras, object mapping, and complete per-object voxel occupancy at 64³.
-Its source manifest has SHA-256 `2c4dcd1cd1e2e56a0eb08f2f92da320f299729c8ce7a2f52828c272cbc1fa0ad`.
-The extracted files occupy 87.82 GB before filesystem overhead.
-The [verified inventory](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/073988c5b5e206570da67f57aada4a2f0ad94e95/bundles/foundationpose/index.json) contains 86 archives totaling 89.33 GB.
-The export excludes raw archives, meshes, model weights, image features, SLAT latents, and GT occlusion relations.
-
-The loaders resolve input paths relative to the restored dataset.
-Historical absolute paths remain provenance entries.
-SS preparation creates the union of complete occupancy for objects with supplied masks and excludes other object voxels.
-
-### Restore the data
-
-Use Python 3.12 and a compatible PyTorch/CUDA installation.
-Run these commands from the repository root.
-
-1. Install the project dependencies.
-
- ```bash
- python -m pip install -e '.[preprocess,ss-multiobj-depth,tracking]'
- ```
-
-2. Restore the prepared observations and voxel targets.
-
- ```bash
- python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --dataset foundationpose --cleanup \
- --revision 073988c5b5e206570da67f57aada4a2f0ad94e95
- ```
-
-3. Initialize the pinned Pixal3D source.
-
- ```bash
- git submodule update --init third_party/Pixal3D
- ```
-
-`--cleanup` retains extracted data and removes each verified temporary archive.
-Allow at least 100 GB for data restoration, plus space for weights and model features.
-Use `--revision <Hub commit>` to retain one dataset snapshot.
-
-### Acquire SS weights
-
-All required weights for the following SS configuration are available from Hugging Face.
-The commands pin revisions with the same configuration and weight bytes as the verified local files.
-DINOv3 requires approved access to its [gated model repository](https://huggingface.co/facebook/dinov3-vitl16-pretrain-lvd1689m).
-
-1. Authenticate with an account that can download DINOv3.
-
- ```bash
- hf auth login
- ```
+## Select data by task
-2. Download the native SS flow and decoder from [Pixal3D](https://huggingface.co/TencentARC/Pixal3D).
+Use `--task` to download only the data required by a server.
+The [HF task catalog](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/main/tasks/index.json) records components and sizes.
+The [HF task guide](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/blob/main/tasks/README.md) also lists sizes for individual datasets.
- ```bash
- hf download TencentARC/Pixal3D \
- --revision b0cb2e1b794cab9aa0ac38a95d794a4d9337437f \
- --local-dir checkpoints/Pixal3D \
- --include 'ckpts/ss_flow_img_dit_1_3B_64_bf16.*' 'ckpts/ss_dec_conv3d_16l8_fp16.*'
- ```
+| Task | Required data | Default datasets | Transfer, GB |
+| --- | --- | --- | ---: |
+| `eval` | RGB, masks, GT meshes | PICASSO, MessyKitchen, selected 3D-FRONT test views | 23.404 |
+| `ss` | Observations and encoded SS targets | 3D-FRONT, SAGE, FoundationPose | 265.667 |
+| `slat-seg` | Observations only | 3D-FRONT, SAGE, FoundationPose | 221.950 |
+| `slat-shape` | Observations and 32³ object shape targets | 3D-FRONT, SAGE | 166.318 |
+| `all-training` | All training components | 3D-FRONT, SAGE, FoundationPose | 271.793 |
-3. Download the SS encoder and paired decoder from [TRELLIS](https://huggingface.co/microsoft/TRELLIS-image-large).
+Sizes use decimal GB and exclude model weights.
+Archive extraction needs additional local space.
+The task commands verify archives and remove them after extraction.
+They retain existing files and resume partial transfers.
- ```bash
- hf download microsoft/TRELLIS-image-large \
- --revision 25e0d31ffbebe4b5a97464dd851910efc3002d96 \
- --local-dir checkpoints/TRELLIS \
- --include 'ckpts/ss_enc_conv3d_16l8_fp16.*' 'ckpts/ss_dec_conv3d_16l8_fp16.safetensors'
- ```
+Preview the selected components before downloading:
-4. Download DINOv3.
-
- ```bash
- hf download facebook/dinov3-vitl16-pretrain-lvd1689m \
- --revision ea8dc2863c51be0a264bab82070e3e8836b02d51 \
- --local-dir checkpoints/DINOv3 --include config.json model.safetensors
- ```
-
-### Prepare features and train SS
-
-The [FoundationPose configuration](ss_multiobj_depth/configs/foundationpose.json) uses GT depth, `depth_embedding` voxel conditioning, global cross-attention, and rank-8 NoRA.
-It creates features under `outputs/ss_multiobj_depth/foundationpose/features` and preserves the saved training/test splits.
-It starts a new run with W&B online by default.
-Online logging requires W&B authentication.
-The setting `training.wandb_mode="disabled"` permits a local run without W&B.
-
-1. Prepare local features and encoded SS targets.
-
- ```bash
- python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/foundationpose.json
- ```
-
-2. Start training.
-
- ```bash
- python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/foundationpose.json
- ```
-
-This configuration needs no source archives, meshes, or additional dataset downloads.
-The `occlusion_object` variant additionally requires a matching GT occlusion cache.
-That cache requires mesh geometry during preparation and is absent from this FoundationPose bundle.
-A matching GT occlusion overlay can transfer separately without another download of the observation archives.
-New SLAT shape encoding and mesh-based evaluation also require geometry or separately transferred targets.
-Exact resume of an existing run requires its matching checkpoint, feature manifests, source hashes, and settings.
-
-## GT occlusion relations
-
-Separate archives under `precomputed_occlusion/` preserve the completed GT occlusion caches.
-The caches contain directed `[front, back]` relations from calibrated visible masks and posed GT mesh silhouettes.
-Each archive preserves the original matrices, completion records, and manifest bytes.
-
-| Dataset | Training views | Test views | Archives | Size, MB |
-| --- | ---: | ---: | ---: | ---: |
-| 3D-FRONT | 39,930 | 10,066 | 3 | 240.01 |
-| SAGE-10k | 17,456 | 1,952 | 3 | 103.45 |
-| Total | 57,386 | 12,018 | 6 | 343.46 |
+```bash
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss --dry-run
+```
-MB means decimal megabytes.
-The inventories at `precomputed_occlusion/<dataset>/index.json` record archive sizes and SHA-256 checksums.
-They also preserve the source policy and checksum of the matching extent manifest.
+The preview reads small indices without transferring data archives.
+Select one task for the server:
-### Download GT occlusion caches
+```bash
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-seg
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-shape
+```
-Restore the matching extent datasets before these overlays.
-Run these commands from the repository root.
+Select individual datasets with `--dataset`:
```bash
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \
- --dataset 3dfront --revision 88cdf8f0e880a33e7cafa580ee9722776f16aa28 --cleanup
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \
- --dataset sage --revision 88cdf8f0e880a33e7cafa580ee9722776f16aa28 --cleanup
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval --dataset picasso
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task eval --dataset picasso,messykitchen
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-seg --dataset foundationpose
```
-The commands restore `datasets/<dataset>/extent/point_cloud/occlusion/`.
-The downloader verifies each archive and refuses to replace different existing files.
-The dataset reader checks the extent manifest identity before reading GT relations.
-
-SS training with occlusion-aware object cross-attention reads these relations.
-SLAT shape tokens already have instance identities and require no occlusion matrix.
-Frozen image features and SLAT shape latents remain separate artifacts.
+PICASSO alone requires about 0.165 GB, including shared metadata.
+Evaluation metadata describes the full cohort. Data files cover only the selected datasets.
+The evaluation bundle contains no depth predictions. Depth-dependent models need their configured depth estimator.
+
+SS uses published native targets without another target encoding pass.
+Segmentation generates instance codes and image features during training.
+Use `preprocess.reproduction configure-shape` for online shape conditioning without a separate feature cache.
+FoundationPose shape targets remain unavailable.
+Explicit FoundationPose shape requests fail before any archive transfer.
+Custom configurations can require optional occlusion data or additional test observations.
+
+Commands without `--task` preserve the previous behavior and restore all training components.
+Task selection does not download model weights.
+Select exact checkpoint paths using the include patterns in the [checkpoint guide](HF_MODEL_CHECKPOINTS.md#download-checkpoints).
+
+## Mandatory files
+
+These paths refer to the Hugging Face repository root.
+Files are mandatory for the task specified in each row.
+The default command restores training files.
+The benchmark also requires the separate download with `--dataset evaluation`.
+
+| File or directory | Required task | Contents |
+| --- | --- | --- |
+| `training/index.json` | Training restoration | Component paths, sizes, monitoring counts, and source identities |
+| `training/observations/<dataset>/` | Training on the selected dataset | Archive index, sample NPZ files, calibration, object mappings, and scene voxel targets |
+| `training/ss/<dataset>/` | Direct SS training after target publication | Archive index, native SS latents, and codec provenance |
+| `training/shape/32/<dataset>/` | SLAT shape training where targets are available | Archive index and object shape targets with explicit exclusions |
+| `evaluation/index.json` | Benchmark restoration | Archive list and SHA-256 checksums |
+| `evaluation/metadata.tar` | Benchmark evaluation | Portable manifests, source selections, and dataset documentation |
+| `evaluation/picasso-*.tar` | Benchmark evaluation | All 100 PICASSO images, masks, previews, and GT meshes |
+| `evaluation/messykitchen-*.tar` | Benchmark evaluation | All 1,503 MessyKitchens images, masks, previews, and 100 shared GT meshes |
+| `evaluation/3dfront-*.tar` | Benchmark evaluation | The selected 1,000 3D-FRONT test images, masks, previews, and GT meshes |
+
+Restore every archive listed in the selected component's `index.json`.
+The complete evaluation bundle has 26 archives and requires about 23.4 GB.
+Task downloads can select only the archives required by individual evaluation datasets.
+Older checkouts also require the corresponding restore patch under `code/`.
+
+## Optional files
+
+These components support additional datasets, test views, and target generation.
+The mandatory evaluation bundle already includes its RGB images, masks, and GT meshes.
+Some SS configurations require the matching optional occlusion component.
+
+| File or directory | Purpose |
+| --- | --- |
+| `optional/held_out/<dataset>/` | Remaining test observations beyond the training monitors |
+| `optional/geometry/<dataset>/` | Source geometry for new targets or other evaluation sets |
+| `optional/occlusion/<dataset>/` | GT occlusion relations for applicable SS configurations |
+| `optional/evaluation/ycbv/` | Additional YCB-V observations and GT geometry |
+
+Optional components are separate downloads with `--optional`.
+Historical files under `_deprecated/20261020/` are obsolete and unnecessary for the current release.
+
+The default SS and segmentation datasets include 3D-FRONT, SAGE-10k, and FoundationPose.
+Its observation bundle supports SS and segmentation, but contains no shape targets or mesh geometry.
+
+## Restore on another server
+
+The dataset card records the required Git revision and restore patch.
+Apply that patch to the recorded project checkout before using the new commands.
+Install the project dependencies with its configured Python environment.
+```bash
+python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]'
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed
+```
-### Publish GT occlusion caches
+The command downloads the default datasets and their available SS and 32³ object shape targets.
+It excludes optional and deprecated folders.
+It verifies each archive before extraction and removes temporary archives after restoration.
+Use `--keep-archives` only when you need those temporary files.
+Temporary transfer files use `datasets/_deprecated/<dataset>/huggingface/`.
-Package the verified caches from the prepared extent roots:
+Select one dataset with `--dataset`:
```bash
-python -m preprocess.huggingface pack --artifact-kind gt-occlusion \
- --dataset 3dfront=datasets/3dfront/extent/point_cloud \
- --dataset sage=datasets/sage/extent/point_cloud \
- --output outputs/huggingface/gt_occlusion
-python -m preprocess.huggingface upload \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_occlusion \
- --dataset 3dfront --dataset sage --output outputs/huggingface/gt_occlusion
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset foundationpose
```
-Packaging checks every matrix checksum and its completion record.
-The uploader publishes complete inventories after it verifies all remote archives.
-
-## Additional SLAT targets
-
-The same repository provides separate 32³ SLAT targets under `precomputed_slat/`.
-The 3D-FRONT bundle covers 39,930 training views. The SAGE bundle covers 17,456 training views.
-Together, their ten archives contain 6.37 GiB of latent targets and metadata.
-The existing extent datasets supply the RGB images, masks, depth, and geometry.
+Add `--revision <Hub commit>` to retain one dataset snapshot.
+Restoration refuses to replace different existing data.
+Original extent manifests retain their bytes and SHA-256 identities.
+The separate `compact_training.json` identifies available views without changing those manifests.
+
+## Training inputs
+
+The observations contain every training view and the first 16 test views per dataset.
+These test views cover the existing eight-view and sixteen-view training monitors.
+The remaining test observations require an optional download.
+Training view order and source splits remain unchanged.
+
+Each sample NPZ already contains RGB, depth, visible labels, and complete per-object occupancy.
+The compact export excludes separate RGB, mask, depth, overlay, and per-view voxel copies.
+SS monitoring reads RGB and labels directly from the sample NPZ.
+Scene voxel targets remain available because SS preparation reads them.
+
+Shape targets preserve all object arrays, including coordinates, instance identities, and overlapping tokens.
+The export excludes combined scene latents because the current shape objective uses object targets.
+It records the three failed SAGE views as explicit exclusions.
+These exclusions match the existing object-mean shape experiment.
+SS and segmentation retain those views.
+
+Published SS components contain exact native latents with shape `8×16×16×16`.
+The standard download restores them to the cache paths used by online SS training.
+The [portable SS guide](preprocess/SS_TARGETS.md) describes direct training after restoration.
+Each component preserves its original cache files and manifest identity.
+The observation bundles provide the first 16 test views for training monitors.
+The HF card lists the components that completed publication.
+The download excludes trained weights.
+SS archives retain historical feature fields when their original cache manifests require them.
+Online SS training reads only the latent target from these tensor files.
+Run SS preparation only when compatible encoded targets are unavailable.
+Segmentation extracts image features during training.
+The `configure-shape` command creates an online configuration without a separate image-feature cache.
+It preserves the selected preset's model and optimization settings.
+The [SLAT preparation guide](preprocess/slat/HUGGING_FACE.md) describes both shape options.
+
+## Optional downloads
+
+Restore observations before adding geometry, occlusion, or remaining test views.
+The YCB-V evaluation bundle includes its own observations and geometry.
+Select each optional component explicitly:
```bash
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset 3dfront --cleanup
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset sage --cleanup
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --optional geometry
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset 3dfront --optional occlusion
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset sage --optional held-out
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset ycbv --optional evaluation
```
-These commands restore `datasets/<dataset>/slat/32/targets/`.
-The snapshots retain partial scene encoding and three failed SAGE object targets.
-Frozen image features require separate preparation.
-See the [SLAT snapshot specification](preprocess/slat/HUGGING_FACE.md) for source revisions, coverage, and preparation steps.
-The [local restoration report](reports/huggingface_additional_slat_targets_20261017.md) records downloaded snapshots and verification results.
+Geometry supports mesh scoring and shape encoding at other resolutions.
+GT occlusion relations support SS configurations with occlusion-aware object attention.
+The current shape tokens already identify their objects and require no GT occlusion matrix.
+The optional test overlay expands the available views without replacing training inputs.
-## Publication
+## Frozen evaluation
+
+The local dataset resides under `datasets/evaluation/`.
+It contains 100 PICASSO images, 1,503 MessyKitchens images, and 1,000 3D-FRONT test views.
+The 3D-FRONT selection uses seed 42 and samples views without replacement.
+Each MessyKitchens scene has one shared GT mesh export.
+Every view references its mesh through a relative manifest path.
+Archive members contain regular files, so restoration requires no symbolic links.
-The reusable publication commands produce approximately 1 GiB archive shards
-under `outputs/`, without modifying the source datasets:
+The benchmark requires this evaluation dataset.
+Download the evaluation bundle:
```bash
-python -m preprocess.huggingface pack \
- --dataset ycbv=datasets/ycbv/extent/point_cloud \
- --dataset 3dfront=datasets/3dfront/extent/point_cloud \
- --output outputs/huggingface/preprocessed
-python -m preprocess.huggingface catalog \
- --dataset 3dfront=datasets/3dfront/extent/point_cloud \
- --dataset ycbv=datasets/ycbv/extent/point_cloud \
- --repo cubec/PartProbe3D-preprocessed --output outputs/huggingface/preprocessed
-python -m preprocess.huggingface upload \
- --dataset 3dfront --dataset ycbv --repo cubec/PartProbe3D-preprocessed \
- --output outputs/huggingface/preprocessed --follow
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --dataset evaluation
```
-`--follow` uploads finished shards while packaging continues. Repeating the
-commands reuses verified packages and skips matching remote archives. The publisher uploads the complete archive index after it uploads all archives.
-Use `upload --workers 16` to request 16 concurrent archive transfers.
-The default retains the Hugging Face client's transfer settings.
-The initial run logs are `outputs/huggingface/preprocessed/pack.log`,
-`upload-3dfront.log`, and `upload-ycbv.log`.
+The dataset card includes the loader patch for checkouts that lack `dataloader/frozen.py`.
+Use `--dataset frozen` with the corresponding `evaluation/configs/*_frozen.json` file.
+Original selections remain in `source_selection.json` for provenance.
+The loader reads the exported GLB geometry with its stored float32 vertices.
+RGB pixels and mask labels retain their original selection checksums.
+These bundles contain no depth maps, model weights, or image features.
-For one job that packages, uploads, retries transient Hub failures and updates
-the public dataset card, use:
+Create the local dataset and publish its archives with these commands:
```bash
-python -m preprocess.huggingface publish \
- --dataset ycbv=datasets/ycbv/extent/point_cloud \
- --dataset 3dfront=datasets/3dfront/extent/point_cloud \
- --repo cubec/PartProbe3D-preprocessed --output outputs/huggingface/preprocessed
+python -m preprocess.evaluation store --source outputs/evaluation/full_dataset_20261021
+python -m preprocess.evaluation publish --repo cubec/PartProbe3D-preprocessed
```
-The job records `running`, `complete`, or `failed` in
-`outputs/huggingface/preprocessed/publish-status.json`. The detached server run
-records its process ID in `publish.pid` and writes `publish.log` in that folder.
+## Deprecated uploads
-For large datasets, `publish --cleanup` creates, uploads and verifies one shard
-before removing it and creating the next.
-The command preserves original datasets, archive inventories, previews, transfer logs, and remote archives.
-Failures retain the current unverified shard. Repeating the command verifies
-existing remote archives and resumes the upload.
-The publisher can rebuild removed staging shards from the unchanged source. Existing dataset catalogs remain in the repo:
+The previous layout remains under `_deprecated/20261020/`.
+The original [snapshot](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/tree/d13e577a7e71291ed94fa40e4297f54106577fbd) also remains accessible by revision.
+Default downloads never select these paths.
+An unfiltered Hugging Face snapshot download still includes every folder.
+Use the project downloader to avoid optional and deprecated data.
+
+## Publication
+
+Run this command from the project root:
```bash
-python -m preprocess.huggingface publish \
- --dataset sage=datasets/sage/extent/point_cloud \
+python -m preprocess.reproduction publish \
--repo cubec/PartProbe3D-preprocessed \
- --output outputs/huggingface/preprocessed --cleanup
+ --output outputs/huggingface/reproduction \
+ --dataset 3dfront --dataset sage --dataset foundationpose
```
-## SS targets for masked objects
-
-The prepared dataset already contains complete per-object occupancy and the prompt mapping.
-SS target generation uses the saved labels and prompt mapping.
-It creates new local targets and encoded latents.
-The published dataset retains its existing files. Existing local copies need no additional dataset download.
-
-See [SS target regeneration and transfer](ss_multiobj_depth/README.md#regenerate-targets-for-masked-objects) for target overlays and reuse of existing conditioning caches.
+Publication preserves source datasets and limits temporary archive storage through verified upload batches.
+Repetition reuses remote archives with matching SHA-256 identities.
+The publisher retains unverified files after a failure.
diff --git a/dataloader/dataset.py b/dataloader/dataset.py
index 08f0d62..cdd79fd 100644
--- a/dataloader/dataset.py
+++ b/dataloader/dataset.py
@@ -110,6 +110,18 @@ class ViewDataset:
if not self.manifest["complete"] and not allow_incomplete:
raise ValueError("Conversion is incomplete; do not use partial data for training")
self.views = [row for row in self.manifest["views"] if split is None or row["split"] == split]
+ selection_path = self.root / 'compact_training.json'
+ if selection_path.exists():
+ from utils.hashing import sha256
+ selection = json.loads(selection_path.read_text())
+ ids = selection.get('view_ids', [])
+ if (selection.get('schema') != 'partprobe3d.compact-training.v1'
+ or selection.get('source_manifest_sha256') != sha256(self.root / 'manifest.json')
+ or len(ids) != len(set(ids))
+ or set(ids) - {row['id'] for row in self.manifest['views']}):
+ raise ValueError('Compact training selection differs from the source manifest')
+ available = set(ids)
+ self.views = [row for row in self.views if row['id'] in available]
def __len__(self):
return len(self.views)
diff --git a/dataloader/extent.py b/dataloader/extent.py
index d13d628..245f83e 100644
--- a/dataloader/extent.py
+++ b/dataloader/extent.py
@@ -31,6 +31,10 @@ class ExtentLoader(BaseDataLoader):
from PIL import Image
index = self.dataset._index(index)
row = self.rows[index]
+ if (self.root / 'compact_training.json').exists():
+ # Load only these two NPZ members. Calibration and depth stay unread.
+ with np.load(self.root / row['sample'], allow_pickle=False) as arrays:
+ return arrays['rgb'], arrays['image_labels'].astype(np.int32) + 1
with Image.open(self.root / row["rgb"]) as image:
rgb = np.array(image.convert("RGB"))
objects = self.dataset.source.objects(self.dataset.indices[index])["prompts"]
diff --git a/models/voxel_condition.py b/models/voxel_condition.py
index 71c0708..d0192fd 100644
--- a/models/voxel_condition.py
+++ b/models/voxel_condition.py
@@ -14,6 +14,26 @@ LORA_IMAGE_PROJECTION_FORMAT = 'lora-image-projection-v1'
FROZEN_IMAGE_PROJECTION_FORMAT = 'frozen-image-projection-v1'
+def voxel_adapter_settings(settings, adapters=None):
+ """Resolve new LoRA defaults and retain historical checkpoint semantics."""
+ settings = dict(settings)
+ recorded_method = adapters.get('backbone_adapter_method', 'nora') if adapters is not None else 'lora'
+ settings.setdefault('adapter_method', recorded_method)
+ if adapters is not None and settings['adapter_method'] != recorded_method:
+ raise ValueError('Checkpoint backbone adapter method differs from model settings')
+ if settings['adapter_method'] not in ('lora', 'nora'):
+ raise ValueError('adapter_method must be lora or nora')
+ recorded_image = ({NORA_IMAGE_PROJECTION_FORMAT: 'nora', LORA_IMAGE_PROJECTION_FORMAT: 'lora',
+ FROZEN_IMAGE_PROJECTION_FORMAT: 'frozen'}.get(adapters.get('image_projection_format'), 'full')
+ if adapters is not None else None)
+ settings.setdefault('image_projection_adaptation', recorded_image or
+ (settings['adapter_method'] if settings.get('rank', 0) else 'full'))
+ if recorded_image is not None and settings['image_projection_adaptation'] != recorded_image:
+ raise ValueError('Checkpoint image projection adaptation differs from model settings')
+ image_projection_adaptation(settings)
+ return settings
+
+
def image_projection_adaptation(settings):
"""Validate the shared image projection policy for SS and SLAT models."""
mode = settings.get('image_projection_adaptation', 'full')
@@ -405,13 +425,16 @@ def install_voxel_adapters(flow, *, depth_channels=128, rank=8, alpha=8.,
voxel_condition_mode='additive', voxel_condition_hidden_channels=None,
mask_channels=None, object_context=False, object_aggregation=False,
region_image_channels=2048, coverage_conditioned=False,
- image_projection_adaptation='full'):
+ image_projection_adaptation='full', adapter_method='lora'):
"""Train full image projections and new conditions; adapt the remaining frozen backbone."""
voxel_condition_width(voxel_condition_mode, voxel_condition_hidden_channels)
+ if adapter_method not in ('lora', 'nora'):
+ raise ValueError('adapter_method must be lora or nora')
if (getattr(flow, 'image_attn_mode', None) != 'proj' or not flow.blocks
or any(not hasattr(block.cross_attn, 'proj_linear') for block in flow.blocks)):
raise ValueError('Expected unwrapped native Pixal3D proj blocks')
flow.requires_grad_(False)
+ flow.voxel_adapter_method = adapter_method
if object_aggregation:
resize_image_projection(flow, region_image_channels)
for block in flow.blocks:
@@ -421,7 +444,7 @@ def install_voxel_adapters(flow, *, depth_channels=128, rank=8, alpha=8.,
coverage_conditioned=coverage_conditioned)
block.use_checkpoint = True
if rank:
- install_lora(flow, rank=rank, alpha=alpha, method='nora')
+ install_lora(flow, rank=rank, alpha=alpha, method=adapter_method)
configure_image_projections(flow, {'image_projection_adaptation': image_projection_adaptation,
'rank': rank, 'alpha': alpha})
return flow
@@ -431,10 +454,14 @@ def adapter_state(flow, conditioner):
return {'flow': {name: parameter.detach().cpu() for name, parameter in flow.named_parameters()
if parameter.requires_grad},
'image_projection_format': image_projection_format(flow),
+ 'backbone_adapter_method': getattr(flow, 'voxel_adapter_method', 'nora'),
'conditioner': {name: value.detach().cpu() for name, value in conditioner.state_dict().items()}}
def load_adapter_state(flow, conditioner, state, *, allow_legacy=True):
+ if (any(isinstance(layer, LoRALinear) for layer in flow.modules())
+ and getattr(flow, 'voxel_adapter_method', 'nora') != state.get('backbone_adapter_method', 'nora')):
+ raise ValueError('Checkpoint backbone adapter method differs from this model')
parameters = dict(flow.named_parameters())
weights = {}
for name, value in state['flow'].items():
diff --git a/preprocess/SS_TARGETS.md b/preprocess/SS_TARGETS.md
new file mode 100644
index 0000000..b75a878
--- /dev/null
+++ b/preprocess/SS_TARGETS.md
@@ -0,0 +1,79 @@
+# Portable SS targets
+
+The SS task download includes observations and native SS latents for 3D-FRONT, SAGE-10k, and FoundationPose.
+The publisher adds each dataset after all its target archives pass remote checksum checks.
+The [dataset card](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed) lists the available SS components.
+
+| Data | Purpose | Offline work after restoration |
+| --- | --- | --- |
+| Observations and voxel labels | Calibrated inputs and occupancy supervision | None |
+| SS latents | Native SS flow targets, shape `8×16×16×16` | None |
+
+Image encoders compute features during online training.
+This avoids separate image caches while preserving current conditioning.
+Model weights and software dependencies remain separate requirements.
+
+## Restore and train
+
+Use the project revision recorded in the HF card.
+Download only the SS training components:
+
+```bash
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task ss
+```
+
+This command selects all three datasets, including FoundationPose.
+It excludes shape targets and evaluation data.
+Add `--dataset foundationpose` to select one dataset.
+Add `--dry-run` to preview components and transfer sizes.
+The restore command checks archive hashes and preserves original observation manifests.
+It writes SS caches to the paths used by the default training configuration.
+
+Start SS training with the desired device configuration:
+
+```bash
+envs/sam3d/bin/python -m ss_multiobj_depth.train \
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json
+```
+
+The encoded targets remove the SS preparation command from this procedure.
+The default uses online conditioning, a real batch of 16, and one accumulation step.
+Use a fresh cache destination when existing files differ from the selected HF release.
+
+## Publish completed targets
+
+Run this command after native SS target preparation:
+
+```bash
+python -m preprocess.ss_targets \
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json \
+ --output outputs/huggingface/ss_targets
+```
+
+Add `--follow` to wait for each source cache to become complete.
+Publication streams the completed cache through the archive writer.
+The writer checks source file hashes during that pass.
+Publication uses CPU operations and leaves training processes active.
+It preserves every view in the original cache.
+The export preserves the original files and manifest bytes.
+It also retains historical cached features when the original manifest requires them.
+Online training computes its image features from the current configuration.
+It reads only the saved SS latent from each target tensor file.
+
+Each dataset uses `training/ss/<dataset>/` on HF.
+The publisher registers its component in `training/index.json` after archive verification.
+The task downloader reads this inventory and selects observations plus SS targets.
+Later observation publications retain SS components when their dataset identities still match.
+
+## Compatibility checks
+
+The export retains the target scope, observation hashes, and frozen codec identities.
+The export retains the original model hashes and dataset provenance.
+The training loader checks the dataset manifest and model weights against its configuration.
+The cache also retains any additional test targets from the original preparation.
+The observation download provides the monitoring views used by training.
+Original manifest identities support exact checkpoint resume with matching code, configuration, and model weights.
+
+The relocation test restores real archive files into a separate directory.
+It removes the original observations and cache before reading the restored training data.
+It checks latent equality and rejects changed targets, incomplete caches, and mismatched datasets.
diff --git a/preprocess/huggingface.py b/preprocess/huggingface.py
index 60aafa7..6afd3ce 100644
--- a/preprocess/huggingface.py
+++ b/preprocess/huggingface.py
@@ -8,6 +8,7 @@ import os
from pathlib import Path, PurePosixPath
import re
import shutil
+import stat
import tarfile
import tempfile
import time
@@ -90,8 +91,13 @@ class _HashWriter:
return self.stream.write(data)
-def _archive(path, files, source, destination, previous=None):
- records = [(str(p.relative_to(source)), p.stat().st_size, p.stat().st_mtime_ns) for p in files]
+def _archive(path, files, source, destination, previous=None, *, checksums=None):
+ records = []
+ for file in files:
+ original = file.stat(follow_symlinks=False)
+ if not stat.S_ISREG(original.st_mode):
+ raise ValueError(f'Archive sources must be regular files: {file}')
+ records.append((str(file.relative_to(source)), original.st_size, original.st_mtime_ns))
identity = hashlib.sha256(json.dumps(records).encode()).hexdigest()
if previous and previous.get('identity') == identity and path.is_file():
if path.stat().st_size == previous['bytes'] and sha256(path) == previous['sha256']:
@@ -101,18 +107,36 @@ def _archive(path, files, source, destination, previous=None):
try:
with temporary.open('wb') as stream:
writer = _HashWriter(stream)
- with tarfile.open(fileobj=writer, mode='w|', format=tarfile.USTAR_FORMAT) as archive:
+ with tarfile.open(fileobj=writer, mode='w|', format=tarfile.USTAR_FORMAT,
+ bufsize=256 * 1024, copybufsize=1024**2) as archive:
for file, (name, size, mtime) in zip(files, records):
- info = archive.gettarinfo(str(file), arcname=str(destination / name))
- if not info.isfile() or info.size != size or file.stat().st_mtime_ns != mtime:
- raise ValueError(f'Source changed during packaging: {file}')
+ info = tarfile.TarInfo(str(destination / name))
+ info.size = size
info.uid = info.gid = info.mtime = 0
info.uname = info.gname = ''
info.mode = 0o644
with file.open('rb') as data:
- archive.addfile(info, data)
- if file.stat().st_mtime_ns != mtime or file.stat().st_size != size:
- raise ValueError(f'Source changed during packaging: {file}')
+ opened = os.fstat(data.fileno())
+ if opened.st_size != size or opened.st_mtime_ns != mtime:
+ raise ValueError(f'Source changed during packaging: {file}')
+ if checksums and file in checksums:
+ class CheckedReader:
+ def __init__(self, stream):
+ self.stream, self.digest = stream, hashlib.sha256()
+
+ def read(self, size=-1):
+ block = self.stream.read(size)
+ self.digest.update(block)
+ return block
+ checked = CheckedReader(data)
+ archive.addfile(info, checked)
+ if checked.digest.hexdigest() != checksums[file]:
+ raise ValueError(f'Source checksum changed during packaging: {file}')
+ else:
+ archive.addfile(info, data)
+ finished = os.fstat(data.fileno())
+ if finished.st_mtime_ns != mtime or finished.st_size != size:
+ raise ValueError(f'Source changed during packaging: {file}')
stream.flush()
os.fsync(stream.fileno())
digest = writer.digest.hexdigest()
@@ -370,15 +394,15 @@ def extract(index, folder, destination):
if index.get('schema') != SCHEMA or not index.get('complete'):
raise ValueError('A complete archive index is required')
folder, destination = Path(folder), Path(destination).resolve()
- prefix = _relative(index['destination'])
+ prefix = _relative(index.get('archive_prefix', index['destination']))
restored_prefix = (_slat_destination(index['name'], index['resolution'])
- if index.get('artifact_kind') == 'slat-shape-targets' else prefix)
+ if index.get('artifact_kind') == 'slat-shape-targets' else _relative(index['destination']))
# Publish the original complete manifest only after restoring its artifacts.
for item in sorted(index['archives'], key=lambda item: item['file'] == 'metadata.tar'):
path = folder / _relative(item['file'])
if path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']:
raise ValueError(f'Archive checksum mismatch: {path}')
- with tarfile.open(path, 'r|') as archive:
+ with tarfile.open(path, 'r|', bufsize=256 * 1024) as archive:
for member in archive:
relative = _relative(member.name)
if not relative.is_relative_to(prefix) or not member.isfile():
@@ -401,6 +425,9 @@ def extract(index, folder, destination):
finally:
temporary.unlink(missing_ok=True)
print(f"RESTORED {index['name']}/{item['file']}", flush=True)
+ if index.get('artifact_kind') in ('compact-training', 'held-out-observations'):
+ from preprocess.reproduction import refresh_selection
+ refresh_selection(destination / restored_prefix)
return destination / restored_prefix
@@ -523,25 +550,43 @@ def upload(output, repo, names, *, follow=False, packing=None, update_card=False
print(f'UPLOADED {name}: https://huggingface.co/datasets/{repo}', flush=True)
-def download(repo, name, destination, revision, *, cleanup=False, bundle_root='bundles'):
+def download(repo, name, destination, revision, *, cleanup=None, bundle_root=None, archive_files=None):
+ if name == 'evaluation' and bundle_root is None:
+ bundle_root = ''
+ if bundle_root is None:
+ from preprocess.reproduction import download_training
+ return download_training(repo, name, destination, revision, cleanup=cleanup is not False)
from huggingface_hub import HfApi, hf_hub_download
from utils.huggingface_download import download_huggingface_file
# Resolve main once so all archives and the index belong to one snapshot.
revision = HfApi().dataset_info(repo, revision=revision).sha
- bundle_root = str(_relative(bundle_root))
+ bundle_root = str(_relative(bundle_root)) if bundle_root else ''
+ component = str(PurePosixPath(bundle_root) / _relative(name))
destination = Path(destination).resolve()
- cache = destination / 'datasets' / name / 'archives' / 'huggingface'
- index_path = hf_hub_download(repo, f'{bundle_root}/{name}/index.json', repo_type='dataset',
+ # Keep active dataset folders free of transfer archives. Retain the legacy
+ # cache path only when an explicit historical component needs resume.
+ cache = (destination / 'datasets' / '_deprecated' / name / 'huggingface'
+ if component.split('/')[0] in ('training', 'optional', 'evaluation')
+ else destination / 'datasets' / name / 'archives' / 'huggingface')
+ index_path = hf_hub_download(repo, f'{component}/index.json', repo_type='dataset',
revision=revision, local_dir=cache)
index = _json(index_path)
if index.get('name') != name or not index.get('complete'):
raise ValueError('Requested dataset has no complete archive index')
- folder = cache / bundle_root / name
+ archives = index['archives']
+ if archive_files is not None:
+ selected = set(archive_files)
+ available = {item['file'] for item in archives}
+ if not selected or not selected.issubset(available) or 'metadata.tar' not in selected:
+ raise ValueError('Select existing archives and include metadata.tar')
+ archives = [item for item in archives if item['file'] in selected]
+ folder = cache / component
status_path = folder / 'download-status.json'
status = {'state': 'running', 'pid': os.getpid(), 'repo': repo, 'revision': revision,
'dataset': name, 'bundle_root': bundle_root, 'started_unix': time.time(),
- 'archives_total': len(index['archives']), 'archives_restored': 0,
- 'archive_bytes_total': sum(item['bytes'] for item in index['archives']),
+ 'archives_total': len(archives), 'archives_restored': 0,
+ 'selected_archives': [item['file'] for item in archives],
+ 'archive_bytes_total': sum(item['bytes'] for item in archives),
'archive_bytes_restored': 0, 'file_workers': 1, 'parallel_ranges': False}
def save():
@@ -554,11 +599,11 @@ def download(repo, name, destination, revision, *, cleanup=False, bundle_root='b
save()
try:
- for item in sorted(index['archives'], key=lambda item: item['file'] == 'metadata.tar'):
+ for item in sorted(archives, key=lambda item: item['file'] == 'metadata.tar'):
status.update(state='downloading', current_archive=item['file'], active_transfer=None)
save()
archive = download_huggingface_file(
- repo, f'{bundle_root}/{name}/{item["file"]}', repo_type='dataset',
+ repo, f'{component}/{item["file"]}', repo_type='dataset',
revision=revision, local_dir=cache, expected_size=item['bytes'],
expected_sha256=item['sha256'], progress=progress)
status['state'] = 'restoring'
@@ -820,12 +865,19 @@ def main():
help='Concurrent archive transfers. Default: Hugging Face client setting')
restoring = commands.add_parser('download')
restoring.add_argument('--repo', required=True)
- restoring.add_argument('--dataset', required=True)
+ restoring.add_argument('--dataset', default='all', help='Training dataset name, or evaluation for the required benchmark')
restoring.add_argument('--destination', type=Path, default=Path('.'))
restoring.add_argument('--revision', default='main')
- restoring.add_argument('--bundle-root', default='bundles')
+ restoring.add_argument('--task', choices=('eval', 'ss', 'slat-seg', 'slat-shape', 'all-training'),
+ help='Restore only the data required by this task')
+ restoring.add_argument('--dry-run', action='store_true', help='Print the task plan without downloading archives')
+ restoring.add_argument('--bundle-root', default=None,
+ help='Explicit component root. Default: compact training data and 32-cubed shape targets')
restoring.add_argument('--cleanup', action='store_true',
help='Restore one archive at a time and remove it after successful extraction')
+ restoring.add_argument('--keep-archives', action='store_true', help='Retain temporary archives after restoration')
+ restoring.add_argument('--optional', choices=('geometry', 'occlusion', 'held-out', 'evaluation'),
+ help='Download only this optional component for the selected dataset')
describing = commands.add_parser('catalog')
describing.add_argument('--dataset', action='append', required=True, metavar='NAME=EXTENT_ROOT')
describing.add_argument('--output', type=Path, required=True)
@@ -853,8 +905,23 @@ def main():
publish(args.output, dict(dataset.split('=', 1) for dataset in args.dataset), args.repo,
cleanup=args.cleanup)
else:
- download(args.repo, args.dataset, args.destination, args.revision, cleanup=args.cleanup,
- bundle_root=args.bundle_root)
+ if args.task:
+ if args.optional or args.bundle_root is not None:
+ parser.error('--task cannot be combined with --optional or --bundle-root')
+ from preprocess.tasks import download_task
+ download_task(args.repo, args.task, args.dataset, args.destination, args.revision,
+ cleanup=not args.keep_archives, dry_run=args.dry_run)
+ return
+ if args.dry_run:
+ parser.error('--dry-run requires --task')
+ if args.optional and args.bundle_root:
+ parser.error('--optional and --bundle-root cannot be combined')
+ bundle_root = f'optional/{args.optional.replace("-", "_")}' if args.optional else args.bundle_root
+ if args.optional and args.dataset == 'all':
+ parser.error('Select one dataset with --dataset for an optional download')
+ cleanup = not args.keep_archives if bundle_root is None or args.optional else args.cleanup
+ download(args.repo, args.dataset, args.destination, args.revision, cleanup=cleanup,
+ bundle_root=bundle_root)
if __name__ == '__main__':
diff --git a/preprocess/reproduction.py b/preprocess/reproduction.py
new file mode 100644
index 0000000..34eaed4
--- /dev/null
+++ b/preprocess/reproduction.py
@@ -0,0 +1,690 @@
+"""Publish compact training data and explicit optional components on Hugging Face."""
+import argparse
+from collections import Counter, defaultdict
+from concurrent.futures import ThreadPoolExecutor
+from copy import deepcopy
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+
+from preprocess.huggingface import SCHEMA, _archive, _json, _relative, _retry
+from preprocess.storage import atomic_json
+from utils.hashing import sha256
+
+
+RECIPE_SCHEMA = 'partprobe3d.reproduction.v1'
+COMPACT_SCHEMA = 'partprobe3d.compact-training.v1'
+DEFAULT_REPO = 'cubec/PartProbe3D-preprocessed'
+DEFAULT_DATASETS = ('3dfront', 'sage')
+LEGACY_PREFIX = '_deprecated/20261020'
+LEGACY_REVISION = 'd13e577a7e71291ed94fa40e4297f54106577fbd'
+
+
+def refresh_selection(root):
+ """Identify restored views without changing the original manifest bytes."""
+ root = Path(root)
+ path = root / 'manifest.json'
+ if not path.exists():
+ return
+ manifest = _json(path)
+ rows = [row for row in manifest['views']
+ if all((root / row[key]).is_file() for key in ('sample', 'camera', 'scene_gt', 'object_table'))]
+ atomic_json(root / 'compact_training.json', {
+ 'schema': COMPACT_SCHEMA, 'source_manifest_sha256': sha256(path),
+ 'view_ids': [row['id'] for row in rows],
+ 'counts': dict(Counter(row['split'] for row in rows)),
+ 'geometry_included': False, 'observations': 'RGB, depth and labels in sample NPZ files'})
+
+
+def stage_observations(source, staged, *, monitor_views=16):
+ """Index original training files for direct streaming without another dataset copy."""
+ source, staged = Path(source).resolve(), Path(staged).resolve()
+ manifest = _json(source / 'manifest.json')
+ if (not manifest.get('complete') or len(manifest['views']) != manifest['expected_views']
+ or monitor_views < 1):
+ raise ValueError('A complete source and a positive monitoring count are required')
+ original_hash = sha256(source / 'manifest.json')
+
+ def scene_groups(groups):
+ # Follow the original scene archive order to avoid random HDD seeks.
+ scenes = {source / row['sample']: row['scene'] for row in manifest['views']}
+ paths_by_scene, counts = defaultdict(set), Counter()
+ for label, paths, count in groups:
+ scene = next(scenes[path] for path in paths if path in scenes)
+ paths_by_scene[label, scene].update(paths)
+ counts[label, scene] += count
+ return [(label, sorted(paths), counts[label, scene])
+ for (label, scene), paths in sorted(paths_by_scene.items())]
+ staged.mkdir(parents=True, exist_ok=True)
+ inventory_path = staged / 'stream_inventory.json'
+ if inventory_path.exists():
+ saved = _json(inventory_path)
+ if (saved.get('source_manifest_sha256') == original_hash and saved.get('monitor_views') == monitor_views
+ and saved.get('source_root') == str(source)):
+ decode = lambda groups: [(label, [source / _relative(path) for path in paths], count)
+ for label, paths, count in groups]
+ return (manifest, [source / _relative(path) for path in saved['metadata']],
+ scene_groups(decode(saved['core'])), scene_groups(decode(saved['held_out'])),
+ {source / _relative(path): digest for path, digest in saved['checksums'].items()})
+ metadata = [source / name for name in ('manifest.json', 'conversion_policy.json') if (source / name).exists()]
+ core, held_out, checksums = [], [], {}
+ monitor_ids = {row['id'] for row in [row for row in manifest['views'] if row['split'] != 'train'][:monitor_views]}
+
+ def inspect_view(row):
+ selected = row['split'] == 'train' or row['id'] in monitor_ids
+ label = 'train' if row['split'] == 'train' else 'monitor' if selected else 'held-out'
+ folder = source / _relative(row['view_directory'])
+ marker = folder / 'complete.json'
+ stamp = _json(marker)
+ if stamp['row']['id'] != row['id']:
+ raise ValueError(f'Completion record differs from the source view: {row["id"]}')
+ paths = {source / _relative(row[key]) for key in ('sample', 'camera', 'scene_gt', 'object_table')}
+ paths.update((folder / 'objects.json', marker))
+ expected = {source / row[key]: stamp['sha256'][str(Path(row[key]).relative_to(row['view_directory']))]
+ for key in ('sample', 'camera')}
+ expected[folder / 'objects.json'] = stamp['sha256']['objects.json']
+ target_marker = (source / row['scene_gt']).with_name('complete.json')
+ if target_marker.exists():
+ paths.add(target_marker)
+ target_digest = _json(target_marker).get('sha256')
+ if isinstance(target_digest, str):
+ expected[source / row['scene_gt']] = target_digest
+ return selected, (label, sorted(paths), 1), expected
+
+ with ThreadPoolExecutor(max_workers=16) as pool:
+ for number, (selected, group, expected) in enumerate(pool.map(inspect_view, manifest['views']), 1):
+ (core if selected else held_out).append(group)
+ checksums.update(expected)
+ if number % 5000 == 0:
+ print(f'INDEXED {manifest["dataset"]}: {number}/{len(manifest["views"])} views', flush=True)
+ core, held_out = scene_groups(core), scene_groups(held_out)
+ if sha256(source / 'manifest.json') != original_hash:
+ raise ValueError('Source manifest changed during observation indexing')
+ encode = lambda groups: [(label, [str(path.relative_to(source)) for path in paths], count)
+ for label, paths, count in groups]
+ atomic_json(inventory_path, {'source_manifest_sha256': original_hash, 'source_root': str(source),
+ 'monitor_views': monitor_views, 'metadata': [str(path.relative_to(source)) for path in metadata],
+ 'core': encode(core), 'held_out': encode(held_out),
+ 'checksums': {str(path.relative_to(source)): digest for path, digest in checksums.items()}})
+ return manifest, metadata, core, held_out, checksums
+
+
+def stage_shape(source, staged):
+ """Preserve object arrays and record existing failures as explicit exclusions."""
+ import numpy as np
+ from slat_multiobj_shape.storage import object_sha256, read_view_targets
+
+ source, staged = Path(source).resolve(), Path(staged).resolve()
+ original = _json(source / 'manifest.json')
+ source_hash = sha256(source / 'manifest.json')
+ receipt = staged / 'export.json'
+ if receipt.exists() and _json(receipt).get('source_manifest_sha256') == source_hash:
+ manifest = _json(staged / 'manifest.json')
+ else:
+ manifest = deepcopy(original)
+ manifest.update(entries={}, target_scope='objects', phase='objects', phase_complete=True,
+ complete=False, excluded_views=sorted(set(original.get('excluded_views', [])) | {
+ key for key, row in original['entries'].items() if row.get('failed_objects')}))
+ manifest['export'] = {'source_manifest_sha256': source_hash, 'scene_latents_included': False,
+ 'object_arrays_unchanged': True}
+ def export_view(item):
+ key, row = item
+ path = source / _relative(row['file'])
+ if sha256(path) != row['sha256']:
+ raise ValueError(f'Original shape target checksum changed: {key}')
+ arrays = read_view_targets(path)
+ identity = object_sha256(arrays)
+ arrays.update(scene_coords=np.empty((0, 3), np.uint8), scene_feats=np.empty((0, 32), np.float16),
+ scene_status=np.array('pending'), scene_seconds=np.array(0.),
+ scene_dual_voxels=np.array(0), scene_error=np.array(''))
+ output = staged / _relative(row['file'])
+ output.parent.mkdir(parents=True, exist_ok=True)
+ np.savez_compressed(output, **arrays)
+ if object_sha256(read_view_targets(output)) != identity:
+ raise ValueError(f'Object shape arrays changed during export: {key}')
+ entry = {**row, 'sha256': sha256(output), 'object_sha256': identity,
+ 'scene_status': 'pending', 'scene_latent_cells': 0, 'scene_seconds': 0.}
+ atomic_json(output.with_suffix('.complete.json'), entry)
+ return key, entry
+ selected = sorted(((key, row) for key, row in original['entries'].items()
+ if key not in manifest['excluded_views']), key=lambda item: (item[1]['scene'], item[0]))
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ for number, (key, entry) in enumerate(pool.map(export_view, selected), 1):
+ manifest['entries'][key] = entry
+ if number % 5000 == 0:
+ print(f'SHAPE {source.parent.parent.parent.name}: {number}/{len(selected)}', flush=True)
+ if sha256(source / 'manifest.json') != source_hash:
+ raise ValueError('Source manifest changed during shape export')
+ atomic_json(staged / 'manifest.json', manifest)
+ atomic_json(receipt, manifest['export'])
+ groups, checksums = [], {}
+ for key, row in manifest['entries'].items():
+ path = staged / _relative(row['file'])
+ groups.append(('train', [path, path.with_suffix('.complete.json')], 1))
+ checksums[path] = row['sha256']
+ return manifest, [staged / 'manifest.json', receipt], groups, checksums
+
+
+def package(root, output, component, name, *, destination, kind, metadata, groups,
+ details=None, checksums=None, shard_bytes=1024**3, publisher=None):
+ """Write deterministic shards and publish them with bounded temporary storage."""
+ root, output = Path(root).resolve(), Path(output).resolve()
+ folder = output / (_relative(component) if component else Path()) / name
+ folder.mkdir(parents=True, exist_ok=True)
+ remote_root = str(folder.relative_to(output))
+ path = folder / 'index.json'
+ old = _json(path) if path.exists() else {}
+ identity = {'destination': str(destination), 'artifact_kind': kind, **(details or {})}
+ if old and any(old.get(key) != value for key, value in identity.items()):
+ raise ValueError(f'Package source changed. Select another output: {component}/{name}')
+ previous = {row['file']: row for row in old.get('archives', [])}
+ index = {'schema': SCHEMA, 'name': name, 'complete': False, **identity, 'archives': []}
+ if 'archive_prefix' in old:
+ index['archive_prefix'] = old['archive_prefix']
+ atomic_json(path, index)
+
+ def save(label, files, views):
+ filename = label + '.tar'
+ files = sorted(set(files))
+ old_record = previous.get(filename)
+ remote_path = f'{remote_root}/{filename}'
+ reusable = False
+ if old_record and publisher and publisher.matches(remote_path, old_record):
+ records = []
+ for file in files:
+ saved = file.stat()
+ records.append((str(file.relative_to(root)), saved.st_size, saved.st_mtime_ns))
+ reusable = old_record.get('identity') == hashlib.sha256(json.dumps(records).encode()).hexdigest()
+ if reusable:
+ record = old_record
+ else:
+ record = _archive(folder / filename, files, root,
+ Path(index.get('archive_prefix', destination)), old_record, checksums=checksums)
+ record['views'] = views
+ index['archives'].append(record)
+ atomic_json(path, index)
+ print(f'PACKED {remote_path}: {record["bytes"]/1e9:.3f} GB, {views} views', flush=True)
+ if publisher:
+ publisher.ready(remote_path, folder / filename, record)
+
+ if metadata:
+ save('metadata', metadata, 0)
+ emitted, paths, size, views, label, number = set(), [], 0, 0, None, 0
+ for group_label, group_files, group_views in groups:
+ fresh = [path for path in group_files if path not in emitted]
+ required = sum(path.stat().st_size + 1024 for path in fresh)
+ if paths and (label != group_label or size + required > shard_bytes):
+ save(f'{label}-{number:05d}', paths, views)
+ paths, size, views, number = [], 0, 0, number + 1
+ emitted.update(fresh)
+ label = group_label
+ paths.extend(fresh)
+ size += required
+ views += group_views
+ if paths:
+ save(f'{label}-{number:05d}', paths, views)
+ if publisher:
+ publisher.flush()
+ index.update(complete=True, bytes=sum(row['bytes'] for row in index['archives']))
+ atomic_json(path, index)
+ if publisher:
+ publisher.small(f'{remote_root}/index.json', path)
+ return index
+
+
+class Publisher:
+ """Verify remote SHA-256 identities before deleting local transfer shards."""
+ def __init__(self, repo, *, cleanup=True, workers=4):
+ from huggingface_hub import HfApi
+ self.repo, self.api, self.cleanup, self.workers = repo, HfApi(), cleanup, workers
+ self.remote = {item.rfilename: item for item in self.api.dataset_info(repo, files_metadata=True).siblings}
+ self.pending = []
+
+ def matches(self, path, record):
+ existing = self.remote.get(path)
+ return bool(existing and existing.size == record['bytes'] and existing.lfs
+ and existing.lfs.sha256 == record['sha256'])
+
+ def ready(self, remote_path, local_path, record):
+ if self.matches(remote_path, record):
+ if self.cleanup:
+ local_path.unlink(missing_ok=True)
+ return
+ self.pending.append((remote_path, local_path, record))
+ if len(self.pending) >= 8:
+ self.flush()
+
+ def flush(self):
+ from huggingface_hub import CommitOperationAdd
+ if not self.pending:
+ return
+ batch = self.pending
+ print(f'UPLOADING {len(batch)} archives, {sum(row[2]["bytes"] for row in batch)/1e9:.3f} GB', flush=True)
+ _retry(lambda: self.api.create_commit(repo_id=self.repo, repo_type='dataset',
+ operations=[CommitOperationAdd(path_in_repo=remote, path_or_fileobj=local)
+ for remote, local, record in batch], num_threads=self.workers,
+ commit_message='Upload compact reproduction archives'))
+ entries = _retry(lambda: self.api.get_paths_info(self.repo, [row[0] for row in batch], repo_type='dataset'))
+ self.remote.update({entry.path: entry for entry in entries})
+ # RepoFile uses path, while RepoSibling uses rfilename. Both expose size and lfs.
+ for remote, local, record in batch:
+ if not self.matches(remote, record):
+ raise ValueError(f'Remote archive verification failed: {remote}')
+ if self.cleanup:
+ local.unlink()
+ self.pending = []
+
+ def small(self, remote_path, local_path):
+ _retry(lambda: self.api.upload_file(repo_id=self.repo, repo_type='dataset',
+ path_in_repo=remote_path, path_or_fileobj=local_path,
+ commit_message=f'Publish {remote_path}'))
+
+
+def download_training(repo, name, destination, revision='main', *, cleanup=True):
+ """Restore only active training components. Optional and deprecated paths stay untouched."""
+ from huggingface_hub import HfApi, hf_hub_download
+ from preprocess.huggingface import download
+ revision = HfApi().dataset_info(repo, revision=revision).sha
+ cache = Path(destination).resolve() / 'outputs/huggingface/reproduction'
+ path = hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision, local_dir=cache)
+ recipe = _json(path)
+ if recipe.get('schema') != RECIPE_SCHEMA or not recipe.get('complete'):
+ raise ValueError('The active training inventory is incomplete')
+ names = recipe['default_datasets'] if name == 'all' else [name]
+ restored = []
+ for dataset in names:
+ if dataset not in recipe['datasets']:
+ raise ValueError(f'Unknown training dataset: {dataset}')
+ for component in recipe['datasets'][dataset]['required']:
+ relative = _relative(component)
+ if relative.parts[0] != 'training' or relative.name != dataset:
+ raise ValueError('Default downloads must remain in the active training folder')
+ restored.append(download(repo, dataset, destination, revision, cleanup=cleanup,
+ bundle_root=str(relative.parent)))
+ return restored
+
+
+def publish(repo, output, names, *, monitor_views=16, optional=True, shard_bytes=1024**3, workers=4):
+ """Publish compact observations, object targets and separate optional components."""
+ output = Path(output).resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ publisher = Publisher(repo, workers=workers)
+ recipe = {'schema': RECIPE_SCHEMA, 'complete': False, 'default_datasets': list(DEFAULT_DATASETS),
+ 'monitor_views_per_dataset': monitor_views, 'datasets': {}, 'optional': {},
+ 'base_git_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()}
+ status = output / 'status.json'
+ atomic_json(status, {'phase': 'running', 'repo': repo, 'pid': os.getpid()})
+ for name in names:
+ source = Path('datasets') / name / 'extent/point_cloud'
+ staged = output / 'staging' / name / 'extent/point_cloud'
+ manifest, metadata, core, held_out, checksums = stage_observations(source, staged, monitor_views=monitor_views)
+ digest = sha256(source / 'manifest.json')
+ destination = Path('datasets') / name / 'extent/point_cloud'
+ details = {'source_manifest_sha256': digest, 'resolution': manifest['resolution'],
+ 'source_views': len(manifest['views']), 'views': sum(row[2] for row in core),
+ 'monitor_views': sum(row[2] for row in core if row[0] == 'monitor'),
+ 'training_views': sum(row[2] for row in core if row[0] == 'train')}
+ index = package(source, output, 'training/observations', name, destination=destination,
+ kind='compact-training', metadata=metadata, groups=core, details=details,
+ checksums=checksums, shard_bytes=shard_bytes, publisher=publisher)
+ record = {'required': [f'training/observations/{name}'], 'bytes': index['bytes'], **details}
+ shape = Path('datasets') / name / 'slat/32/targets'
+ if (shape / 'manifest.json').exists():
+ shape_stage = output / 'staging' / name / 'slat/32/targets'
+ targets, shape_metadata, groups, target_checksums = stage_shape(shape, shape_stage)
+ shape_index = package(shape_stage, output, 'training/shape/32', name,
+ destination=Path('datasets') / name / 'slat/32/targets', kind='object-shape-targets',
+ metadata=shape_metadata, groups=groups, checksums=target_checksums,
+ details={'source_manifest_sha256': sha256(shape / 'manifest.json'), 'resolution': 32,
+ 'views': len(targets['entries']), 'excluded_views': targets['excluded_views'],
+ 'dataset_manifest_sha256': digest, 'scene_latents_included': False},
+ shard_bytes=shard_bytes, publisher=publisher)
+ record['required'].append(f'training/shape/32/{name}')
+ record['bytes'] += shape_index['bytes']
+ record['shape_excluded_views'] = targets['excluded_views']
+ recipe['datasets'][name] = record
+ if optional:
+ if held_out:
+ held_index = package(source, output, 'optional/held_out', name, destination=destination,
+ kind='held-out-observations', metadata=[], groups=held_out, checksums=checksums,
+ details={'source_manifest_sha256': digest, 'views': sum(row[2] for row in held_out)},
+ shard_bytes=shard_bytes, publisher=publisher)
+ recipe['optional'][f'held_out/{name}'] = {'component': f'optional/held_out/{name}',
+ 'bytes': held_index['bytes']}
+ geometry = sorted({source.resolve() / row['geometry'] for row in manifest['views']})
+ if geometry and all(path.exists() for path in geometry):
+ from dataloader.geometry import geometry_artifacts
+ groups = [('geometry', geometry_artifacts(source, str(path.relative_to(source.resolve()))), 0)
+ for path in geometry]
+ geometry_index = package(source, output, 'optional/geometry', name, destination=destination,
+ kind='mesh-geometry', metadata=[], groups=groups,
+ details={'source_manifest_sha256': digest}, shard_bytes=shard_bytes, publisher=publisher)
+ recipe['optional'][f'geometry/{name}'] = {'component': f'optional/geometry/{name}',
+ 'bytes': geometry_index['bytes']}
+ atomic_json(output / 'training/index.json', recipe)
+ atomic_json(status, {'phase': 'running', 'repo': repo, 'pid': os.getpid(), 'finished_dataset': name,
+ 'datasets': list(recipe['datasets'])})
+ recipe['complete'] = True
+ from preprocess.ss_targets import retain_registered
+ retain_registered(recipe, repo, output)
+ atomic_json(output / 'training/index.json', recipe)
+ publisher.small('training/index.json', output / 'training/index.json')
+ atomic_json(status, {'phase': 'data_uploaded', 'repo': repo, 'pid': os.getpid(),
+ 'revision': publisher.api.dataset_info(repo).sha, 'datasets': recipe['datasets']})
+ return recipe
+
+
+def publish_evaluation(repo, output):
+ """Publish YCB-V scoring inputs without duplicate image and depth files."""
+ from dataloader.geometry import geometry_artifacts
+ output = Path(output).resolve()
+ source = Path('datasets/ycbv/extent/point_cloud')
+ ready = output / 'optional/evaluation/ycbv/index.json'
+ if ready.exists():
+ previous = _json(ready)
+ if previous.get('complete') and previous.get('source_manifest_sha256') == sha256(source / 'manifest.json'):
+ remote = Publisher(repo)
+ if all(remote.matches(f'optional/evaluation/ycbv/{row["file"]}', row) for row in previous['archives']):
+ return {'component': 'optional/evaluation/ycbv', 'bytes': previous['bytes']}
+ staged = output / 'staging/ycbv/extent/point_cloud'
+ manifest, metadata, groups, _, checksums = stage_observations(source, staged, monitor_views=1000000)
+ for relative in sorted({row['geometry'] for row in manifest['views']}):
+ files = geometry_artifacts(source, relative)
+ groups.append(('geometry', files, 0))
+ index = package(source, output, 'optional/evaluation', 'ycbv',
+ destination=Path('datasets/ycbv/extent/point_cloud'), kind='compact-training', metadata=metadata,
+ groups=groups, checksums=checksums, details={'source_manifest_sha256': sha256(source / 'manifest.json'),
+ 'evaluation_only': True, 'views': len(manifest['views']), 'geometry_included': True},
+ publisher=Publisher(repo))
+ return {'component': 'optional/evaluation/ycbv', 'bytes': index['bytes']}
+
+
+def _copy_files(api, repo, output, mapping, *, revision=LEGACY_REVISION, remove_sources=False):
+ """Copy LFS objects on the server and transfer only small Git files."""
+ from huggingface_hub import CommitOperationAdd, CommitOperationCopy, CommitOperationDelete, hf_hub_download
+ source_info = api.dataset_info(repo, revision=revision, files_metadata=True)
+ sources = {row.rfilename: row for row in source_info.siblings}
+ current = {row.rfilename: row for row in api.dataset_info(repo, files_metadata=True).siblings}
+ operations = []
+ commits = []
+
+ def flush():
+ if operations:
+ result = _retry(lambda: api.create_commit(repo_id=repo, repo_type='dataset', operations=list(operations),
+ commit_message='Move superseded dataset uploads to the deprecated folder' if remove_sources
+ else 'Separate optional GT occlusion archives'))
+ commits.append(result.oid)
+ operations.clear()
+
+ for source, target in mapping.items():
+ original = sources[source]
+ existing = current.get(target)
+ matches = bool(existing and existing.size == original.size and (
+ existing.lfs.sha256 == original.lfs.sha256 if original.lfs and existing.lfs
+ else existing.blob_id == original.blob_id))
+ if existing and not matches:
+ raise ValueError(f'Existing destination differs from the historical file: {target}')
+ if not matches:
+ if original.lfs:
+ operations.append(CommitOperationCopy(src_path_in_repo=source, path_in_repo=target,
+ src_revision=revision))
+ else:
+ local = hf_hub_download(repo, source, repo_type='dataset', revision=revision,
+ local_dir=Path(output) / 'historical_metadata')
+ operations.append(CommitOperationAdd(path_in_repo=target, path_or_fileobj=local))
+ if remove_sources and source in current:
+ old = current[source]
+ same = old.lfs.sha256 == original.lfs.sha256 if old.lfs and original.lfs else old.blob_id == original.blob_id
+ if not same:
+ raise ValueError(f'The legacy source changed during migration: {source}')
+ operations.append(CommitOperationDelete(path_in_repo=source))
+ if len(operations) >= 100:
+ flush()
+ flush()
+ return commits
+
+
+def export_code(output, base_revision, *, tracked=None, added=None, name='reproduction'):
+ """Export selected source changes and preserve unrelated workspace edits."""
+ output = Path(output)
+ folder = output / 'code'
+ folder.mkdir(parents=True, exist_ok=True)
+ if tracked is None:
+ runtime = subprocess.check_output(['git', 'ls-files', '--', 'ss_multiobj_depth',
+ 'utils/training', 'models/voxel_condition.py'], text=True).splitlines()
+ tracked = ['HF_DATASETS.md', 'preprocess/slat/HUGGING_FACE.md', 'preprocess/slat/README.md',
+ 'dataloader/dataset.py', 'dataloader/extent.py', 'preprocess/huggingface.py',
+ 'preprocess/validate_dataset.py', *runtime]
+ added = (['preprocess/reproduction.py', 'preprocess/tests/test_reproduction.py',
+ 'preprocess/ss_targets.py', 'preprocess/tests/test_ss_targets.py', 'preprocess/SS_TARGETS.md',
+ 'preprocess/tasks.py']
+ if added is None else added)
+ content = subprocess.check_output(['git', 'diff', '--binary', base_revision, '--', *tracked, *added])
+ for path in added:
+ present = subprocess.run(['git', 'cat-file', '-e', f'{base_revision}:{path}'],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
+ indexed = subprocess.run(['git', 'ls-files', '--error-unmatch', path],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
+ if present or indexed:
+ continue
+ result = subprocess.run(['git', 'diff', '--binary', '--no-index', '--', '/dev/null', path],
+ stdout=subprocess.PIPE, check=False)
+ if result.returncode not in (0, 1):
+ raise RuntimeError(f'Cannot export restore source: {path}')
+ content += result.stdout
+ patch = folder / f'{name}.patch'
+ patch.write_bytes(content)
+ manifest = {'base_git_revision': base_revision, 'patch_sha256': sha256(patch),
+ 'files': {path: sha256(path) for path in [*tracked, *added]}}
+ atomic_json(folder / ('manifest.json' if name == 'reproduction' else f'{name}_manifest.json'), manifest)
+ return manifest
+
+
+def write_card(output, recipe, repo):
+ """Write the active download instructions with measured archive sizes."""
+ output = Path(output)
+ total = sum(recipe['datasets'][name]['bytes'] for name in recipe['default_datasets'])
+ lines = ['---', 'language:', '- en', 'tags:', '- 3d', '- depth', '- segmentation',
+ '- voxel-occupancy', 'pretty_name: PartProbe3D compact reproduction data', '---', '',
+ '# PartProbe3D reproduction data', '',
+ 'This release supports SS, generative SLAT segmentation, and 32³ SLAT shape training.',
+ f'The default transfer is **{total/1e9:.2f} GB**, including both training datasets and object shape targets.',
+ 'Default downloads exclude optional and deprecated folders.', '',
+ '## Restore tools', '',
+ f'Use the project checkout at Git revision `{recipe["base_git_revision"]}`.',
+ 'Apply the supplied restore patch before using the compact data.',
+ 'The patch preserves unrelated files and adds the compact readers and download commands.', '',
+ '```bash', f'hf download {repo} code/reproduction.patch --repo-type dataset --local-dir outputs/huggingface/bootstrap',
+ 'git apply --check outputs/huggingface/bootstrap/code/reproduction.patch',
+ 'git apply outputs/huggingface/bootstrap/code/reproduction.patch',
+ "python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]'", '```', '',
+ 'The [source manifest](code/manifest.json) records the patch checksum and required Git revision.', '',
+ '## Default download', '', 'Run this command from the patched project root:', '', '```bash',
+ f'python -m preprocess.huggingface download --repo {repo}', '```', '',
+ 'The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.',
+ 'It verifies each archive and removes temporary archives after restoration.',
+ 'The downloader pins one Hub revision before reading any archive.',
+ 'Add `--revision <Hub commit>` to select a fixed release.',
+ 'Add `--keep-archives` only when you need temporary transfer files.', '',
+ '| Dataset | SS/segmentation training views | Shape training views | Monitoring views | Transfer, GB |',
+ '| --- | ---: | ---: | ---: | ---: |']
+ for name, row in recipe['datasets'].items():
+ shape_views = row['training_views'] - len(row.get('shape_excluded_views', [])) if len(row['required']) > 1 else 'Unavailable'
+ lines.append(f'| {name} | {row["training_views"]:,} | {shape_views if isinstance(shape_views, str) else format(shape_views, ",")} | {row["monitor_views"]} | {row["bytes"]/1e9:.2f} |')
+ lines += ['', 'FoundationPose requires explicit selection and supports SS and segmentation.', '', '```bash',
+ f'python -m preprocess.huggingface download --repo {repo} --dataset foundationpose', '```', '',
+ '## Contents', '',
+ 'Sample NPZ files retain RGB, metric depth, visible labels, complete object occupancy, and the original transforms.',
+ 'Calibration, scene voxel targets, object mappings, and original extent manifests remain available.',
+ 'The compact export omits separate RGB, masks, depth copies, overlays, and duplicate voxel exports.',
+ 'Every training view remains available to SS and segmentation.',
+ 'The first 16 test views per dataset support existing eight-view and sixteen-view training monitors.',
+ 'All other test observations require an optional download.', '',
+ 'Object shape arrays retain their original values and identities.',
+ 'Shape manifests explicitly exclude the three failed SAGE views used by the existing experiment.',
+ 'SS and segmentation retain those views.',
+ 'The export omits combined scene latents because the current shape objective uses object targets.',
+ 'Model weights and image-feature caches remain separate dependencies.', '',
+ '## Optional components', '',
+ '| Component | Purpose | Transfer, GB |', '| --- | --- | ---: |']
+ descriptions = {'geometry': 'Mesh scoring and new target encoding', 'held_out': 'Remaining test observations',
+ 'occlusion': 'GT relations for SS object attention', 'evaluation': 'YCB-V mesh evaluation'}
+ for name, row in sorted(recipe['optional'].items()):
+ lines.append(f'| `{name}` | {descriptions[name.split("/")[0]]} | {row["bytes"]/1e9:.3f} |')
+ lines += ['', 'Restore observations before geometry, occlusion, or test overlays.',
+ 'YCB-V evaluation includes its own observations and geometry.', 'Select each optional component explicitly:', '',
+ '```bash', f'python -m preprocess.huggingface download --repo {repo} --dataset sage --optional geometry',
+ f'python -m preprocess.huggingface download --repo {repo} --dataset 3dfront --optional occlusion',
+ f'python -m preprocess.huggingface download --repo {repo} --dataset sage --optional held-out',
+ f'python -m preprocess.huggingface download --repo {repo} --dataset ycbv --optional evaluation', '```', '',
+ '## Train all three stages', '',
+ 'Obtain the configured model weights separately.', 'Run SS preparation before SS training.', '',
+ '```bash',
+ 'python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json',
+ 'python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json',
+ 'python -m slat_segvigen.train --config slat_segvigen/configs/object_mean_image_nora_coverage_gate.json',
+ 'python -m preprocess.slat.prepare --config preprocess/slat/configs/front3d_sage_32_assigned_object.json --stage features --devices cuda:0 cuda:1',
+ 'python -m slat_multiobj_shape.train --config slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json', '```', '',
+ 'Use the saved configuration and pretrained assets for a specific experiment.',
+ 'Feature preparation creates local caches without meshes or another dataset download.',
+ 'For lower local storage, generate an online shape configuration:', '', '```bash',
+ 'python -m preprocess.reproduction configure-shape --output outputs/reproduction/shape_online.json',
+ 'python -m slat_multiobj_shape.train --config outputs/reproduction/shape_online.json', '```', '',
+ 'The generated configuration computes image conditioning during training and avoids separate image-feature caches.',
+ 'It preserves the selected preset\'s model and optimization settings.',
+ 'Use the original cached preset when reproducing a cached-feature experiment.',
+ 'Data and decoder provenance remain in the restored manifests.',
+ 'Exact checkpoint resume requires the original matching feature and data identities.', '',
+ '## Deprecated uploads', '',
+ f'`{LEGACY_PREFIX}/` contains superseded bundles and catalogs.',
+ 'The project downloader never selects these paths.',
+ 'An unfiltered Hugging Face snapshot download includes every folder.',
+ 'Use the project downloader for minimal transfer.',
+ f'The [original release](https://huggingface.co/datasets/{repo}/tree/{LEGACY_REVISION}) remains available by revision.', '',
+ '## Source terms and previews', '',
+ 'Source dataset terms continue to apply to these derived observations.',
+ 'The prepared data does not replace access agreements for original source assets.', '',
+ '', '',
+ '', '',
+ '[Posed object geometry](previews/3dfront/train-geometry.glb)', '']
+ card = '\n'.join(lines)
+ if any(row.get('ss_targets') for row in recipe['datasets'].values()):
+ from preprocess.ss_targets import update_card
+ card = update_card(card, recipe, repo)
+ from preprocess.tasks import update_card
+ card = update_card(card, None, repo)
+ (output / 'README.md').write_text(card)
+
+
+def finalize(repo, output, *, deprecate=False):
+ """Verify active artifacts before moving any legacy file."""
+ from huggingface_hub import HfApi, hf_hub_download
+ output = Path(output).resolve()
+ recipe = _json(output / 'training/index.json')
+ if not recipe.get('complete'):
+ raise ValueError('Complete training publication before finalizing the repository')
+ api = HfApi()
+ legacy = api.dataset_info(repo, revision=LEGACY_REVISION, files_metadata=True)
+ copies = {row.rfilename: row.rfilename.replace('precomputed_occlusion/', 'optional/occlusion/', 1)
+ for row in legacy.siblings if row.rfilename.startswith('precomputed_occlusion/')
+ and (row.rfilename.endswith('.tar') or row.rfilename.endswith('/index.json'))}
+ _copy_files(api, repo, output, copies)
+ for name in DEFAULT_DATASETS:
+ path = hf_hub_download(repo, f'precomputed_occlusion/{name}/index.json', repo_type='dataset',
+ revision=LEGACY_REVISION, local_dir=output / 'historical_metadata')
+ recipe['optional'][f'occlusion/{name}'] = {'component': f'optional/occlusion/{name}', 'bytes': _json(path)['bytes']}
+ recipe['optional']['evaluation/ycbv'] = publish_evaluation(repo, output)
+ publisher = Publisher(repo)
+ components = [part for row in recipe['datasets'].values() for part in row['required']]
+ components += [row['component'] for row in recipe['optional'].values()]
+ verified = []
+ for component in components:
+ path = hf_hub_download(repo, f'{component}/index.json', repo_type='dataset', local_dir=output / 'verification')
+ index = _json(path)
+ if not index.get('complete'):
+ raise ValueError(f'Incomplete component: {component}')
+ for row in index['archives']:
+ if not publisher.matches(f'{component}/{row["file"]}', row):
+ raise ValueError(f'Remote archive mismatch: {component}/{row["file"]}')
+ verified.append({'component': component, 'archives': len(index['archives']), 'bytes': index['bytes']})
+ code = export_code(output, recipe['base_git_revision'])
+ publisher.small('code/reproduction.patch', output / 'code/reproduction.patch')
+ publisher.small('code/manifest.json', output / 'code/manifest.json')
+ atomic_json(output / 'training/index.json', recipe)
+ publisher.small('training/index.json', output / 'training/index.json')
+ write_card(output, recipe, repo)
+ publisher.small('README.md', output / 'README.md')
+ commits = []
+ if deprecate:
+ prefixes = ('bundles/', 'precomputed_slat/', 'precomputed_occlusion/', 'metadata/', 'catalog/')
+ mapping = {row.rfilename: f'{LEGACY_PREFIX}/{row.rfilename}' for row in legacy.siblings
+ if row.rfilename.startswith(prefixes) or row.rfilename == 'catalog.json'}
+ commits = _copy_files(api, repo, output, mapping, remove_sources=True)
+ folder = output / LEGACY_PREFIX
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / 'README.md').write_text('# Deprecated dataset uploads\n\n'
+ 'These files preserve the previous dataset layout.\n'
+ 'Default reproduction downloads exclude this folder.\n'
+ 'Use the active `training/` components and explicit `optional/` downloads.\n\n'
+ f'[Original release](https://huggingface.co/datasets/{repo}/tree/{LEGACY_REVISION}).\n')
+ publisher.small(f'{LEGACY_PREFIX}/README.md', folder / 'README.md')
+ result = {'complete': True, 'repo': repo, 'revision': api.dataset_info(repo).sha,
+ 'components': verified, 'code': code, 'deprecation_commits': commits,
+ 'default_bytes': sum(recipe['datasets'][name]['bytes'] for name in recipe['default_datasets'])}
+ atomic_json(output / 'completion.json', result)
+ atomic_json(output / 'status.json', {'phase': 'complete', **result})
+ return result
+
+
+def configure_shape(source, output):
+ """Select online image conditioning without changing model or optimization settings."""
+ config = _json(source)
+ for entry in config.get('prepared_datasets', []):
+ entry.pop('features', None)
+ entry.pop('training_targets', None)
+ config.pop('features', None)
+ config.pop('training_targets', None)
+ config['output'] = 'outputs/slat_multiobj_shape/reproduction_online/train'
+ config['checkpoints'] = 'checkpoints/training/slat_multiobj_shape/reproduction_online'
+ config['checkpoint'] = config['checkpoints'] + '/last.pt'
+ output = Path(output)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ if output.exists() and _json(output) != config:
+ raise FileExistsError(f'Configuration already contains different settings: {output}')
+ atomic_json(output, config)
+ return config
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest='command', required=True)
+ publishing = commands.add_parser('publish')
+ publishing.add_argument('--repo', default=DEFAULT_REPO)
+ publishing.add_argument('--output', type=Path, required=True)
+ publishing.add_argument('--dataset', action='append', required=True)
+ publishing.add_argument('--monitor-views', type=int, default=16)
+ publishing.add_argument('--workers', type=int, default=4)
+ publishing.add_argument('--shard-gib', type=float, default=1)
+ publishing.add_argument('--without-optional', action='store_true')
+ finishing = commands.add_parser('finalize')
+ finishing.add_argument('--repo', default=DEFAULT_REPO)
+ finishing.add_argument('--output', type=Path, required=True)
+ finishing.add_argument('--deprecate', action='store_true')
+ configuring = commands.add_parser('configure-shape')
+ configuring.add_argument('--source', type=Path,
+ default=Path('slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json'))
+ configuring.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == 'finalize':
+ finalize(args.repo, args.output, deprecate=args.deprecate)
+ elif args.command == 'configure-shape':
+ configure_shape(args.source, args.output)
+ else:
+ publish(args.repo, args.output, args.dataset, monitor_views=args.monitor_views,
+ optional=not args.without_optional, shard_bytes=int(args.shard_gib * 1024**3), workers=args.workers)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/preprocess/slat/HUGGING_FACE.md b/preprocess/slat/HUGGING_FACE.md
index dee49f8..0865e0d 100644
--- a/preprocess/slat/HUGGING_FACE.md
+++ b/preprocess/slat/HUGGING_FACE.md
@@ -1,145 +1,98 @@
-## SLAT shape: upload and download specification
-
-The repository contains prepared extent datasets and separate SLAT-shape targets.
-Combined 32³ SLAT finetuning requires both artifact types for both training datasets.
-The 6.84 GB SLAT upload contains latent targets and metadata.
-It excludes RGB observations, depth maps, masks, and frozen image features.
-
-The sizes and coverage below describe data snapshot `0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa`.
-GB means decimal gigabytes.
-
-| Bundle | Contents | Training archives and metadata, GB | All archives, GB |
-| --- | --- | ---: | ---: |
-| `bundles/3dfront` | Calibrated observations, extent geometry, and occupancy targets | 234.67 | 293.70 |
-| `bundles/sage` | Calibrated observations, extent geometry, and occupancy targets | 460.59 | 510.88 |
-| `precomputed_slat/3dfront` | 32³ object latents and available scene latents | 5.57 | 5.57 |
-| `precomputed_slat/sage` | 32³ object latents and recorded failures | 1.27 | 1.27 |
-| Total | Both datasets and both artifact types | 702.10 | 811.42 |
-
-Training requires each extent bundle's `metadata.tar` and `train-*.tar` archives.
-Evaluation also requires its `test-*.tar` archives.
-The current download command restores every archive in a bundle, including available test archives.
-It has no split filter.
-The four commands below therefore download about 811.42 GB.
-
-### Download and restore
-
-Use the updated PartProbe3D checkout with latent generation in `preprocess/slat/`.
-Install its preprocessing dependencies and `huggingface-hub`.
-Authenticate with a Hugging Face account that can access this dataset repository.
-Run these commands from the repository root.
-
-1. Restore the prepared 3D-FRONT extent dataset.
-
- ```bash
- python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root bundles \
- --dataset 3dfront --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup
- ```
-
-2. Restore the prepared SAGE-10k extent dataset.
-
- ```bash
- python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root bundles \
- --dataset sage --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup
- ```
-
-3. Restore the 3D-FRONT shape targets.
-
- ```bash
- python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset 3dfront --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup
- ```
-
-4. Restore the SAGE-10k shape targets.
-
- ```bash
- python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset sage --revision 0e4623fb0c8d9bad7cbe1dfb161a993ac165b6aa --cleanup
- ```
-
-| Dataset | Prepared observations and extent targets | SLAT targets |
-| --- | --- | --- |
-| 3D-FRONT | `datasets/3dfront/extent/point_cloud/` | `datasets/3dfront/slat/32/targets/` |
-| SAGE-10k | `datasets/sage/extent/point_cloud/` | `datasets/sage/slat/32/targets/` |
-
-The updated downloader maps historical SLAT archive paths under `outputs/` to these dataset locations.
-It preserves target bytes and verifies every archive's size and SHA-256 checksum.
-It refuses to replace different existing files.
-`--cleanup` retains one temporary archive at a time and removes it after successful restoration.
-Temporary archives reside under `datasets/<dataset>/archives/huggingface/`.
-Extracted files and future feature caches need additional disk space.
-
-Preserve the original extent manifests without edits.
-The SLAT manifests bind their source datasets through manifest checksums.
-Raw dataset archives, rendering again, and SS feature caches are unnecessary for this workflow.
-
-### Complete preparation before training
-
-The published targets cover 39,930 3D-FRONT training views and 17,456 SAGE-10k training views.
-Three SAGE-10k views retain one failed object target each.
-These failures block strict combined training until object encoding succeeds.
-The snapshot contains scene latents for 6,720 3D-FRONT views and no SAGE-10k scenes.
-The current object loss does not require completed scene encoding.
-
-1. Obtain the configured Pixal3D, DINOv3, and NAF weights separately.
-2. Resolve the three failed SAGE-10k object targets.
-3. Prepare frozen conditioning features and immutable object targets.
-4. Start finetuning after feature preparation succeeds.
-
-The TRELLIS.2 shape encoder and paired decoder are also required when regenerating shape targets.
-Image features and immutable training snapshots are not included in the uploaded target bundles.
-The commands below do not automatically schedule scene encoding or training during feature preparation.
+# SLAT shape reproduction data
+
+The public dataset provides compact observations and separate 32³ object shape targets.
+The [dataset guide](../../HF_DATASETS.md) describes restoration and optional components.
+The shape task downloads both artifact types for 3D-FRONT and SAGE-10k.
+It excludes SS targets and evaluation data.
+FoundationPose shape targets remain unavailable.
```bash
-python -m preprocess.slat.prepare \
- --config preprocess/slat/configs/front3d_sage_32.json \
- --stage features --devices cuda:1 cuda:2
-python -m slat_multiobj_shape.train \
- --config slat_multiobj_shape/configs/front3d_sage_32.json
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed --task slat-shape
```
-Feature preparation writes `object_targets/` and `object_features/` under each dataset's `slat/32/` directory.
-It retains clean GT depth for fresh augmentation during training.
-Testing uses MoGe-3 depth and calibration.
-Training results reside under `outputs/`, and model checkpoints reside under `checkpoints/`.
+## Restored locations
+
+| Artifact | Location |
+| --- | --- |
+| Saved observations and occupancy | `datasets/<dataset>/extent/point_cloud/` |
+| Object shape targets | `datasets/<dataset>/slat/32/targets/` |
+| Optional geometry | `datasets/<dataset>/extent/point_cloud/scenes/` |
+
+The extent manifests retain their original bytes and source splits.
+Each shape manifest binds those extent manifests by SHA-256.
+Each successful object retains its original latent values, cell coordinates, object index, and transform.
+The `object_sha256` identity checks those arrays independently of scene encoding.
+
+The current objective uses separate object latents.
+It does not require combined scene latents or scene encoding.
+The compact targets retain empty scene fields for the existing file schema.
+Use configurations with `require_scene_targets=false`.
-### Upload contract
+## SAGE exclusions
-`bundles/<dataset>/index.json` describes prepared extent archives.
-`precomputed_slat/<dataset>/index.json` describes SLAT target archives.
-Each inventory records archive sizes, SHA-256 checksums, and the restore destination.
-SLAT inventories also record source manifests, codec provenance, coverage, and encoding failures.
+The original release contains three failed object targets.
+The compact release records their views as explicit exclusions:
-An inventory's `complete=true` means packaging covers the snapshot files.
-The uploader publishes a complete inventory after every archive is present with matching size.
-It also compares remote SHA-256 checksums when Hub file metadata provides them.
-`source_complete` separately records whether source preprocessing finished.
-An upload can therefore finish while source object or scene encoding remains incomplete.
-The upload preserves failure records and pending scene statuses.
+- `sage10k/23adeb2d2638a873e5d9`
+- `sage10k/7b2d68afd83bf89364ea`
+- `sage10k/ff0a565cad070014b1b8`
-Package shape targets with this command:
+These exclusions match the existing object-mean shape experiment.
+The exported shape manifest makes them available to every compatible shape preset.
+Shape training therefore uses 39,930 3D-FRONT views and 17,453 SAGE views.
+SS and segmentation still use all 17,456 SAGE training views.
+
+## Train without an image-feature cache
+
+Obtain the configured Pixal3D, DINOv3, and NAF weights separately.
+Create an online configuration from the project root:
```bash
-python -m preprocess.huggingface pack \
- --artifact-kind slat-shape-targets \
- --dataset 3dfront=datasets/3dfront/slat/32/targets \
- --dataset sage=datasets/sage/slat/32/targets \
- --output outputs/huggingface/slat_targets_publish
+python -m preprocess.reproduction configure-shape --output outputs/reproduction/shape_online.json
+python -m slat_multiobj_shape.train \
+ --config outputs/reproduction/shape_online.json
```
-Publish those archives to an existing dataset repository with this command:
+This configuration reads the uploaded object targets and computes image conditioning during training.
+It avoids separate image-feature files and frozen target copies.
+It preserves the selected preset's model, sampling, and optimizer settings.
+It uses separate output and checkpoint directories.
+Use the original cached preset when reproducing a cached-feature experiment.
+
+## Train with cached image features
+
+Prepare the existing assigned-object caches with:
```bash
-python -m preprocess.huggingface upload \
- --repo cubec/PartProbe3D-preprocessed \
- --bundle-root precomputed_slat --dataset 3dfront --dataset sage \
- --output outputs/huggingface/slat_targets_publish
+python -m preprocess.slat.prepare \
+ --config preprocess/slat/configs/front3d_sage_32_assigned_object.json \
+ --stage features --devices cuda:0 cuda:1
+python -m slat_multiobj_shape.train \
+ --config slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json
+```
+
+Feature preparation needs observations, object shape targets, and the configured image encoders.
+It does not need source meshes or the shape encoder.
+The generated feature files and frozen target snapshots consume additional local storage.
+
+## Optional geometry
+
+Geometry is necessary when generating new shape targets or scoring decoded meshes.
+Download it explicitly before these operations:
+
+```bash
+python -m preprocess.huggingface download \
+ --repo cubec/PartProbe3D-preprocessed --dataset 3dfront --optional geometry
+python -m preprocess.huggingface download \
+ --repo cubec/PartProbe3D-preprocessed --dataset sage --optional geometry
```
-The target upload excludes worker jobs, raw assets, model weights, and frozen image feature caches.
-Use a fresh packaging directory when source manifests change.
-Publish matching extent and target snapshots before documenting a new reproducible data revision.
+New encoding also needs the configured shape encoder and paired decoder.
+The public compact shape targets use a 32³ grid.
+Their encoder uses a 512³ geometry grid and produces 32 channels per latent cell.
+
+## Historical snapshots
+
+The original targets remain in the deprecated folder and the original pinned revisions.
+The [original upload report](../../reports/slat_targets_huggingface_20261015.md) records their coverage and codec identities.
+Exact checkpoint resume requires the checkpoint's original data and feature identities.
diff --git a/preprocess/slat/README.md b/preprocess/slat/README.md
index 46e4436..c7e7fde 100644
--- a/preprocess/slat/README.md
+++ b/preprocess/slat/README.md
@@ -1,7 +1,7 @@
# SLAT preparation
This stage prepares reusable training inputs for multi-object SLAT shape finetuning.
-It reads the saved 3D-FRONT and SAGE-10k extent datasets after capture and voxel export.
+It reads saved extent datasets from 3D-FRONT, SAGE-10k, and FoundationPose after capture and voxel export.
It preserves each saved cube, object identity, and room or layout split.
The generation implementation and its configurations reside in this package.
@@ -11,6 +11,106 @@ The generation implementation and its configurations reside in this package.
| `targets.py` | Select posed meshes, preserve the saved cube, and write object and scene targets |
| `encode.py` | Convert meshes to dual grids and apply the frozen pretrained shape encoder |
| `prepare.py` | Coordinate dataset phases and extract frozen conditioning features |
+| `scene_targets.py` | Export one scene token per reference voxel with an explicit latent validity flag |
+
+## Aligned scene targets at 32³
+
+The scene export combines complete meshes for all prompted objects before one frozen shape encoder processes them.
+It preserves each training view's saved cube, calibration, object order, and dataset split.
+Different views of one room can use different cubes.
+The export therefore retains each view ID.
+
+Reference voxels are the union of complete occupancy for prompted objects.
+The shared `prompt_object_cells` function selects these voxels from saved 64³ targets and pools them to 32³.
+Unprompted objects do not add reference voxels.
+Older feature caches can contain extra scene voxels from unprompted objects.
+Those extra rows do not define the reference occupancy for this export.
+
+Each reference voxel has exactly one scene token, including voxels that contain multiple objects.
+The native scene encoder can omit a small number of reference voxels because its rasterization method differs.
+The export retains those coordinates with zero feature storage and `latent_valid=false`.
+Training must exclude invalid rows from the latent loss.
+The export does not average object latents or interpolate missing values.
+
+| Array | Shape | Meaning |
+| --- | --- | --- |
+| `coords` | `[N, 3]` | Unique reference coordinates in sorted order, stored as `uint8` |
+| `feats` | `[N, 32]` | Physical scene latents stored as `float16`, with zeros at invalid rows |
+| `latent_valid` | `[N]` | Boolean flag for an exact coordinate match with native scene encoding |
+| `memberships` | `[N, K]` | Independent per-object voxel occupancy for the same reference rows |
+| `object_ids` | `[K]` | Prompt identities in the saved order |
+| `model_to_world` | `[4, 4]` | Original transform from the normalized cube to world coordinates |
+
+Multiple columns of `memberships` can be positive at one voxel.
+They do not create additional scene tokens.
+
+Run the combined export from the repository root:
+
+```bash
+python -m preprocess.slat.scene_targets \
+ --config preprocess/slat/configs/scenes_32.json
+```
+
+The configuration selects training views only and uses GPUs 0, 1, and 2.
+Sixteen CPU processes prepare meshes for six persistent GPU workers.
+Each GPU hosts two encoder processes.
+Each GPU worker uses four CPU threads to prepare native dual grids while the GPU encodes earlier grids.
+The `mesh_workers` and `raster_workers` settings control these CPU counts.
+The latter count applies separately to each GPU worker.
+The `mesh_executor` setting selects CPU processes or threads.
+CPU processes avoid Python thread contention during mesh preparation.
+They transfer geometry and reference metadata without RGB or depth tensors.
+Prefetch retains a bounded number of grids in memory.
+
+Mesh clipping omits plane cuts when all vertices lie strictly inside the plane.
+Vertices near a clipping plane retain the original Trimesh procedure.
+These changes preserve the cube, rasterization settings, encoder weights, and reference voxels.
+
+Its `encoder_config` selects the existing codec weights, dual-grid settings, and native Python environment.
+Each dataset saves its targets under `datasets/<dataset>/slat/32/scene_targets/`.
+The format identifier is `slat-scene-targets-v1`.
+Logs and combined progress reside under `outputs/slat_scene/32/preparation/`.
+
+The export reuses completed native scene encodings after it checks their dataset, cube, prompts, codec, and file checksums.
+Existing object caches retain their original files.
+Per-view completion records support resume after an interruption.
+Resume retries failed encodings and replaces corrupt output files.
+
+Add `--limit-per-dataset 2` for a short GPU check.
+Repeat the command without that argument to complete every training view.
+The command finishes active jobs before it honors SIGINT or SIGTERM.
+The default storage reserve stops preparation if free space falls below 20 GiB.
+
+`dataloader.slat_scene.SceneTargetDataset` reads one or more exported caches without loading meshes.
+It checks exact reference coordinates, occupancy labels, object identities, and cube transforms against the saved extent views.
+It normalizes valid latents with the pretrained flow statistics and keeps invalid rows zero.
+
+### Test native latent equivalence
+
+Run the regression with the actual pretrained encoder:
+
+```bash
+PARTPROBE3D_NATIVE_SLAT_TEST=1 python -m pytest \
+ preprocess/tests/test_slat_native_equivalence.py -q
+```
+
+This test requires the native CUDA environment and existing codec checkpoints.
+Set `PARTPROBE3D_NATIVE_SLAT_DEVICE` to select a GPU other than `cuda:0`.
+The test compares original serial preparation with optimized clipping and four CPU threads for rasterization.
+It covers inside meshes, clipped meshes, and overlapping objects encoded together.
+It requires identical coordinates and identical stored `float16` latents with zero tolerance.
+The normal test suite skips this GPU test unless the environment flag enables it.
+
+## FoundationPose object targets
+
+The [FoundationPose target preset](configs/targets_foundationpose_32.json) uses the same native shape encoder and dual-grid settings as 3D-FRONT and SAGE.
+It reads saved FoundationPose extents and writes `datasets/foundationpose/slat/32/targets/`.
+Its device `cuda:1` selects the second visible GPU.
+
+FoundationPose observation bundles contain RGB, masks, depth, calibration, and voxel labels.
+They do not contain object shape latents or complete mesh geometry.
+Restore the geometry or existing shape targets before starting FoundationPose-inclusive shape training.
+The training default requires complete target coverage and does not omit FoundationPose when its targets are unavailable.
## Prepared data
@@ -84,25 +184,25 @@ Scene encoding preserves object failures and includes their selected meshes in t
Failed objects still require successful encoding before feature extraction or finetuning.
Resume preserves completed object and scene latents.
-The cached training configurations supervise objects and do not require scene targets.
-Configurations with `require_scene_targets=true` retain scene supervision in their feature caches.
+All shape training configurations supervise object latents only.
+Feature caches exclude scene supervision, while target exports retain scene latents for diagnostics.
1. Prepare targets and features for both training datasets.
```bash
- CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.prepare
+ python -m preprocess.slat.prepare
```
2. Train with equal sampling probability per dataset.
```bash
- CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m slat_multiobj_shape.train
+ python -m slat_multiobj_shape.train
```
3. Resume training with the same prepared data.
```bash
- CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m slat_multiobj_shape.train --resume
+ python -m slat_multiobj_shape.train --resume
```
Use the corresponding `front3d_sage_64.json` files for a 64³ token grid.
@@ -126,10 +226,10 @@ That option overrides the device list for feature extraction.
Rerun the same command to reuse matching entries and regenerate corrupt or failed entries.
`--stage targets` runs the object phase and scene phase without feature extraction.
-Generate latents on physical GPUs 4 and 6 with:
+Generate latents on two visible GPUs with:
```bash
-CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.prepare \
+python -m preprocess.slat.prepare \
--stage targets --devices cuda:0 cuda:1 --parallel 2
```
@@ -181,42 +281,31 @@ Training resume also checks cache provenance and latent target checksums.
## Hugging Face snapshots
-The [upload and download specification](HUGGING_FACE.md) lists training dependencies, archive sizes, restoration commands, and publication requirements.
-
-The [preprocessed dataset repository](https://huggingface.co/datasets/cubec/PartProbe3D-preprocessed/tree/main/precomputed_slat) contains separate snapshots of the available 32³ shape targets.
-The snapshots preserve the original manifests, per-view checksums, object identities, and completion states.
-They cover training views only.
-Frozen DINOv3 and NAF feature caches still require preparation.
-
-| Dataset | Training views | Encoded objects | Failed objects | Completed scene views | Pending scene views |
-| --- | ---: | ---: | ---: | ---: | ---: |
-| 3D-FRONT | 39,930 | 240,952 | 0 | 6,720 | 33,210 |
-| SAGE-10k | 17,456 | 397,203 | 3 | 0 | 17,456 |
-
-These counts describe the published snapshot.
-Three SAGE-10k views retain one failed object each.
-Pending scene records remain pending after restoration.
-An archive's completion flag describes packaging and transfer, not completion of source preprocessing.
-
-Restore both caches from the repository root:
+The [reproduction guide](HUGGING_FACE.md) describes the active compact observations and 32³ object shape targets.
+The default download restores both artifact types for 3D-FRONT and SAGE-10k.
+It excludes optional components and deprecated uploads.
```bash
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset 3dfront --cleanup
-python -m preprocess.huggingface download \
- --repo cubec/PartProbe3D-preprocessed --bundle-root precomputed_slat \
- --dataset sage --cleanup
+python -m preprocess.huggingface download --repo cubec/PartProbe3D-preprocessed
```
-The first command restores `datasets/3dfront/slat/32/targets/`.
-The second command restores `datasets/sage/slat/32/targets/`.
-The downloader maps historical archive paths to these dataset locations.
-Restoration verifies archive checksums and rejects replacement of different existing files.
-Add `--revision <commit>` to select a fixed Hub snapshot.
+The observations restore under `datasets/<dataset>/extent/point_cloud/`.
+The object targets restore under `datasets/<dataset>/slat/32/targets/`.
+The extent manifests retain their original bytes and SHA-256 identities.
+Object arrays retain their latent values, coordinates, instance identities, and transforms.
+
+Shape training uses 39,930 3D-FRONT views and 17,453 SAGE views.
+The shape manifest explicitly excludes the three failed SAGE views from the existing experiment.
+The compact shape export omits combined scene latents because the current object loss does not use them.
+Original snapshots remain under `_deprecated/20261020/` and their pinned revisions.
+
+Add `--revision <Hub commit>` to select a fixed release.
+Restoration checks archive hashes and refuses to replace different existing data.
+The downloader removes temporary archives after successful extraction.
-The corresponding extent datasets remain in the repository's `bundles/` directory.
-Shape target loaders require those source datasets and matching manifests.
+Image features require local preparation or online extraction during training.
+Mesh geometry requires an explicit `--optional geometry` download for target regeneration or mesh scoring.
+See the reproduction guide for the online shape configuration and cached feature commands.
## Training and testing
@@ -241,7 +330,7 @@ See the [shape guide](../../slat_multiobj_shape/README.md) for finetuning and in
Start the combined workflow with:
```bash
-CUDA_VISIBLE_DEVICES=4,6 CUDA_DEVICE_ORDER=PCI_BUS_ID python -m preprocess.slat.finetune \
+python -m preprocess.slat.finetune \
--devices cuda:0 cuda:1 --training-device cuda:0
```
@@ -251,9 +340,9 @@ Select the original training configuration to resume an existing additive run.
The command completes these steps:
-1. Prepare all per-object latents on physical GPUs 4 and 6.
+1. Prepare all per-object latents on the configured devices.
2. Freeze object targets and prepare conditioning features on those GPUs.
-3. Start finetuning on physical GPU 4 and scene encoding on physical GPU 6.
+3. Start finetuning and scene encoding on separate configured devices.
The command reuses verified object targets.
It requires full training coverage unless an explicit `--limit` selects a pilot.
diff --git a/preprocess/ss_targets.py b/preprocess/ss_targets.py
new file mode 100644
index 0000000..aa5ae6a
--- /dev/null
+++ b/preprocess/ss_targets.py
@@ -0,0 +1,265 @@
+"""Publish native SS latents so restored training needs no target encoding."""
+import argparse
+from copy import deepcopy
+import json
+from pathlib import Path
+import re
+import subprocess
+import time
+
+import torch
+
+from dataloader.dataset import ViewDataset
+from preprocess.huggingface import _json, _relative, _retry
+from preprocess.reproduction import DEFAULT_REPO, RECIPE_SCHEMA, Publisher, package
+from preprocess.storage import atomic_json
+from ss_multiobj_depth.config import TARGET_SCOPE, load_config, source_configs
+from ss_multiobj_depth.dataloader import FeatureDataset, dataset_name
+from utils.hashing import sha256
+from utils.paths import REPO_ROOT
+
+
+COMPONENT = 'training/ss'
+CARD_START = '<!-- partprobe3d-ss-targets:start -->'
+CARD_END = '<!-- partprobe3d-ss-targets:end -->'
+
+
+def hub_name(dataset):
+ name = dataset_name(dataset)
+ return 'sage' if name == 'sage10k' else name
+
+
+def index_targets(source, observations, *, monitor_views=16):
+ """Index exact cache files for streaming through the checked archive writer."""
+ source, observations = Path(source).resolve(), Path(observations).resolve()
+ if monitor_views < 1:
+ raise ValueError('Use a positive monitoring count')
+ cache = FeatureDataset(source)
+ if cache.target_scope != TARGET_SCOPE or not cache.compact or not len(cache):
+ raise ValueError('Export requires native masked-object SS targets')
+ views = ViewDataset(observations)
+ if cache.policy['dataset']['manifest_sha256'] != sha256(observations / 'manifest.json'):
+ raise ValueError('SS targets and observations have different dataset manifests')
+ if cache.dataset != dataset_name(views.manifest['dataset']):
+ raise ValueError('SS target dataset identity differs from observations')
+ original = {row['id']: row for row in views.manifest['views']}
+ required = {row['id'] for row in views.manifest['views'] if row['split'] == 'train'}
+ required.update([row['id'] for row in views.manifest['views'] if row['split'] == 'test'][:monitor_views])
+ if not required.issubset({row['id'] for row in cache.rows}):
+ raise ValueError('The SS cache omits required training or monitoring views')
+ clean = cache.read_features(0)['clean']
+ if clean.shape != (8, 16, 16, 16) or not clean.is_floating_point() or not torch.isfinite(clean).all():
+ raise ValueError('Invalid native SS latent')
+ groups, checksums = [], {}
+ for row in sorted(cache.rows, key=lambda row: (row['split'], row['scene'], row['id'])):
+ if (row['id'] not in original
+ or any(row[key] != original[row['id']][key] for key in ('scene', 'split'))):
+ raise ValueError(f'SS target identity or split changed: {row["id"]}')
+ if not {'features.pt', 'targets.npz', 'geometry.json'}.issubset(row['files']):
+ raise ValueError(f'Incomplete SS target record: {row["id"]}')
+ folder = source / _relative(row['directory'])
+ paths = [folder / _relative(name) for name in (*row['files'], 'complete.json')]
+ groups.append((row['split'], paths, 1))
+ checksums.update({folder / _relative(key): value for key, value in row['files'].items()})
+ metadata = [source / 'manifest.json', source / 'policy.json']
+ checksums.update({path: sha256(path) for path in metadata})
+ return cache.manifest, metadata, groups, checksums
+
+
+def target_section(recipe, repo=DEFAULT_REPO):
+ lines = [CARD_START, '## Encoded SS targets', '',
+ 'The SS task download includes encoded targets for the datasets listed below.',
+ 'These targets remove GPU encoding from the restore procedure.',
+ 'They retain the original cache manifests, latent tensors, and monitoring targets.',
+ 'Their native latent shape is `8×16×16×16`.',
+ 'Model weights remain separate dependencies.', '',
+ '| Dataset | Target views | Transfer, GB |', '| --- | ---: | ---: |']
+ for name, row in recipe['datasets'].items():
+ if row.get('ss_targets'):
+ targets = row['ss_targets']
+ lines.append(f'| {name} | {targets["views"]:,} | {targets["bytes"]/1e9:.3f} |')
+ ready = all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose'))
+ lines += ['', 'Use the current project checkout and download the selected datasets:', '', '```bash',
+ f'python -m preprocess.huggingface download --repo {repo} --task ss', '```', '',
+ ('SS training can then use the default online configuration without a preparation command.' if ready
+ else 'Publication continues for the remaining datasets. The listed datasets already include SS targets.'),
+ 'The downloader checks archive hashes before extraction.',
+ 'The training loader checks dataset and frozen codec identities.',
+ 'The image encoders compute features during training.', CARD_END]
+ return '\n'.join(lines)
+
+
+def update_card(card, recipe, repo):
+ """Update restore instructions while preserving unrelated published sections."""
+ total = sum(recipe['datasets'][key]['bytes'] for key in recipe['default_datasets'])
+ card = re.sub(r'The default transfer is \*\*[\d.,]+ GB\*\*[^\n]*',
+ f'The default transfer is **{total/1e9:.2f} GB**, including observations, SS targets, and available shape targets.', card)
+ ready = all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose'))
+ if ready and '## Restore tools' in card and '## Default download' in card:
+ start, end = card.index('## Restore tools'), card.index('## Default download')
+ card = (card[:start] + '## Restore tools\n\n'
+ f'Use project Git revision `{recipe["restore_git_revision"]}` or later.\n'
+ 'This revision includes the restore tools and the online SS defaults.\n\n'
+ '```bash\n'
+ "python -m pip install -e '.[preprocess,ss-multiobj-depth,slat-segvigen,slat-multiobj-shape]'\n"
+ '```\n\n' + card[end:])
+ for name, row in recipe['datasets'].items():
+ card = re.sub(rf'(^\| {name} \|[^\n]*\| )[^|]+( \|$)',
+ lambda match: match[1] + f'{row["bytes"]/1e9:.2f}' + match[2], card, flags=re.MULTILINE)
+ if 'foundationpose' in recipe['default_datasets']:
+ card = card.replace('The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.',
+ 'The command restores observations and SS targets for 3D-FRONT, SAGE-10k, and FoundationPose.\n'
+ 'It also restores available 32³ object shape targets.')
+ card = card.replace('FoundationPose requires explicit selection and supports SS and segmentation.',
+ 'The default includes FoundationPose for SS and segmentation.\n'
+ 'FoundationPose shape targets remain unavailable.\n'
+ 'Use this command to restore FoundationPose alone:')
+ if ready:
+ card = card.replace('Run SS preparation before SS training.',
+ 'The restored SS targets support online SS training directly.')
+ card = card.replace('python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json\n', '')
+ card = card.replace('python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json',
+ 'python -m ss_multiobj_depth.train')
+ section = target_section(recipe, repo)
+ if CARD_START in card:
+ start, end = card.index(CARD_START), card.index(CARD_END) + len(CARD_END)
+ return card[:start] + section + card[end:]
+ return card.rstrip() + '\n\n' + section + '\n'
+
+
+def retain_registered(recipe, repo, output):
+ """Keep compatible SS components when observations or shape targets are republished."""
+ from huggingface_hub import HfApi, hf_hub_download
+ from huggingface_hub.errors import EntryNotFoundError
+ revision = HfApi().dataset_info(repo).sha
+ try:
+ previous = _json(hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision,
+ local_dir=Path(output) / 'registered'))
+ except EntryNotFoundError:
+ return
+ for name, row in recipe['datasets'].items():
+ old = previous.get('datasets', {}).get(name, {})
+ targets = old.get('ss_targets')
+ if not targets or old.get('source_manifest_sha256') != row['source_manifest_sha256']:
+ continue
+ if targets['component'] != f'{COMPONENT}/{name}':
+ raise ValueError('Registered SS targets reference an unexpected component')
+ if targets['component'] not in row['required']:
+ row['required'].append(targets['component'])
+ row['bytes'] += targets['bytes']
+ row['ss_targets'] = deepcopy(targets)
+ if any(row.get('ss_targets') for row in recipe['datasets'].values()):
+ recipe['restore_git_revision'] = previous['restore_git_revision']
+ if all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')):
+ recipe['default_datasets'] = ['3dfront', 'sage', 'foundationpose']
+
+
+def register(repo, output, name, index):
+ """Add verified SS archives without replacing concurrent dataset publications."""
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
+ from huggingface_hub.errors import HfHubHTTPError
+ api, output = HfApi(), Path(output)
+ for attempt in range(5):
+ revision = api.dataset_info(repo).sha
+ recipe = _json(hf_hub_download(repo, 'training/index.json', repo_type='dataset', revision=revision,
+ local_dir=output / 'remote'))
+ if recipe.get('schema') != RECIPE_SCHEMA or not recipe.get('complete'):
+ raise ValueError('A complete active training recipe is required')
+ row = recipe['datasets'][name]
+ if row['source_manifest_sha256'] != index['dataset_manifest_sha256']:
+ raise ValueError('Published observations differ from the encoded SS dataset')
+ if row['training_views'] != index['training_views']:
+ raise ValueError('The SS export omits published training views')
+ previous = row.get('ss_targets', {})
+ row['bytes'] += index['bytes'] - previous.get('bytes', 0)
+ component = f'{COMPONENT}/{name}'
+ if component not in row['required']:
+ row['required'].append(component)
+ row['ss_targets'] = {'component': component, 'bytes': index['bytes'], 'views': index['views'],
+ 'latent_shape': [8, 16, 16, 16], 'target_scope': TARGET_SCOPE}
+ recipe['restore_git_revision'] = subprocess.check_output(
+ ['git', 'rev-parse', 'HEAD'], cwd=REPO_ROOT, text=True).strip()
+ # The default SS and segmentation runs include all three datasets.
+ if all(recipe['datasets'].get(key, {}).get('ss_targets') for key in ('3dfront', 'sage', 'foundationpose')):
+ recipe['default_datasets'] = ['3dfront', 'sage', 'foundationpose']
+ card = Path(hf_hub_download(repo, 'README.md', repo_type='dataset', revision=revision,
+ local_dir=output / 'remote')).read_text()
+ card = update_card(card, recipe, repo)
+ (output / 'training').mkdir(parents=True, exist_ok=True)
+ atomic_json(output / 'training/index.json', recipe)
+ (output / 'README.md').write_text(card)
+ try:
+ result = _retry(lambda: api.create_commit(repo_id=repo, repo_type='dataset', parent_commit=revision,
+ operations=[CommitOperationAdd(path_in_repo='training/index.json', path_or_fileobj=output / 'training/index.json'),
+ CommitOperationAdd(path_in_repo='README.md', path_or_fileobj=output / 'README.md')],
+ commit_message=f'Include encoded SS targets for {name} in standard restoration'))
+ return result.oid
+ except HfHubHTTPError as error:
+ if error.response.status_code not in (409, 412) or attempt == 4:
+ raise
+ raise RuntimeError('The training recipe changed during every registration attempt')
+
+
+def publish(config, output, repo=DEFAULT_REPO, *, monitor_views=16, workers=4,
+ shard_bytes=1024**3, follow=False):
+ output = Path(output).resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ status = {'state': 'running', 'repo': repo, 'datasets': {}}
+ for source in source_configs(config):
+ cache, observations = REPO_ROOT / source['cache'], REPO_ROOT / source['dataset']
+ name = hub_name(_json(observations / 'manifest.json')['dataset'])
+ while not (cache / 'manifest.json').exists() or not _json(cache / 'manifest.json').get('complete'):
+ if not follow:
+ raise ValueError(f'Complete SS target preparation first: {cache}')
+ status.update(state='waiting_for_targets', waiting_dataset=name)
+ atomic_json(output / 'status.json', status)
+ time.sleep(30)
+ status.update(state='exporting', waiting_dataset=None)
+ atomic_json(output / 'status.json', status)
+ manifest, metadata, groups, checksums = index_targets(cache, observations, monitor_views=monitor_views)
+ status['state'] = 'publishing'
+ atomic_json(output / 'status.json', status)
+ cache_name = 'front3d' if name == '3dfront' else name
+ index = package(cache, output, COMPONENT, name,
+ destination=Path('outputs/ss_multiobj_depth') / cache_name / 'masked_objects/targets',
+ kind='ss-latent-targets', metadata=metadata, groups=groups, checksums=checksums,
+ details={'source_manifest_sha256': sha256(cache / 'manifest.json'),
+ 'dataset_manifest_sha256': sha256(observations / 'manifest.json'),
+ 'views': len(manifest['entries']), 'target_scope': TARGET_SCOPE,
+ 'training_views': sum(row['split'] == 'train' for row in manifest['entries']),
+ 'latent_shape': [8, 16, 16, 16]},
+ shard_bytes=shard_bytes, publisher=Publisher(repo, workers=workers))
+ revision = register(repo, output, name, index)
+ status['datasets'][name] = {'views': index['views'], 'bytes': index['bytes'], 'revision': revision}
+ atomic_json(output / 'status.json', status)
+ status.update(state='complete', waiting_dataset=None)
+ atomic_json(output / 'status.json', status)
+ return status
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--config', type=Path, required=True)
+ parser.add_argument('--output', type=Path, default=Path('outputs/huggingface/ss_targets'))
+ parser.add_argument('--repo', default=DEFAULT_REPO)
+ parser.add_argument('--monitor-views', type=int, default=16)
+ parser.add_argument('--workers', type=int, default=4)
+ parser.add_argument('--shard-gib', type=float, default=1.)
+ parser.add_argument('--follow', action='store_true', help='Wait for target preparation before each dataset export')
+ args = parser.parse_args()
+ if args.workers < 1 or args.monitor_views < 1 or args.shard_gib <= 0:
+ parser.error('Worker count, monitoring count and shard size must be positive')
+ torch.set_num_threads(1)
+ try:
+ publish(load_config(args.config), args.output, args.repo, monitor_views=args.monitor_views,
+ workers=args.workers, shard_bytes=int(args.shard_gib*1024**3), follow=args.follow)
+ except Exception as error:
+ args.output.mkdir(parents=True, exist_ok=True)
+ path = args.output / 'status.json'
+ status = _json(path) if path.exists() else {}
+ atomic_json(path, {**status, 'state': 'failed', 'error': f'{type(error).__name__}: {error}'})
+ raise
+
+
+if __name__ == '__main__':
+ main()
diff --git a/preprocess/tasks.py b/preprocess/tasks.py
new file mode 100644
index 0000000..f96f60d
--- /dev/null
+++ b/preprocess/tasks.py
@@ -0,0 +1,265 @@
+"""Plan task-specific data transfers and publish their Hugging Face catalog."""
+import argparse
+import json
+from pathlib import Path
+import re
+import subprocess
+
+from preprocess.huggingface import SCHEMA, _json, _relative, _retry
+from preprocess.storage import atomic_json
+from utils.hashing import sha256
+
+
+TASKS = ('eval', 'ss', 'slat-seg', 'slat-shape', 'all-training')
+ROLES = {'ss': ('observations', 'ss'), 'slat-seg': ('observations',),
+ 'slat-shape': ('observations', 'shape/32')}
+KINDS = {'observations': 'compact-training', 'ss': 'ss-latent-targets',
+ 'shape/32': 'object-shape-targets'}
+CARD_START = '<!-- partprobe3d-tasks:start -->'
+CARD_END = '<!-- partprobe3d-tasks:end -->'
+DEFAULT_REPO = 'cubec/PartProbe3D-preprocessed'
+
+
+class Snapshot:
+ """Resolve the Hub revision once and cache only small inventory files."""
+ def __init__(self, repo, revision, cache):
+ from huggingface_hub import HfApi
+ self.repo = repo
+ self.revision = HfApi().dataset_info(repo, revision=revision).sha
+ self.cache = Path(cache)
+ self.indices = {}
+ self.hashes = {}
+
+ def read(self, path):
+ from huggingface_hub import hf_hub_download
+ if path not in self.indices:
+ file = hf_hub_download(self.repo, path, repo_type='dataset', revision=self.revision,
+ local_dir=self.cache)
+ self.indices[path] = _json(file)
+ self.hashes[path] = sha256(file)
+ return self.indices[path]
+
+
+def _names(value, available):
+ names = list(available) if value == 'all' else value.split(',')
+ if not names or len(names) != len(set(names)) or any(name not in available for name in names):
+ raise ValueError(f'Choose unique datasets from: {", ".join(available)}')
+ return names
+
+
+def _component(snapshot, path, *, kind, archive_files=None):
+ relative = _relative(path)
+ index = snapshot.read(f'{relative}/index.json')
+ if (index.get('schema') != SCHEMA or not index.get('complete')
+ or index.get('name') != relative.name or index.get('artifact_kind') != kind):
+ raise ValueError(f'Incomplete or incompatible component: {path}')
+ archives = index['archives']
+ if index.get('bytes') != sum(row['bytes'] for row in archives):
+ raise ValueError(f'Archive sizes differ from the component total: {path}')
+ if archive_files is not None:
+ archives = [row for row in archives if row['file'] in archive_files]
+ result = {'path': path, 'destination': index['destination'],
+ 'index_sha256': snapshot.hashes[f'{relative}/index.json'],
+ 'bytes': sum(row['bytes'] for row in archives), 'archives': len(archives)}
+ if archive_files is not None:
+ result['archive_files'] = [row['file'] for row in archives]
+ return result
+
+
+def plan(snapshot, task, datasets='all'):
+ """Validate every requested dependency before transferring any data archive."""
+ if task not in TASKS:
+ raise ValueError(f'Unknown task: {task}')
+ notes = ['Model weights are separate. Download only the configured model assets.']
+ if task == 'eval':
+ index = snapshot.read('evaluation/index.json')
+ names = _names('all' if datasets == 'evaluation' else datasets, index['datasets'])
+ files = {'metadata.tar'}
+ for name in names:
+ shards = {row['file'] for row in index['archives'] if row['file'].startswith(f'{name}-')}
+ if not shards:
+ raise ValueError(f'No evaluation archives for {name}')
+ files.update(shards)
+ if not any(row['file'] == 'metadata.tar' for row in index['archives']):
+ raise ValueError('The evaluation metadata archive is missing')
+ components = [_component(snapshot, 'evaluation', kind='frozen-evaluation', archive_files=files)]
+ notes += ['Metadata describes the full cohort. Data files cover only the selected datasets.',
+ 'This bundle has RGB, masks and GT meshes. Depth-dependent models need their configured depth estimator.']
+ else:
+ recipe = snapshot.read('training/index.json')
+ if recipe.get('schema') != 'partprobe3d.reproduction.v1' or not recipe.get('complete'):
+ raise ValueError('The active training inventory is incomplete')
+ defaults = recipe['default_datasets']
+ if task != 'all-training':
+ supported = [name for name in defaults if all(
+ f'training/{role}/{name}' in recipe['datasets'][name]['required'] for role in ROLES[task])]
+ omitted = [name for name in defaults if name not in supported]
+ if datasets == 'all' and omitted:
+ notes.append(f'Targets unavailable for {", ".join(omitted)}. These datasets are excluded from this task default.')
+ defaults = supported
+ names = _names(datasets, defaults if datasets == 'all' else recipe['datasets'])
+ if not names:
+ raise ValueError(f'No published datasets support {task}')
+ selected = []
+ for name in names:
+ required = recipe['datasets'][name]['required']
+ paths = required if task == 'all-training' else [f'training/{role}/{name}' for role in ROLES[task]]
+ for path in paths:
+ relative = _relative(path)
+ if relative.parts[0] != 'training' or relative.name != name:
+ raise ValueError('Task downloads must remain in the active training folder')
+ if path not in required:
+ raise ValueError(f'{task} targets are unavailable for {name}: {path}')
+ role = '/'.join(relative.parts[1:-1])
+ if role not in KINDS:
+ raise ValueError(f'Unknown training component: {path}')
+ selected.append((path, KINDS[role]))
+ components = [_component(snapshot, path, kind=kind) for path, kind in selected]
+ if task == 'ss':
+ notes.append('Native SS targets are ready. Online SS training requires no target encoding.')
+ if task == 'slat-seg':
+ notes.append('Segmentation generates instance codes and image features during training. No latent target download is required.')
+ if task == 'slat-shape':
+ notes.append('Use an online shape configuration to avoid a separate feature cache.')
+ notes.append('Custom configs can require optional occlusion data or additional test observations.')
+ return {'schema': 'partprobe3d.task-download.v1', 'repo': snapshot.repo,
+ 'revision': snapshot.revision, 'task': task, 'datasets': names, 'components': components,
+ 'archive_bytes': sum(row['bytes'] for row in components), 'notes': notes}
+
+
+def download_task(repo, task, datasets, destination, revision='main', *, cleanup=True, dry_run=False):
+ from preprocess.huggingface import download
+ snapshot = Snapshot(repo, revision, Path(destination).resolve() / 'outputs/huggingface/tasks')
+ selected = plan(snapshot, task, datasets)
+ print(json.dumps(selected, indent=2), flush=True)
+ if not dry_run:
+ for row in selected['components']:
+ path = _relative(row['path'])
+ kwargs = {'archive_files': row['archive_files']} if 'archive_files' in row else {}
+ download(repo, path.name, destination, snapshot.revision, cleanup=cleanup,
+ bundle_root='' if len(path.parts) == 1 else str(path.parent), **kwargs)
+ return selected
+
+
+def catalog(snapshot):
+ profiles = {}
+ for task in TASKS:
+ default = plan(snapshot, task)
+ profiles[task] = {**default, 'by_dataset': {
+ name: plan(snapshot, task, name) for name in default['datasets']}}
+ return {'schema': 'partprobe3d.task-catalog.v1', 'repo': snapshot.repo,
+ 'data_revision': snapshot.revision, 'profiles': profiles,
+ 'inventory_sha256': dict(snapshot.hashes),
+ 'restore_git_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()}
+
+
+def card_section(inventory=None, repo=DEFAULT_REPO):
+ descriptions = {'eval': 'RGB, masks and GT meshes', 'ss': 'Observations and native SS targets',
+ 'slat-seg': 'Observations only', 'slat-shape': 'Observations and 32³ object shape targets',
+ 'all-training': 'All published training components'}
+ lines = [CARD_START, '## Download by task', '',
+ 'Select a task to avoid unnecessary data transfers.',
+ 'The [task catalog](tasks/index.json) records component paths, sizes, and the data revision.',
+ 'The [task guide](tasks/README.md) lists downloads for individual datasets.', '',
+ '| Task | Required data | Default transfer, GB |', '| --- | --- | ---: |']
+ for task in TASKS:
+ size = f'{inventory["profiles"][task]["archive_bytes"]/1e9:.3f}' if inventory else 'See catalog'
+ lines.append(f'| [`{task}`](tasks/{task}/index.json) | {descriptions[task]} | {size} |')
+ lines += ['', 'Use the current project checkout for these commands.', 'Preview the transfer before downloading:', '',
+ '```bash', f'python -m preprocess.huggingface download --repo {repo} --task ss --dry-run', '```', '',
+ 'Select the task required by this server:', '', '```bash']
+ for task in TASKS[:-1]:
+ lines.append(f'python -m preprocess.huggingface download --repo {repo} --task {task}')
+ lines += ['```', '', 'Select individual datasets with `--dataset`, using commas for multiple datasets.', '', '```bash',
+ f'python -m preprocess.huggingface download --repo {repo} --task eval --dataset picasso',
+ f'python -m preprocess.huggingface download --repo {repo} --task eval --dataset picasso,messykitchen',
+ f'python -m preprocess.huggingface download --repo {repo} --task slat-seg --dataset foundationpose',
+ '```', '', 'FoundationPose supports SS and segmentation. Its shape targets remain unavailable.', '',
+ 'Shape defaults include 3D-FRONT and SAGE. An explicit FoundationPose shape request fails before archive transfer.', '',
+ 'SS uses the published native targets without another target encoding pass.',
+ 'Segmentation computes its instance codes and image features during training.', '',
+ 'Online shape conditioning avoids a separate image-feature cache.', '',
+ 'Model weights remain separate. Download only the assets required by the selected model.', '',
+ 'Old commands without `--task` still restore all training components.', CARD_END]
+ return '\n'.join(lines)
+
+
+def update_card(card, inventory, repo):
+ if inventory:
+ card = re.sub(r'Use project Git revision `[^`]+` or later\.',
+ f'Use project Git revision `{inventory["restore_git_revision"]}` or later.', card)
+ section = card_section(inventory, repo)
+ if CARD_START in card:
+ start, end = card.index(CARD_START), card.index(CARD_END) + len(CARD_END)
+ return card[:start] + section + card[end:]
+ # Put the task choices before the historical all-training instructions.
+ marker = '## Restore tools'
+ position = card.index(marker) if marker in card else len(card.rstrip())
+ return card[:position].rstrip() + '\n\n' + section + '\n\n' + card[position:]
+
+
+def publish(repo, output, *, revision='main'):
+ """Publish small task inventories without moving or uploading data archives."""
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
+ from huggingface_hub.errors import HfHubHTTPError
+ output = Path(output).resolve()
+ for attempt in range(5):
+ snapshot = Snapshot(repo, revision, output / 'remote')
+ inventory = catalog(snapshot)
+ folder = output / 'tasks'
+ folder.mkdir(parents=True, exist_ok=True)
+ atomic_json(folder / 'index.json', inventory)
+ section = card_section(inventory, repo)
+ lines = ['# Task-specific data downloads', '',
+ f'Use project Git revision `{inventory["restore_git_revision"]}` or later.',
+ f'The measured sizes refer to HF data revision `{snapshot.revision}`.',
+ 'Sizes use decimal GB. Local extracted data needs additional space.',
+ 'A dry run reads small indices. It does not transfer data archives.', '',
+ section.replace('](tasks/', ']('), '',
+ '| Task | Dataset | Transfer, GB |', '| --- | --- | ---: |']
+ paths = ['tasks/index.json', 'tasks/README.md']
+ for task, profile in inventory['profiles'].items():
+ (folder / task).mkdir(exist_ok=True)
+ atomic_json(folder / task / 'index.json', profile)
+ paths.append(f'tasks/{task}/index.json')
+ for name, row in profile['by_dataset'].items():
+ lines.append(f'| `{task}` | {name} | {row["archive_bytes"]/1e9:.3f} |')
+ lines += ['', 'Evaluation sizes include the shared metadata archive for each individual dataset.',
+ 'Combined selections download shared metadata once.',
+ 'Existing archives keep their original paths and checksums.',
+ 'No training or evaluation result changes.', '',
+ 'Regenerate this catalog after publishing new components:', '', '```bash',
+ f'python -m preprocess.tasks publish --repo {repo} --output outputs/huggingface/tasks', '```', '']
+ (folder / 'README.md').write_text('\n'.join(lines))
+ card = Path(hf_hub_download(repo, 'README.md', repo_type='dataset', revision=snapshot.revision,
+ local_dir=output / 'remote')).read_text()
+ # Keep the existing cache and benchmark sections while updating the SS command.
+ card = card.replace(f'python -m preprocess.huggingface download --repo {repo}\n```\n\nSS training',
+ f'python -m preprocess.huggingface download --repo {repo} --task ss\n```\n\nSS training')
+ (output / 'README.md').write_text(update_card(card, inventory, repo))
+ paths.append('README.md')
+ try:
+ result = _retry(lambda: HfApi().create_commit(repo_id=repo, repo_type='dataset',
+ parent_commit=snapshot.revision, commit_message='Categorize downloads by evaluation and training task',
+ operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=output / path) for path in paths]))
+ except HfHubHTTPError as error:
+ if error.response is None or error.response.status_code not in (409, 412) or attempt == 4 or revision != 'main':
+ raise
+ continue
+ atomic_json(output / 'status.json', {'complete': True, 'repo': repo, 'revision': result.oid,
+ 'data_revision': snapshot.revision, 'files': paths})
+ return inventory
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('command', choices=('publish',))
+ parser.add_argument('--repo', default=DEFAULT_REPO)
+ parser.add_argument('--output', type=Path, default=Path('outputs/huggingface/tasks'))
+ parser.add_argument('--revision', default='main')
+ args = parser.parse_args()
+ publish(args.repo, args.output, revision=args.revision)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/preprocess/tests/test_reproduction.py b/preprocess/tests/test_reproduction.py
new file mode 100644
index 0000000..c27f13e
--- /dev/null
+++ b/preprocess/tests/test_reproduction.py
@@ -0,0 +1,258 @@
+"""Compact exports retain training tensors and never select deprecated downloads."""
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+from dataloader.dataset import ViewDataset
+from dataloader.extent import ExtentLoader
+from dataloader.prepared import ExtentDataset
+from preprocess.huggingface import extract
+from preprocess.reproduction import (COMPACT_SCHEMA, RECIPE_SCHEMA, download_training, package,
+ refresh_selection, stage_observations, stage_shape)
+from preprocess.storage import atomic_json
+from preprocess.tests.test_validate_dataset import dataset
+from utils.hashing import sha256
+
+
+def test_compact_restore_preserves_tensors_and_adds_optional_test_views(dataset, tmp_path):
+ source, original = dataset
+ staged = tmp_path / 'staged'
+ manifest, metadata, core, held_out, checksums = stage_observations(source, staged, monitor_views=1)
+ output = tmp_path / 'archives'
+ destination = Path('datasets/fixture/extent/point_cloud')
+ index = package(source, output, 'training/observations', 'fixture', destination=destination,
+ kind='compact-training', metadata=metadata, groups=core, checksums=checksums)
+ restored = extract(index, output / 'training/observations/fixture', tmp_path / 'server')
+ assert sha256(restored / 'manifest.json') == sha256(source / 'manifest.json')
+ assert len(ViewDataset(restored)) == 3
+ assert not list(restored.rglob('*.png'))
+ assert not list(restored.rglob('depth.npy'))
+ assert not list(restored.rglob('geometry.npz'))
+ expected = ExtentDataset(source, split='train')
+ actual = ExtentDataset(restored, split='train')
+ assert len(expected) == len(actual) == 2
+ import torch
+ for a, b in zip(expected, actual):
+ for key in ('rgb', 'masks', 'depth', 'memberships', 'coords', 'intrinsics', 'model_to_world'):
+ torch.testing.assert_close(a[key], b[key], rtol=0, atol=0)
+ loader = ExtentLoader(restored)
+ rgb, masks = loader.load_observation(0)
+ arrays = ViewDataset(restored)[0]
+ np.testing.assert_array_equal(rgb, arrays['rgb'])
+ np.testing.assert_array_equal(masks, arrays['image_labels'] + 1)
+ from preprocess.validate_dataset import validate
+ report = validate(restored, workers=1)
+ assert report['validated_views'] == 3
+ assert report['counts']['train']['views'] == 2 and report['counts']['test']['views'] == 1
+ assert report['source_counts'] == original['counts']
+ assert report['selection_sha256'] == sha256(restored / 'compact_training.json')
+ assert '| test | 1 | 1 |' in (restored / 'DATASET_CARD.md').read_text()
+ optional = package(source, output, 'optional/held_out', 'fixture', destination=destination,
+ kind='held-out-observations', metadata=[], groups=held_out, checksums=checksums)
+ extract(optional, output / 'optional/held_out/fixture', tmp_path / 'server')
+ assert len(ViewDataset(restored)) == 4
+ # Repeating the compact restore must preserve separately restored test views.
+ extract(index, output / 'training/observations/fixture', tmp_path / 'server')
+ assert len(ViewDataset(restored)) == 4
+
+
+def test_compact_pack_rejects_corrupt_original_sample(dataset, tmp_path):
+ source, _ = dataset
+ _, metadata, groups, _, checksums = stage_observations(source, tmp_path / 'staged', monitor_views=1)
+ row = json.loads((source / 'manifest.json').read_text())['views'][0]
+ (source / row['sample']).write_bytes(b'corrupt source')
+ with pytest.raises(ValueError, match='Source checksum changed'):
+ package(source, tmp_path / 'archives', 'training/observations', 'fixture',
+ destination=Path('datasets/fixture/extent/point_cloud'), kind='compact-training',
+ metadata=metadata, groups=groups, checksums=checksums)
+
+
+def test_repeated_package_preserves_archive_prefix_after_layout_change(tmp_path):
+ root, output = tmp_path / 'source', tmp_path / 'archives'
+ root.mkdir()
+ image = root / 'rgb.png'
+ image.write_bytes(b'frozen image')
+ arguments = dict(kind='frozen-evaluation', metadata=[], groups=[('fixture', [image], 1)])
+ index = package(root, output, 'optional', 'evaluation',
+ destination=Path('datasets/evaluation/indoor'), **arguments)
+ index['archive_prefix'] = index['destination']
+ index['destination'] = 'datasets/evaluation'
+ atomic_json(output / 'optional/evaluation/index.json', index)
+ repeated = package(root, output, 'optional', 'evaluation',
+ destination=Path('datasets/evaluation'), **arguments)
+ assert repeated == index
+ restored = extract(repeated, output / 'optional/evaluation', tmp_path / 'server')
+ assert (restored / 'rgb.png').read_bytes() == image.read_bytes()
+ assert not (restored / 'indoor').exists()
+
+
+def test_compact_validation_rejects_changed_view_selection(dataset, monkeypatch):
+ from preprocess import validate_dataset
+ root, _ = dataset
+ refresh_selection(root)
+ path = root / 'compact_training.json'
+ selection = json.loads(path.read_text())
+ selection['view_ids'] = selection['view_ids'][:-1]
+ selection['counts'] = {'train': 2, 'test': 1}
+ atomic_json(path, selection)
+ original = validate_dataset._validate_view
+ def changed(root, row):
+ result = original(root, row)
+ refresh_selection(root)
+ return result
+ monkeypatch.setattr(validate_dataset, '_validate_view', changed)
+ with pytest.raises(ValueError, match='selection changed during validation'):
+ validate_dataset.validate(root, workers=1)
+ assert not (root / 'validation.json').exists()
+
+
+def test_object_shape_export_retains_object_identity_and_explicit_exclusions(tmp_path):
+ from slat_multiobj_shape.storage import SCHEMA, object_sha256, read_view_targets
+ root = tmp_path / 'source'
+ file = root / 'views/fixture/good.npz'
+ file.parent.mkdir(parents=True)
+ arrays = dict(schema=np.array(SCHEMA), coords=np.array([[1, 2, 3]], np.uint8),
+ feats=np.ones((1, 32), np.float16), object_index=np.zeros(1, np.int16),
+ object_ids=np.array(['object']), object_status=np.array(['complete']),
+ resolution=np.array(32), model_to_world=np.eye(4), grid_size=np.array(512),
+ scene_coords=np.array([[1, 2, 3]], np.uint8), scene_feats=np.ones((1, 32), np.float16),
+ scene_status=np.array('complete'), scene_scope=np.array('selected_prompt_objects'),
+ scene_seconds=np.array(1.), scene_dual_voxels=np.array(1), scene_error=np.array(''))
+ np.savez_compressed(file, **arrays)
+ row = {'file': 'views/fixture/good.npz', 'split': 'train', 'scene': 'room',
+ 'failed_objects': 0, 'sha256': sha256(file)}
+ atomic_json(root / 'manifest.json', {'schema': SCHEMA, 'resolution': 32,
+ 'entries': {'fixture/good': row, 'fixture/bad': {**row, 'failed_objects': 1}},
+ 'datasets': [], 'models': {}, 'complete': False})
+ manifest, _, groups, _ = stage_shape(root, tmp_path / 'staged')
+ assert manifest['excluded_views'] == ['fixture/bad']
+ assert len(groups) == 1
+ exported = read_view_targets(tmp_path / 'staged' / row['file'])
+ assert object_sha256(exported) == object_sha256(arrays)
+ assert not len(exported['scene_feats']) and str(exported['scene_status']) == 'pending'
+ assert len(read_view_targets(file)['scene_feats']) == 1
+
+
+def test_default_download_pins_recipe_and_excludes_optional_and_deprecated(tmp_path, monkeypatch):
+ import huggingface_hub
+ import preprocess.huggingface
+ revision = 'a' * 40
+ recipe = tmp_path / 'index.json'
+ atomic_json(recipe, {'schema': RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['fixture'],
+ 'datasets': {'fixture': {'required': ['training/observations/fixture', 'training/shape/32/fixture']}},
+ 'optional': {'geometry': '_deprecated/old'}})
+ monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: SimpleNamespace(
+ dataset_info=lambda *a, **k: SimpleNamespace(sha=revision)))
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda *a, **k: str(recipe))
+ calls = []
+ monkeypatch.setattr(preprocess.huggingface, 'download', lambda *a, **k: calls.append((a, k)))
+ download_training('owner/repo', 'all', tmp_path / 'server')
+ assert [call[1]['bundle_root'] for call in calls] == ['training/observations', 'training/shape/32']
+ assert all(call[0][3] == revision and call[1]['cleanup'] for call in calls)
+ data = json.loads(recipe.read_text())
+ data['datasets']['fixture']['required'].append('_deprecated/fixture')
+ atomic_json(recipe, data)
+ with pytest.raises(ValueError, match='active training folder'):
+ download_training('owner/repo', 'all', tmp_path / 'server')
+
+
+def test_compact_selection_rejects_another_manifest(dataset):
+ root, _ = dataset
+ atomic_json(root / 'compact_training.json', {'schema': COMPACT_SCHEMA,
+ 'source_manifest_sha256': 'wrong', 'view_ids': []})
+ with pytest.raises(ValueError, match='source manifest'):
+ ViewDataset(root)
+
+
+@pytest.mark.parametrize('corrupt', [False, True])
+def test_upload_cleanup_requires_verified_remote_digest(tmp_path, monkeypatch, corrupt):
+ import huggingface_hub
+ from preprocess.reproduction import Publisher
+ path = tmp_path / 'archive.tar'
+ path.write_bytes(b'verified data')
+ digest = sha256(path)
+ entry = SimpleNamespace(path='training/observations/fixture/train.tar', size=path.stat().st_size,
+ lfs=SimpleNamespace(sha256='wrong' if corrupt else digest))
+ api = SimpleNamespace(dataset_info=lambda *a, **k: SimpleNamespace(siblings=[]),
+ create_commit=lambda **k: SimpleNamespace(oid='commit'),
+ get_paths_info=lambda *a, **k: [entry])
+ monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: api)
+ publisher = Publisher('owner/repo')
+ publisher.ready(entry.path, path, {'bytes': path.stat().st_size, 'sha256': digest})
+ if corrupt:
+ with pytest.raises(ValueError, match='verification failed'):
+ publisher.flush()
+ assert path.read_bytes() == b'verified data'
+ else:
+ publisher.flush()
+ assert not path.exists()
+
+
+def test_deprecation_rejects_concurrently_changed_legacy_file(tmp_path):
+ from preprocess.reproduction import _copy_files, LEGACY_REVISION
+ old = SimpleNamespace(rfilename='bundles/fixture/train.tar', size=10, blob_id='blob',
+ lfs=SimpleNamespace(sha256='original'))
+ changed = SimpleNamespace(rfilename=old.rfilename, size=10, blob_id='changed',
+ lfs=SimpleNamespace(sha256='changed'))
+ def info(*args, **kwargs):
+ return SimpleNamespace(siblings=[old if kwargs.get('revision') == LEGACY_REVISION else changed])
+ api = SimpleNamespace(dataset_info=info, create_commit=lambda **k: pytest.fail('Changed data must remain untouched'))
+ with pytest.raises(ValueError, match='source changed'):
+ _copy_files(api, 'owner/repo', tmp_path,
+ {old.rfilename: '_deprecated/old/' + old.rfilename}, remove_sources=True)
+
+
+@pytest.mark.parametrize('optional,keep', [(False, False), (True, False), (False, True)])
+def test_download_command_defaults_to_active_data_and_removes_archives(monkeypatch, optional, keep):
+ import sys
+ from preprocess import huggingface
+ arguments = ['download', '--repo', 'owner/repo']
+ if optional:
+ arguments += ['--dataset', 'fixture', '--optional', 'geometry']
+ if keep:
+ arguments += ['--keep-archives']
+ monkeypatch.setattr(sys, 'argv', ['huggingface', *arguments])
+ calls = []
+ monkeypatch.setattr(huggingface, 'download', lambda *a, **k: calls.append((a, k)))
+ huggingface.main()
+ assert calls[0][1]['cleanup'] is not keep
+ assert calls[0][1]['bundle_root'] == ('optional/geometry' if optional else None)
+ assert calls[0][0][1] == ('fixture' if optional else 'all')
+
+
+@pytest.mark.parametrize('dataset,bundle_root,optional', [
+ ('evaluation', None, False), ('ycbv', 'optional/evaluation', True)])
+def test_evaluation_download_routes_required_cohort_and_optional_dataset(monkeypatch, dataset, bundle_root, optional):
+ import sys
+ from preprocess import huggingface
+ arguments = ['huggingface', 'download', '--repo', 'owner/repo', '--dataset', dataset]
+ if optional:
+ arguments.extend(['--optional', 'evaluation'])
+ monkeypatch.setattr(sys, 'argv', arguments)
+ calls = []
+ monkeypatch.setattr(huggingface, 'download', lambda *a, **k: calls.append((a, k)))
+ huggingface.main()
+ assert calls[0][0][1] == dataset
+ assert calls[0][1]['bundle_root'] == bundle_root
+ assert calls[0][1]['cleanup']
+
+
+def test_online_shape_configuration_preserves_model_and_optimizer_settings(tmp_path):
+ from preprocess.reproduction import configure_shape
+ original = {'model': {'rank': 8, 'local_condition_mode': 'assigned_object'},
+ 'training': {'learning_rate': .0001, 'optimizer': {'betas': [.9, .95]}},
+ 'prepared_datasets': [{'targets': 'datasets/fixture/slat/32/targets',
+ 'features': 'old', 'training_targets': 'old'}],
+ 'require_scene_targets': False, 'features': 'old', 'training_targets': 'old'}
+ source = tmp_path / 'source.json'
+ atomic_json(source, original)
+ output = tmp_path / 'generated/online.json'
+ actual = configure_shape(source, output)
+ assert actual['model'] == original['model'] and actual['training'] == original['training']
+ assert actual['prepared_datasets'] == [{'targets': 'datasets/fixture/slat/32/targets'}]
+ assert not {'features', 'training_targets'} & actual.keys()
+ assert json.loads(source.read_text()) == original
+ assert configure_shape(source, output) == actual
diff --git a/preprocess/tests/test_ss_targets.py b/preprocess/tests/test_ss_targets.py
new file mode 100644
index 0000000..7d7636f
--- /dev/null
+++ b/preprocess/tests/test_ss_targets.py
@@ -0,0 +1,236 @@
+"""Portable SS targets retain exact supervision without another encoding pass."""
+from copy import deepcopy
+import hashlib
+import json
+from pathlib import Path
+import shutil
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+import torch
+
+from preprocess import ss_targets as module
+from preprocess.front3d.splits import MIDI_TEST_ROOM_IDS
+from preprocess.generator_targets import VoxelSettings
+from preprocess.huggingface import extract
+from preprocess.reproduction import package, stage_observations
+from preprocess.storage import atomic_json, atomic_npz
+from preprocess.tests.test_extent_spec import CameraCaptures, CameraTargets
+from ss_multiobj_depth.config import TARGET_SCOPE
+from ss_multiobj_depth.dataloader import FEATURE_SCHEMA, OnlineObservationDataset, SSDepthDataset
+from utils.hashing import sha256
+
+
+@pytest.fixture
+def targets(tmp_path):
+ capture, observations, cache = (tmp_path / name for name in ('map', 'observations', 'cache'))
+ source = {'complete': True, 'views': [
+ {'scene': scene, 'source_view': str(view), 'frame': str(view), 'split': split}
+ for scene, split in [('train-house/train-room', 'train'), (MIDI_TEST_ROOM_IDS[0], 'test')]
+ for view in range(2)]}
+ class Captures(CameraCaptures):
+ def capture_view(self, row):
+ view = super().capture_view(row)
+ for name in ('rgb', 'instance_labels', 'depth'):
+ values = getattr(view, name)
+ setattr(view, name, np.repeat(np.repeat(values, 16, axis=0), 16, axis=1))
+ view.camera['renderProductResolution'] = [64, 64]
+ intrinsics = np.asarray(view.camera['intrinsics_K'])
+ intrinsics[:2] *= 16
+ view.camera['intrinsics_K'] = intrinsics.tolist()
+ return view
+ Captures(source, {}).generate_captures(capture)
+ CameraTargets.generate_targets(capture, observations, VoxelSettings(64, minimum_mask_pixels=1, extent_strategy='mesh'))
+ data = SSDepthDataset(observations)
+ cache.mkdir()
+ models = {'upstream': 'third_party/Pixal3D', 'upstream_revision': 'revision',
+ 'encoder': 'checkpoints/encoder', 'decoder': 'checkpoints/decoder',
+ 'paired_decoder': 'checkpoints/paired_decoder', 'dino': 'checkpoints/DINOv3'}
+ files = {models[key] + suffix: 'weight-hash' for key in ('encoder', 'decoder', 'paired_decoder')
+ for suffix in (('.safetensors',) if key == 'paired_decoder' else ('.json', '.safetensors'))}
+ files['checkpoints/DINOv3/model.safetensors'] = 'image-weight-hash'
+ policy = {'target_scope': TARGET_SCOPE, 'dataset': data.provenance(),
+ 'settings': {'models': models}, 'models': {'files': files, 'upstream_revision': 'revision'}}
+ atomic_json(cache / 'policy.json', policy)
+ rows, expected = [], {}
+ for number, row in enumerate(data.rows):
+ sample = data[number]
+ occupancy = sample['occupancy'][0].numpy()
+ directory = hashlib.sha256(row['id'].encode()).hexdigest()[:24]
+ folder = cache / directory
+ folder.mkdir()
+ clean = torch.arange(32768, dtype=torch.float32).reshape(8, 16, 16, 16) / 32768 + number
+ if number % 2:
+ clean = clean.half()
+ expected[row['id']] = clean.clone()
+ torch.save({'clean': clean, 'historical_image_features': torch.ones(8)}, folder / 'features.pt')
+ atomic_npz(folder / 'targets.npz', occupancy=occupancy)
+ arrays, camera = data.read(number)
+ atomic_json(folder / 'geometry.json', {'grid': data.grid(arrays, camera).as_dict()})
+ entry = {**{key: row[key] for key in ('id', 'scene', 'split')}, 'directory': directory,
+ 'inputs': {key: sha256(observations / row[key]) for key in ('sample', 'camera', 'scene_gt')},
+ 'occupied_cells': int(occupancy.sum()),
+ 'files': {name: sha256(folder / name) for name in ('features.pt', 'targets.npz', 'geometry.json')}}
+ atomic_json(folder / 'complete.json', entry)
+ rows.append(entry)
+ atomic_json(cache / 'manifest.json', {'schema': FEATURE_SCHEMA, 'complete': True, 'dataset': '3D-FRONT',
+ 'policy_sha256': sha256(cache / 'policy.json'), 'entries': rows})
+ return observations, cache, expected
+
+
+def test_restore_retains_exact_latents_and_loads_without_original_environment(targets, tmp_path, monkeypatch):
+ observations, cache, expected = targets
+ manifest, metadata, groups, checksums = module.index_targets(cache, observations, monitor_views=1)
+ assert len(manifest['entries']) == 4
+ original_manifest = sha256(cache / 'manifest.json')
+ original_policy = sha256(cache / 'policy.json')
+ policy = json.loads((cache / 'policy.json').read_text())
+ assert policy['dataset']['root'] == str(observations.resolve())
+ for row in manifest['entries']:
+ saved = torch.load(cache / row['directory'] / 'features.pt', weights_only=True)
+ assert 'historical_image_features' in saved
+ assert torch.equal(saved['clean'], expected[row['id']])
+ assert saved['clean'].dtype == expected[row['id']].dtype
+ module.index_targets(cache, observations, monitor_views=1)
+ assert sha256(cache / 'manifest.json') == original_manifest
+ output = tmp_path / 'archives'
+ index = package(cache, output, 'training/ss', '3dfront',
+ destination=Path('outputs/ss_multiobj_depth/front3d/masked_objects/targets'),
+ kind='ss-latent-targets', metadata=metadata, groups=groups, checksums=checksums)
+ server = tmp_path / 'another-server'
+ restored = extract(index, output / 'training/ss/3dfront', server)
+ assert sha256(restored / 'manifest.json') == original_manifest
+ assert sha256(restored / 'policy.json') == original_policy
+ _, obs_metadata, obs_groups, _, obs_checksums = stage_observations(observations, tmp_path / 'obs-stage', monitor_views=1)
+ obs_index = package(observations, output, 'training/observations', '3dfront',
+ destination=Path('datasets/3dfront/extent/point_cloud'), kind='compact-training',
+ metadata=obs_metadata, groups=obs_groups, checksums=obs_checksums)
+ restored_observations = extract(obs_index, output / 'training/observations/3dfront', server)
+ shutil.rmtree(observations)
+ shutil.rmtree(cache)
+ import ss_multiobj_depth.prepare
+ monkeypatch.setattr(ss_multiobj_depth.prepare, 'load_target_encoder',
+ lambda *a, **k: pytest.fail('Restoration must not invoke the SS encoder'))
+ for split, count in [('train', 2)]:
+ data = OnlineObservationDataset(restored_observations, restored, split=split)
+ assert len(data) == count
+ for row, sample in zip(data.rows, data):
+ assert torch.equal(sample['clean'], expected[row['id']])
+ assert sample['clean'].dtype == expected[row['id']].dtype
+ assert sample['rgb'].shape == (3, 64, 64)
+
+
+@pytest.mark.parametrize('damage', ['latent', 'incomplete', 'dataset', 'missing_view'])
+def test_export_rejects_corrupt_or_incompatible_targets(targets, tmp_path, damage):
+ observations, cache, _ = targets
+ path = cache / 'manifest.json'
+ manifest = json.loads(path.read_text())
+ if damage == 'latent':
+ (cache / manifest['entries'][0]['directory'] / 'features.pt').write_bytes(b'corrupt')
+ elif damage == 'incomplete':
+ manifest['complete'] = False
+ atomic_json(path, manifest)
+ elif damage == 'dataset':
+ (observations / 'manifest.json').write_text((observations / 'manifest.json').read_text() + '\n')
+ else:
+ manifest['entries'] = []
+ atomic_json(path, manifest)
+ with pytest.raises(ValueError):
+ module.index_targets(cache, observations, monitor_views=1)
+
+
+def test_registration_preserves_remote_edits_and_adds_targets_to_default_download(tmp_path, monkeypatch):
+ import httpx
+ import huggingface_hub
+ from huggingface_hub.errors import HfHubHTTPError
+ recipe = {'schema': module.RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['3dfront', 'sage'],
+ 'datasets': {name: {'bytes': 10, 'training_views': 2, 'required': [f'training/observations/{name}'],
+ 'source_manifest_sha256': 'dataset', 'ss_targets': {'bytes': 2, 'views': 3}}
+ for name in ('3dfront', 'sage', 'foundationpose')}, 'optional': {}}
+ del recipe['datasets']['foundationpose']['ss_targets']
+ remote = tmp_path / 'remote'
+ remote.mkdir()
+ api = SimpleNamespace(dataset_info=lambda *a, **k: SimpleNamespace(sha='revision'))
+ attempts = []
+ def download(repo, filename, **kwargs):
+ if filename == 'training/index.json':
+ value = deepcopy(recipe)
+ if attempts:
+ value['optional']['concurrent_evaluation'] = {'bytes': 123}
+ path = remote / 'index.json'
+ atomic_json(path, value)
+ else:
+ path = remote / 'README.md'
+ path.write_text('# Existing card\n\nKeep the evaluation section.\n')
+ return str(path)
+ def commit(**kwargs):
+ attempts.append(kwargs)
+ if len(attempts) == 1:
+ raise HfHubHTTPError('Concurrent edit', response=httpx.Response(409, request=httpx.Request('POST', 'https://hf.test')))
+ return SimpleNamespace(oid='registered')
+ api.create_commit = commit
+ monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: api)
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', download)
+ output = tmp_path / 'output'
+ output.mkdir()
+ index = {'dataset_manifest_sha256': 'dataset', 'bytes': 5, 'views': 3, 'training_views': 2}
+ assert module.register('owner/repo', output, 'foundationpose', index) == 'registered'
+ actual = json.loads((output / 'training/index.json').read_text())
+ assert actual['optional']['concurrent_evaluation']['bytes'] == 123
+ assert actual['datasets']['foundationpose']['required'][-1] == 'training/ss/foundationpose'
+ assert actual['datasets']['foundationpose']['bytes'] == 15
+ assert actual['default_datasets'] == ['3dfront', 'sage', 'foundationpose']
+ assert 'Keep the evaluation section.' in (output / 'README.md').read_text()
+ assert all(attempt['parent_commit'] == 'revision' for attempt in attempts)
+
+
+def test_republication_retains_only_compatible_targets_and_standard_download_restores_them(tmp_path, monkeypatch):
+ import huggingface_hub
+ import preprocess.huggingface
+ from preprocess.reproduction import download_training
+ current = {'schema': module.RECIPE_SCHEMA, 'complete': True, 'default_datasets': ['3dfront'],
+ 'datasets': {'3dfront': {'bytes': 10, 'required': ['training/observations/3dfront'],
+ 'source_manifest_sha256': 'dataset'}}, 'optional': {}}
+ previous = deepcopy(current)
+ previous['datasets']['3dfront']['ss_targets'] = {'component': 'training/ss/3dfront', 'bytes': 5, 'views': 3}
+ previous['restore_git_revision'] = 'code'
+ path = tmp_path / 'registered.json'
+ atomic_json(path, previous)
+ monkeypatch.setattr(huggingface_hub, 'HfApi', lambda: SimpleNamespace(
+ dataset_info=lambda *a, **k: SimpleNamespace(sha='revision')))
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda *a, **k: str(path))
+ module.retain_registered(current, 'owner/repo', tmp_path)
+ module.retain_registered(current, 'owner/repo', tmp_path)
+ assert current['datasets']['3dfront']['bytes'] == 15
+ assert current['datasets']['3dfront']['required'] == ['training/observations/3dfront', 'training/ss/3dfront']
+ atomic_json(path, current)
+ calls = []
+ monkeypatch.setattr(preprocess.huggingface, 'download', lambda *a, **k: calls.append(k['bundle_root']))
+ download_training('owner/repo', 'all', tmp_path)
+ assert calls == ['training/observations', 'training/ss']
+ current['datasets']['3dfront']['source_manifest_sha256'] = 'changed'
+ current['datasets']['3dfront'].pop('ss_targets')
+ current['datasets']['3dfront']['required'] = ['training/observations/3dfront']
+ module.retain_registered(current, 'owner/repo', tmp_path)
+ assert 'ss_targets' not in current['datasets']['3dfront']
+
+
+def test_complete_card_removes_ss_preparation_and_retains_other_sections():
+ recipe = {'restore_git_revision': 'current-code', 'default_datasets': ['3dfront', 'sage', 'foundationpose'],
+ 'datasets': {name: {'bytes': 1000000000, 'ss_targets': {'views': 10, 'bytes': 100}}
+ for name in ('3dfront', 'sage', 'foundationpose')}}
+ card = ('The default transfer is **1.00 GB**, including old data.\n\n'
+ '## Restore tools\n\nold bootstrap patch\n\n## Default download\n\n'
+ 'The command restores 3D-FRONT, SAGE-10k, and their 32³ object shape targets.\n'
+ 'FoundationPose requires explicit selection and supports SS and segmentation.\n'
+ 'Run SS preparation before SS training.\n'
+ 'python -m ss_multiobj_depth.prepare --config ss_multiobj_depth/configs/front3d_sage.json\n'
+ 'python -m ss_multiobj_depth.train --config ss_multiobj_depth/configs/front3d_sage.json\n'
+ '\n## Evaluation\n\nKeep evaluation links.\n')
+ updated = module.update_card(card, recipe, 'owner/repo')
+ assert '**3.00 GB**' in updated and 'current-code' in updated
+ assert 'old bootstrap patch' not in updated and 'ss_multiobj_depth.prepare' not in updated
+ assert 'Keep evaluation links.' in updated and 'FoundationPose shape targets remain unavailable.' in updated
+ assert 'python -m preprocess.huggingface download --repo owner/repo' in updated
+ assert module.update_card(updated, recipe, 'owner/repo') == updated
diff --git a/preprocess/validate_dataset.py b/preprocess/validate_dataset.py
index d9131c6..7eac2ea 100644
--- a/preprocess/validate_dataset.py
+++ b/preprocess/validate_dataset.py
@@ -28,11 +28,16 @@ def _validate_view(root, row):
sample = vd.canonical_sample(vd.load_npz(root / row['sample']), gt)
folder = root / row['view_directory']
stamp = json.loads((folder / 'complete.json').read_text())
+ compact = (root / 'compact_training.json').exists()
+ required = {Path(row['sample']).name, Path(row['camera']).name, 'objects.json'}
for filename, checksum in stamp['sha256'].items():
+ if compact and filename not in required:
+ continue
if sha256(folder / filename) != checksum:
raise ValueError(f'Checksum mismatch: {folder / filename}')
- with Image.open(folder / 'rgb.png') as im:
- np.testing.assert_array_equal(np.asarray(im), sample['rgb'])
+ if not compact:
+ with Image.open(folder / 'rgb.png') as im:
+ np.testing.assert_array_equal(np.asarray(im), sample['rgb'])
for name, key in (('instance_labels.png', 'image_labels'),
('support_instance_labels.png', 'all_image_labels')):
if (folder / name).exists():
@@ -50,8 +55,11 @@ def _validate_view(root, row):
table = json.loads((folder / 'objects.json').read_text())['prompts']
for prompt in table:
k = prompt['prompt_index']
- with Image.open(folder / prompt['mask']) as im:
- mask = np.asarray(im)
+ if compact:
+ mask = (sample['image_labels'] == k).astype(np.uint8) * 255
+ else:
+ with Image.open(folder / prompt['mask']) as im:
+ mask = np.asarray(im)
np.testing.assert_array_equal(mask != 0, sample['image_labels'] == k)
if set(np.unique(mask)) - {0, 255}:
raise ValueError('Mask PNG is not lossless binary')
@@ -146,9 +154,11 @@ def validate(root, *, write_card=True, workers=DEFAULT_WORKERS):
"""Check all views with isolated CPU workers and publish one complete report."""
if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1:
raise ValueError('Validation workers must be a positive integer')
+ selection_path = Path(root) / 'compact_training.json'
+ selection_sha256 = sha256(selection_path) if selection_path.exists() else None
dataset = ViewDataset(root)
rows = dataset.views
- if len(rows) != dataset.manifest["expected_views"]:
+ if len(dataset.manifest['views']) != dataset.manifest["expected_views"]:
raise ValueError("Completed manifest has the wrong capture count")
if len({Path(r["file"]).name for r in rows}) != len(rows):
raise ValueError("Sample filenames collide in a feature cache")
@@ -185,9 +195,38 @@ def validate(root, *, write_card=True, workers=DEFAULT_WORKERS):
"checks": ["artifact hashes", "RGB/depth/label alignment", "binary mask/object identity",
"sparse/dense occupancy equality", "shared scene GT and prompt columns",
"scene split separation", "unique cache filenames"]}
+ current_selection_sha256 = sha256(selection_path) if selection_path.exists() else None
+ if current_selection_sha256 != selection_sha256:
+ raise ValueError('Restored view selection changed during validation')
+ if selection_sha256 is not None:
+ restored_counts = {split: {
+ 'scenes': len({row['scene'] for row in rows if row['split'] == split}),
+ 'views': sum(row['split'] == split for row in rows)}
+ for split in sorted({row['split'] for row in rows})}
+ report.update(scope='restored_compact_views', full_validation=len(rows) == dataset.manifest['expected_views'],
+ source_views=dataset.manifest['expected_views'], source_counts=report['counts'],
+ counts=restored_counts, selection_sha256=selection_sha256)
vd.write_json(dataset.root / "validation.json", report)
if not write_card:
return report
+ if report.get('scope') == 'restored_compact_views':
+ card = [f"# {dataset.manifest['dataset']} compact observations", '',
+ f'The validator checked {images} views, {len(scenes)} scenes, and {mask_count} prompt masks.',
+ 'The table describes restored views.',
+ f"The original source manifest lists {report['source_views']} views.", '',
+ '| Split | Scenes | Views |', '| --- | ---: | ---: |']
+ for split, counts in report['counts'].items():
+ card.append(f"| {split} | {counts['scenes']} | {counts['views']} |")
+ card.extend(['', 'Sample NPZ files contain RGB, depth, visible labels, and per-object occupancy.',
+ 'Saved calibration and object mappings remain available.',
+ 'The samples retain hidden object surfaces and overlapping labels.',
+ 'NPZ labels use zero-based object indices and -1 for context.',
+ 'The default training download omits separate PNG, depth, and mesh exports.',
+ 'The export preserves the original manifest bytes.', '',
+ '[Source inventory](manifest.json).',
+ '[Validation report](validation.json).', ''])
+ (dataset.root / 'DATASET_CARD.md').write_text('\n'.join(card))
+ return report
card = [f"# {dataset.manifest['dataset']} — converted per-view dataset", "",
f"Schema: `{vd.SCHEMA}`. Validated **{images} captures**, **{len(scenes)} scenes**, "
f"and **{mask_count} binary object masks**.", "",
diff --git a/ss_multiobj_depth/README.md b/ss_multiobj_depth/README.md
index 8307513..fbcbca8 100644
--- a/ss_multiobj_depth/README.md
+++ b/ss_multiobj_depth/README.md
@@ -13,6 +13,121 @@ Partial mode connects SS and the native SLAT shape stage. Mesh evaluation uses t
In this document, SS means sparse structure, and GT means ground truth.
An extent defines the spatial bounds of a voxel grid.
+## Configuration inventory
+
+This table collects the controls for SS training and inference.
+
+**Keep** marks active controls. **Review** marks candidates for deprecation. **Compatibility** marks historical inputs. **Fixed** marks architectural requirements.
+These labels are review recommendations. They do not change supported behavior.
+
+Control locations are:
+
+- **Run:** the selected stage JSON, including the [CLI training default](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json).
+- **Optimizer:** the shared [optimization recipe](../utils/training/configs/default.json), selected through `training.optimizer_config`.
+- **CFG:** the `ss` section of the shared [CFG profile](../utils/training/configs/cfg.json), selected through `cfg_config`.
+
+The CLI default uses object means, learned coverage gates, and online conditions across all three datasets.
+Earlier point-sampling and cached presets remain available through explicit configurations.
+The [two-dataset coverage preset](configs/front3d_sage_object_mean_image_coverage_gate.json) retains its historical dataset mix and batch settings.
+
+| Area | Control and location | Current value or choices | Recommendation and dependency |
+| --- | --- | --- | --- |
+| Conditioning | Run: `model.voxel_aggregation` | CLI: `object_mean`. Earlier explicit presets retain `point`. | **Keep** object means as the default. **Review** the earlier point branch. |
+| Conditioning | Run: `model.voxel_condition_mode` | `depth_embedding`. Alternative: `additive`. | **Keep** the embedding gate and additive conditioning. Object means require `depth_embedding`. |
+| Conditioning | Run: `model.voxel_condition_hidden_channels` | `64` for the embedding gate, `0` for additive mode. | **Keep** gate width. The additive value depends on retaining that branch. |
+| Conditioning | Run: `model.depth_channels` | `128`. Positive embedding width. | **Keep.** This controls the shared depth encoder. |
+| Conditioning | Run: `model.voxel_image_features` | `dino` only. | **Fixed.** Local features use DINOv3. This selector applies to object means. |
+| Conditioning | Whole-mask descriptor | DINOv3/NAF, 2048 channels, in object-mean mode. | **Fixed.** SS exposes no separate mask-feature selector. |
+| Conditioning | Run: `model.voxel_coverage_weighting` | Coverage preset: `learned_gate`. Earlier object means: `area`. | **Keep** learned coverage. **Review** area multiplication. Learned coverage requires object means. |
+| Attention | Run: `model.cross_attention_mode` | `global`. Alternative: `occlusion_object`. | **Keep** global attention. **Review** object attention and its occlusion dependencies. Object means require `global`. |
+| Adapters | Run: `model.adapter_method` | `shared` resolves to `lora`. Explicit `lora` or `nora` also works. | **Keep** the shared selector. **Review** per-run overrides after comparisons finish. |
+| Adapters | Run: `model.image_projection_adaptation` | `shared` resolves to `lora`. Alternatives: `full`, `nora`, `lora`. | **Keep** shared image adapters. **Review** alternate branches after checking checkpoints and ablations. |
+| Adapters | Run: `model.rank`, `model.alpha` | `8`, `8.0`. SS also accepts rank `0`. | **Keep** adapter dimensions. **Review** rank-zero training if no experiment needs it. |
+| Adapters | Optimizer: `adapter_method` | `lora`. Alternative: `nora`. | **Keep.** This selects backbone and image adapters across all three stages. |
+| Optimizer | Optimizer: `optimizer.name` | `AdamW` only. | **Fixed.** Consider removing this redundant selector from future presets. |
+| Optimizer | Optimizer: `learning_rate` | `1e-4`. | **Keep.** Target rate for new layers. |
+| Optimizer | Optimizer: `optimizer.adapter_learning_rate` | `1e-4`. | **Keep.** Target rate for adapter matrices. |
+| Optimizer | Optimizer: `optimizer.betas`, `optimizer.eps` | `[0.9, 0.95]`, `1e-8`. | **Keep.** Shared optimizer controls. |
+| Optimizer | Optimizer: `weight_decay` | `0.01`. | **Keep.** Decay for non-adapter matrices. |
+| Optimizer | Optimizer: `optimizer.adapter_weight_decay` | `0.01`. | **Keep.** Decay for adapter matrices. |
+| Optimizer | Optimizer: `optimizer.bias_norm_scalar_weight_decay` | `0`. | **Keep.** Includes biases, normalization parameters, scalars, and other vectors. |
+| Optimizer | Optimizer: `optimizer.warmup_steps` | `500` optimizer updates. | **Keep one control.** The loader derives `training.warmup` from this value. |
+| EMA | Optimizer: `ema_decay` | `0.999`. `null` disables EMA. | **Keep.** EMA averages trainable parameters only. |
+| EMA | Run: `inference_weights` | Omitted, resolves to `auto`. Alternatives: `raw`, `ema`. | **Keep.** Auto selects EMA when available, otherwise raw weights. |
+| CFG | CFG: `cfg_dropout` | `0.1`. | **Keep.** Joint condition dropout during training. |
+| CFG | CFG: `guidance_strength` | `7.5`. | **Keep.** Resolves to `sampling.cfg_strength` for SS inference. |
+| CFG | CFG: `guidance_rescale` | `0.7`. | **Keep.** Resolves to `sampling.cfg_rescale`. |
+| CFG | CFG: `guidance_interval` | `[0.6, 1.0]`. | **Keep.** Resolves to `sampling.cfg_interval`. |
+| Sampling | Run: `sampling.steps`, `sampling.rescale_t` | `12`, `5`. | **Keep.** These control inference integration, separately from CFG. |
+| Objective | Loss and timestep distribution | Native dense MSE. Time is `sigmoid(N(1,1))`. | **Fixed.** No loss-weight or timestep-distribution selector exists. |
+| Data | Run: `sources[].dataset`, `sources[].cache` | 3D-FRONT and SAGE, sampled with equal probability. | **Keep.** Combined runs need distinct datasets and cache paths. |
+| Data | Run: `dataset`, `cache` | Used instead of `sources` for a single dataset. | **Keep.** Single-source preparation and training still use this form. |
+| Data | Run: `training.conditioning_source` | CLI: omitted, resolves to `cached`. Coverage preset: `online`. | **Keep both pending a default decision.** Online extraction requires object means and verified cached SS targets. |
+| Data | Run: `depth_source`, `moge_config` | Training: `gt`. Inference uses the MoGe-3 configuration. | **Keep.** Training requires saved GT depth and calibration. |
+| Extent | Evaluation: `method_config.extent_spec`, including `strategy` and `options` | Inference uses `point_cloud` defaults. Training reads the saved dataset grid. | **Keep** inference extent controls. The training JSON rejects extent overrides. See [extent behavior](#inference-extent-definition). |
+| Augmentation | Run: `training.depth_augmentation.noise_probability` | `0.3`. | **Keep.** Probability of Gaussian depth noise for each view. |
+| Augmentation | Run: `training.depth_augmentation.noise_std_fraction` | `0.015625`. | **Keep.** Noise standard deviation as a fraction of cube size. |
+| Augmentation | Run: `training.depth_augmentation.pixel_dropout` | `0.1`. | **Keep.** Independent removal of valid depth pixels during training. |
+| Training | Run: `training.steps` | `20000`. | **Keep.** Number of optimizer updates. |
+| Training | Run: `training.batch_size`, `training.accumulation` | `16`, `1`. Effective batch: `16`. | **Keep.** These control memory use and effective batch size. |
+| Training | Run: `training.workers` | `4`. | **Keep.** CPU data-loader workers. |
+| Monitoring | Run: `training.save_every`, `training.eval_every`, `training.eval_limit` | `500`, `500`, `8` test views per dataset. | **Keep.** Zero evaluation cadence disables scheduled monitoring. |
+| Monitoring | Run: `training.wandb_mode`, `wandb_project`, `wandb_entity` | `online`, `PartProbe3D`, `null`, all under `training`. | **Keep.** W&B mode also accepts `offline` and `disabled`. |
+| Runtime | Run: `device`, `seed`, `output`, `checkpoints` | `cuda:0`, `0`, preset-specific directories. | **Keep.** Select a logical device from the visible GPUs. |
+| Assets | Run: `models.*` | Pinned Pixal3D, DINOv3, SS encoder/decoder, and optional NAF assets. | **Keep.** Asset paths and source revisions define initialization and provenance. |
+| CLI | Training: `--config`, `--resume`, `--accept-source-changes` | Default preset, fresh run, strict source checks. | **Keep.** These select the run and control explicit resume behavior. |
+| CLI | Preparation: `--shard`, `--shards` | `0`, `1`. | **Keep.** Preparation can process independent interleaved shards. |
+| Compatibility | Inline optimizer/CFG values in saved runs | Resolved historical settings. | **Compatibility.** New presets use shared files. Inline overrides cannot accompany their corresponding profile reference. |
+| Compatibility | Optimizer: `optimizer.adapter_learning_rate_after_warmup`, `optimizer.exclude_bias_norm_from_weight_decay` | Absent from the shared default. Earlier rate and decay policies. | **Review** independent scheduling. **Compatibility** for the older decay flag. |
+
+The equations below explain the supported branches.
+The table is the configuration reference, including candidates for deprecation.
+Historical experiment sections retain the values used by those runs.
+Saved run configurations retain resolved optimization and CFG values with their source hashes.
+The [configuration loader](config.py) and [shared voxel settings](../models/voxel_condition.py) define validation and checkpoint compatibility.
+
+## Default training
+
+The default includes 3D-FRONT, SAGE-10k, and FoundationPose with equal sampling probability.
+It uses a real batch of 16 and one accumulation step.
+The [preset for `cuda:1`](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json) selects the second visible GPU and separate run directories.
+It initializes from pretrained Pixal3D SS weights.
+
+Local image conditions use 1024-channel DINOv3 features.
+Whole-mask descriptors use 2048-channel DINOv3/NAF features.
+Object means use depth embeddings and raw mask coverage in learned gates.
+Native global image cross-attention remains enabled.
+The backbone and image projections use rank-8 LoRA with alpha 8 and trainable image biases.
+
+Both learning rates target `1e-4` after 500 linear warmup updates.
+AdamW uses betas `[0.9, 0.95]`, matrix decay `0.01`, and zero decay for biases and normalization parameters.
+The run uses 20,000 optimizer updates, EMA decay `0.999`, and online W&B logging.
+It saves checkpoints and evaluates eight test views per dataset every 500 updates.
+Training uses GT depth with the configured noise and dropout.
+
+The [portable SS guide](../preprocess/SS_TARGETS.md) describes HF restoration without target encoding.
+Use its standard download when the selected release includes all required SS components.
+Prepare native SS targets when a compatible encoded cache is unavailable:
+
+```bash
+envs/sam3d/bin/python -m ss_multiobj_depth.prepare_targets \
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json \
+ --batch-size 64 --workers 16
+```
+
+Preparation encodes saved voxel labels and requires no shape meshes or SLAT targets.
+It preserves completed records after source and artifact checksum checks.
+The target caches reside under `outputs/ss_multiobj_depth/<dataset>/masked_objects/targets/`.
+The training batch remains 16 regardless of the preparation batch.
+
+Run training after all three caches are complete:
+
+```bash
+PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ envs/sam3d/bin/python -m ss_multiobj_depth.train \
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json
+```
+
## Object-wise region pooling
Each voxel defines a projected region in the image.
@@ -22,19 +137,22 @@ The local region feature uses this intersection, while the whole-mask object des
The mask coverage fraction divides the object-region area by the projected-region area, including background.
The [object-mean configuration](configs/front3d_sage_object_footprint_mean.json) enables the shared [region aggregator](../models/object_region_pool.py).
-It uses DINOv3 and NAF for local image features and whole-mask object descriptors.
+It uses DINOv3 for local image features by default.
+Whole-mask object descriptors retain DINOv3 and NAF features.
Local features and observed depth use arithmetic means within each object's projected voxel region.
No feature replacement or median correction occurs.
Let $R_v$ contain visible encoder pixels whose positive camera rays intersect the SS node's spatial box.
SS uses its native 16³ endpoint lattice, with midpoint boundaries and boxes clipped to the scene cube.
-Let $R_{vi}=R_v\cap M_i$, and let $F(u)$ concatenate bilinear DINOv3 and NAF features at 512 × 512 resolution.
+Let $R_{vi}=R_v\cap M_i$.
+Let $F_{\mathrm{DINO}}(u)$ contain bilinear DINOv3 features at 512 × 512 resolution.
+Let $F_{\mathrm{DINO+NAF}}(u)$ concatenate those features with NAF features at the same resolution.
The features and local block update are:
$$
\begin{aligned}
-f_{vi}&=\operatorname{mean}_{u\in R_{vi}}F(u),\qquad
-m_i=\operatorname{mean}_{u\in M_i}F(u),\qquad
+f_{vi}&=\operatorname{mean}_{u\in R_{vi}}F_{\mathrm{DINO}}(u),\qquad
+m_i=\operatorname{mean}_{u\in M_i}F_{\mathrm{DINO+NAF}}(u),\qquad
r_{vi}=|R_{vi}|/|R_v|,\\
D_{vi}&=\operatorname{mean}_{u\in R_{vi},\;D(u)\text{ valid}}D(u),\\
\delta_{vi}&=\operatorname{clip}((z_v-D_{vi})/L_{\mathrm{cube}},-1,1),\\
@@ -44,23 +162,24 @@ L_{v,\ell}&=\sum_i r_{vi}g_{vi,\ell}
\end{aligned}
$$
-Both feature terms contain 2048 channels.
-The optional `voxel_image_features="dino"` selects 1024 local channels while retaining the combined mask descriptor.
+Local image features contain 1024 channels by default, with `voxel_image_features="dino"`.
+Whole-mask descriptors contain 2048 DINOv3 and NAF channels.
The denominator includes background pixels inside the original camera image and encoder crop.
Missing depth produces a zero depth embedding.
Empty object intersections contribute nothing, while the image bias remains outside the sum.
SS has no segmentation identity-code term; generative SLAT segmentation adds that term through the same shared block.
Native SS image projections accept 1024 channels.
-The combined mode copies their DINO weights and initializes the additional NAF columns at zero.
-It preserves the pretrained bias and trains every image weight and bias.
+SS copies these weights and their bias from the pretrained Pixal3D SS checkpoint.
+The `full` adaptation mode trains every image weight and bias.
The new mask projection accepts the combined descriptor and initializes at zero.
The configuration uses separate feature caches because historical caches lack object regions and NAF descriptors.
Depth corruption changes each original observed pixel once before the object means are calculated.
-### Learned coverage gate with image NoRA
+### Learned coverage gate with shared adapters
-The [SS coverage preset](configs/front3d_sage_object_mean_image_nora_coverage_gate.json) matches the conditioning in the [SLAT coverage preset](../slat_segvigen/configs/object_mean_image_nora_coverage_gate.json).
+The [SS coverage preset](configs/front3d_sage_object_mean_image_coverage_gate.json) shares region pooling and coverage gates with the [SLAT coverage preset](../slat_segvigen/configs/object_mean_image_nora_coverage_gate.json).
+SS uses DINO-only local features, while the SLAT preset retains DINOv3 and NAF local features.
It aggregates image features, whole-mask descriptors, and depth separately for each voxel–object intersection.
SS uses no one-hot instance codes or segmentation projection.
Its target remains one combined occupancy grid for objects with supplied masks.
@@ -89,18 +208,22 @@ The gate initializes to $\sigma(3)$, approximately 0.953.
The initial coverage weights are zero.
Empty intersections contribute nothing, and the native image bias occurs once after summation.
Native global image attention remains active.
-The backbone and image projections use rank-8 NoRA with `alpha=8`.
-Image projection biases remain trainable.
+The backbone and image projections use rank-8 LoRA with `alpha=8` by default.
+The [shared recipe](../utils/training/configs/default.json) selects LoRA or NoRA for both projections across all three stages.
+The image base retains the native 1024-channel Pixal3D SS weights.
+LoRA initializes its residual to zero and keeps those base weights frozen.
+The copied image biases remain trainable.
This preset uses `training.conditioning_source="online"`.
CPU workers prepare crops and ray intersections from the saved extent views.
Frozen DINOv3 and NAF encoders calculate conditioning during training.
+NAF contributes only to the whole-mask descriptors in the default SS presets.
Training reuses the existing verified SS latent targets for complete masked-object occupancy.
It does not duplicate the full conditioning cache.
Dataset sampling gives equal probability to 3D-FRONT and SAGE-10k.
-The [three-dataset configuration](configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json) also uses the FoundationPose export for training.
-It retains object-mean conditioning, image NoRA, learned coverage gates, and the shared learning rate of `1e-4`.
+The [three-dataset configuration](configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json) also uses the FoundationPose export for training.
+It retains object-mean conditioning, image adapters, learned coverage gates, and the shared learning rate of `1e-4`.
Each dataset has probability one third for each sampled training view.
Sampling gives a 1:1:1 ratio in expectation. Individual batches can contain unequal dataset counts.
The run uses 39,930 3D-FRONT views, 17,456 SAGE views, and 42,256 FoundationPose views for training.
@@ -109,7 +232,7 @@ Prepare FoundationPose latent targets before this run:
```bash
python -m ss_multiobj_depth.prepare_targets \
- --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json \
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json \
--dataset foundationpose --batch-size 64 --workers 16
```
@@ -123,10 +246,12 @@ Run the separate training command:
```bash
python -m ss_multiobj_depth.train \
- --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json
+ --config ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json
```
-The [2026-10-19 training run](https://wandb.ai/jaeyun/PartProbe3D/runs/58321290) uses this configuration on GPU 1.
+The [2026-10-19 training run](https://wandb.ai/jaeyun/PartProbe3D/runs/58321290) used DINOv3 and NAF local features on GPU 1.
+The current preset selects DINO-only local features for new runs.
+Existing runs and checkpoints retain their recorded feature settings.
It used pretrained Pixal3D SS weights with fresh NoRA adapters and conditioning layers.
On one RTX 3090, preparation took 19.4 minutes with batch size 64 and 16 CPU workers.
@@ -137,7 +262,7 @@ Run a fresh training job from the repository root:
```bash
python -m ss_multiobj_depth.train \
- --config ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json
+ --config ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json
```
The preset uses 20,000 steps and an effective batch size of eight.
@@ -301,7 +426,7 @@ $$
#### (3) Selectable voxel conditioning
Both SS and SLAT shape use the shared [voxel conditioning module](../models/voxel_condition.py).
-The modes `additive`, `depth_scalar`, and `depth_embedding` use the same observation features and latent targets.
+The modes `additive` and `depth_embedding` use the same observation features and latent targets.
New training selects `depth_embedding` when you omit `--config`.
Explicit configurations retain their declared architecture for existing checkpoints and ablations.
They control pixel conditioning independently of the attention type.
@@ -309,7 +434,7 @@ The setting `model.cross_attention_mode` selects global scene tokens or [occlusi
Let $x_v=\operatorname{LN}(h_v(t))$, where $h_v(t)$ is the voxel state after self-attention.
The flow timestep $t$ already affects this state.
-All three settings use the same residual update:
+Both modes use the same residual update:
$$
h_v' = h_v(t) + A_v + P_v^{\mathrm{mode}},\qquad
@@ -319,11 +444,9 @@ $$
Here, $A_v$ is the selected attention update, and $P_v^{\mathrm{mode}}$ is pixel conditioning.
The matrices $W_{\mathrm{mask}}$ and $W_{\mathrm{depth}}$ are linear projections without bias.
-| `model.voxel_condition_mode` | Gate input with the hidden state | Separate depth projection |
-| --- | --- | --- |
-| `additive` | No gate | $W_{\mathrm{depth}}f_d(v)$ |
-| `depth_scalar` | Signed residual $\Delta_v = s_d(v)$ | $W_{\mathrm{depth}}f_d(v)$ |
-| `depth_embedding` | Depth embedding $f_d(v)$ | None |
+The [configuration inventory](#configuration-inventory) lists the mode controls and their review status.
+Additive mode has no gate.
+Embedding mode gates from the depth embedding and omits the separate depth projection.
The pixel-conditioning terms compare directly:
@@ -331,9 +454,6 @@ $$
\begin{aligned}
P_v^{\mathrm{additive}} &= W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m
+W_{\mathrm{depth}}f_d+b_{\mathrm{block}},\\
-P_v^{\mathrm{scalar}} &= V_v^{\mathrm{scalar}}(t)
- (W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m)
- +W_{\mathrm{depth}}f_d+b_{\mathrm{block}},\\
P_v^{\mathrm{embedding}} &= V_v^{\mathrm{embedding}}(t)
(W_{\mathrm{block}}f_v+W_{\mathrm{mask}}f_m)
+b_{\mathrm{block}}.
@@ -341,15 +461,12 @@ P_v^{\mathrm{embedding}} &= V_v^{\mathrm{embedding}}(t)
$$
The `additive` mode adds image, mask, and depth terms without a gate.
-The `depth_scalar` mode gates image and mask terms but retains additive depth.
The `depth_embedding` mode uses depth inside its gate and omits the separate depth projection.
-Neither gate multiplies the attention update $A_v$ or the projection bias $b_{\mathrm{block}}$.
-The two gates are:
+The embedding gate does not multiply the attention update $A_v$ or the projection bias $b_{\mathrm{block}}$.
+Its equation is:
$$
\begin{aligned}
-V_v^{\mathrm{scalar}}(t) &= \sigma\!\left(\operatorname{MLP}_{\mathrm{scalar}}(
- \operatorname{concat}(x_v,\Delta_v))\right),\\
V_v^{\mathrm{embedding}}(t) &= \sigma\!\left(\operatorname{MLP}_{\mathrm{embedding}}(
\operatorname{concat}(x_v,f_d(v)))\right).
\end{aligned}
@@ -375,37 +492,35 @@ SS has no segmentation identity term $W_{S,\ell}s_v$.
The [shared implementation](../models/voxel_condition.py) gates image features before their affine projection.
Thus, $W_{I,\ell}(g_{v,\ell}f_v)+b_{I,\ell}=g_{v,\ell}W_{I,\ell}f_v+b_{I,\ell}$.
-New training fully updates $W_{I,\ell}$ and $b_{I,\ell}$ from their pretrained Pixal3D values.
-This projection uses no low-rank adapter and no random reinitialization.
-Its trainable parameters remain float32, while forward computation retains the native feature precision.
-Checkpoints store the complete image weight and bias for every block.
-
-Older checkpoints without these tensors retain Pixal3D image projections during inference.
-Their optimizer cannot resume under the new trainable parameter set.
-Start a new run to train the image projection and bias.
+New training adapts $W_{I,\ell}$ with LoRA and trains $b_{I,\ell}$ from their pretrained Pixal3D values.
+The shared recipe selects LoRA or NoRA, and `full` trains the complete projection.
+Trainable parameters remain float32, while forward computation retains the native feature precision.
+Checkpoints store the selected adapter format and all trainable tensors.
+Checkpoint loading requires current parameter names and complete image projection tensors.
Each block has its own gate MLP with one hidden layer and SiLU activation.
The setting `model.voxel_condition_hidden_channels` controls its width.
-Its default is 64 for either depth gate and zero for `additive`.
+Its default is 64 for `depth_embedding` and zero for `additive`.
The final layer has zero initial weights and bias 3, giving an initial gate near 0.95.
The symbol $\sigma$ denotes the sigmoid function. The operator $\operatorname{concat}$ joins feature vectors along their channel dimension.
-Neither gate receives a separate timestep embedding or a `depth_valid` channel.
+The embedding gate receives no separate timestep embedding or `depth_valid` channel.
The existing validity flag still zeros $f_d$ after its MLP. Missing depth produces a zero residual.
Training learns the gate through the flow loss. It does not supervise visibility or guarantee sharpening during denoising.
-The optimizer separates NoRA/LoRA parameters from all other trainable layers.
-The depth MLP, gate MLP, and other trainable projections share `training.learning_rate`.
-NoRA/LoRA parameters use `training.optimizer.adapter_learning_rate` when specified, or the same learning rate otherwise.
-The supplied configurations use `1e-4` for both groups.
-Both groups use the same linear warmup. Training has no separate depth learning rate.
+SS, SegviGen, and SLAT shape share one [optimization recipe](../utils/training/configs/default.json).
+The [training guide](../utils/training/README.md) describes its parameter groups, 500-update warmup, and weight EMA.
+Each preset references this recipe through `training.optimizer_config`.
+The loader records resolved values in each run snapshot and checkpoint.
+Training resumes raw weights and EMA history, while evaluation selects EMA weights when available.
+Training has no separate depth learning rate.
Checkpoints with the former flow/depth groups require optimizer state conversion before training resumes.
This conversion does not change model weights.
#### Crop borders and the original camera view
-All three settings repeat DINOv3 border features without a camera-validity multiplier.
+Both modes repeat DINOv3 border features without a camera-validity multiplier.
Projection follows these conditions:
- Inside the crop, sample the projected image feature.
@@ -433,33 +548,16 @@ In global attention mode, global attention and the projection bias can still con
`model.cross_attention_mode` selects cross-attention independently of `model.voxel_condition_mode`.
CA means cross-attention.
-Both SS and SLAT shape accept the same mode names:
-
-| Mode | SS attention keys | SLAT shape attention keys |
-| --- | --- | --- |
-| `global` | Native global DINOv3 scene tokens | Native global DINOv3 scene tokens |
-| `occlusion_object` | Object descriptors filtered by directed occlusion candidates, plus a null descriptor | One descriptor for the token's assigned instance |
-
-The default mode is `global`.
-Either CA mode can use `additive`, `depth_scalar`, or `depth_embedding` voxel conditioning.
-CA selects the attention keys, while voxel conditioning controls the local image, mask, and depth terms.
-
-Set these fields inside `model` for object CA with a depth gate:
-
-```json
-{
- "cross_attention_mode": "occlusion_object",
- "voxel_condition_mode": "depth_embedding",
- "voxel_condition_hidden_channels": 64
-}
-```
+The [configuration inventory](#configuration-inventory) lists accepted modes, defaults, and their constraints.
+Global CA reads native DINOv3 scene tokens.
+Object CA reads descriptors selected through directed occlusion candidates, plus a null descriptor.
+The [shape attention guide](../slat_multiobj_shape/README.md#select-cross-attention) describes its separate owner-based rule and default disabled CA.
-The [object preset](configs/front3d_sage_object_attention_1.json) selects this combination.
+The [object preset](configs/front3d_sage_object_attention_1.json) selects object CA with the depth-embedding gate.
Its filename preserves the historical run identity.
Each native SS transformer block contains one CA layer in either mode.
Set `cross_attention_mode` explicitly for new configurations.
-The loader rejects the retired `object_attention_layers` field.
Checkpoints record the resolved CA mode.
A CA change requires a new adapter run.
Evaluation rejects an explicit mode that differs from the checkpoint.
@@ -470,7 +568,7 @@ The intended method replaces global scene-token attention with masked attention
It uses **one cross-attention layer per native SS transformer block**.
Voxel projection and occlusion relations select the instance registers that each query can attend to.
An instance register is an attention token that represents one object.
-The visibility gate remains independent and can use `none`, `scalar`, or `embedding`.
+Voxel conditioning remains independent and supports `additive` or `depth_embedding`.
The SS decoder still generates one scene occupancy grid.
##### Replacement of global attention
@@ -546,7 +644,7 @@ The block follows **SA → CA → pixel conditioning → MLP**:
1. **SA:** Apply native self-attention to the voxel states.
2. **CA:** Apply one occlusion-aware masked cross-attention layer over the eligible instance registers.
-3. **Pixel conditioning:** Add projected image, mask, and depth terms according to the selected visibility mode.
+3. **Pixel conditioning:** Apply the selected additive or depth-embedding equation.
4. **MLP:** Apply the native feed-forward network, a multilayer perceptron.
CA and pixel conditioning use the same normalized voxel state after SA.
@@ -862,13 +960,7 @@ As of 2026-10-10, the [official repository](https://github.com/cvlab-kaist/Tetri
5. Sample augmentations during training with resumable random number generator (RNG) state.
Evaluate generated occupancy on observations without augmentation.
-Configure the corruption under `training.depth_augmentation`:
-
-```json
-{"noise_probability": 0.3, "noise_std_fraction": 0.015625, "pixel_dropout": 0.1}
-```
-
-Set the noise scale with `noise_std_fraction` as a fraction of the cube's side length.
+The [configuration inventory](#configuration-inventory) collects the depth augmentation controls and their defaults.
The feature cache retains these values:
@@ -1020,8 +1112,9 @@ Follow the [checkpoint download guide](../HF_MODEL_CHECKPOINTS.md) for authentic
The [masked-object snapshot at step 9,000](https://huggingface.co/cubec/PartProbe3D-checkpoints/blob/9b15cd5ea5d5fad506ae7998c6fe03146f120644/checkpoints/training/ss_multiobj_depth/front3d_sage_object_attention_masked_objects/step_009000.pt) uses 3D-FRONT and SAGE-10k.
It retains object attention, the depth-embedding gate, and complete occupancy for objects with supplied masks.
-The repository also provides two snapshots trained on combined 3D-FRONT and SAGE data.
+The repository also preserves two historical snapshots trained on combined 3D-FRONT and SAGE data.
Both snapshots retain the crop-border fix.
+These historical snapshots require their recorded source revisions.
| Gate | Saved step | Checkpoint directory under `checkpoints/training/ss_multiobj_depth/` |
| --- | ---: | --- |
@@ -1138,10 +1231,10 @@ The preset uses batch size 8 and one accumulation step.
Its effective batch remains eight views per optimizer update, matching the previous settings of two views and four accumulation steps.
A training profile on one RTX PRO 6000 Blackwell GPU used 13.2 GiB for allocated tensors and 16.1 GiB for reserved memory.
These values include forward calculation, gradients, and an optimizer update with real samples from both datasets.
-The trainer uses one GPU. Prepare caches on both permitted GPUs before training.
+The trainer uses one GPU. Prepare caches on the configured devices before training.
-For this workspace, set `CUDA_VISIBLE_DEVICES=4,6` and `CUDA_DEVICE_ORDER=PCI_BUS_ID` before each GPU command.
-Use `cuda:0` for physical GPU 4 and `cuda:1` for physical GPU 6.
+Select visible GPUs through `CUDA_VISIBLE_DEVICES`.
+Select logical devices within that visible set through the configuration.
Local training requires complete feature caches and GT occlusion relations for both sources.
Use `wandb_mode="offline"` when no W&B login is available.
@@ -1180,7 +1273,7 @@ ln -s /path/to/existing/ss_features /path/to/overlay/conditioning
### Combined 3D-FRONT + SAGE-10k training
-The default [embedding configuration](configs/front3d_sage_depth_embedding_gate.json) trains one SS model from separate feature caches for the two datasets.
+The earlier [embedding configuration](configs/front3d_sage_depth_embedding_gate.json) trains one SS model from separate feature caches for two datasets.
Its `sources` list contains a `dataset` and `cache` pair for each source.
The sampler selects either dataset with probability 50%. It then samples uniformly from that dataset's training views.
The saved MIDI room split and SAGE layout split remain unchanged.
@@ -1216,7 +1309,7 @@ Use `--config` to select the equation and run directories:
```bash
python -m ss_multiobj_depth.train \
- --config ss_multiobj_depth/configs/front3d_sage_depth_residual_gate.json
+ --config ss_multiobj_depth/configs/front3d_sage.json
python -m ss_multiobj_depth.train \
--config ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json
@@ -1225,29 +1318,25 @@ python -m ss_multiobj_depth.train \
Only the configuration path changes between these commands.
The configurations share feature caches and all other training settings.
-| Configuration | `model.voxel_condition_mode` | Equation |
-| --- | --- | --- |
-| [front3d_sage_depth_residual_gate.json](configs/front3d_sage_depth_residual_gate.json) | `depth_scalar` | Gate from the signed depth residual, with a separate additive depth projection |
-| [front3d_sage_depth_embedding_gate.json](configs/front3d_sage_depth_embedding_gate.json) | `depth_embedding` | Gate from the depth embedding, without a separate additive depth projection |
-| [front3d_sage.json](configs/front3d_sage.json) | Absent, defaults to `additive` | Additive mask and depth projections without a gate |
+The [configuration inventory](#configuration-inventory) compares these mode choices and identifies the CLI default.
+The [combined preset](configs/front3d_sage.json) uses additive conditioning.
+The [embedding preset](configs/front3d_sage_depth_embedding_gate.json) uses the depth-embedding gate.
Each configuration explicitly defines `output` and `checkpoints`. Loading it does not change those paths.
-The training command defaults to the embedding configuration.
+The training command defaults to object means and learned coverage across 3D-FRONT, SAGE-10k, and FoundationPose.
Explicit `front3d.json`, `sage.json`, and `front3d_sage.json` retain additive conditioning for their existing runs.
-The two gate configurations use separate directories named `front3d_sage_depth_residual_gate` and `front3d_sage_depth_embedding_gate`.
-They do not overwrite each other's checkpoints or the existing baseline run.
-The CLI no longer accepts `--visibility-mode`.
+The presets use separate output and checkpoint directories.
+The CLI selects the conditioning equation through `--config`.
Append `--resume` to the same command to continue its run.
For an existing run, select its saved `config.json` with its original directories.
New gated runs require `model.voxel_condition_mode` in JSON.
-Uploaded gate checkpoints retain their recorded width fields and tensor names.
Saved configurations, checkpoints, and W&B record the resolved mode and gate width.
-Evaluation and resume infer missing mode metadata from legacy checkpoint tensors.
-The loader rejects the retired `visibility_mode` field.
-It also accepts historical `visibility_hidden_channels` fields and `.visibility.` tensor keys.
+Evaluation and resume check the architecture against saved adapter tensors.
+Unknown configuration fields and unsupported checkpoint formats cause errors.
+
An explicit mode must match the checkpoint. Switching equations requires a new run.
Source changes still require `--accept-source-changes` for resume. Data and objective checks remain active.
@@ -1341,19 +1430,26 @@ It concatenates their cosine and sine values and learns a shared MLP.
It masks missing or nonfinite depth **after** the biased MLP.
Each native projection block receives a bias-free `W_mask` addition.
-The `scalar` and `none` modes also use `W_depth`. The `embedding` mode has no separate depth projection.
+The `additive` mode also uses `W_depth`. The `depth_embedding` mode has no separate depth projection.
The code initializes these additions to zero after it loads pretrained weights.
-Training updates these additions, any visibility heads, the depth MLP, and rank-8 NoRA adapters.
+Training updates these additions, the embedding gates, the depth MLP, and rank-8 LoRA adapters by default.
Object attention mode also trains the depth queries, geometric biases, and null descriptors.
Other original flow parameters, DINOv3, and the SS codec remain frozen.
The native flow-matching objective uses `1000*t` timesteps and one denoising trajectory per scene.
Classifier-free guidance (CFG) removes RGB, mask, and depth features together.
+The [shared CFG profile](../utils/training/configs/cfg.json) supplies `training.cfg_dropout=0.1`, matching GenRecon and WorldSculpt's configured rate.
This removal matches the all-zero negative condition for sampling.
The implementation does not include the proposed 2×2 ablations.
+The same profile sets inference strength `7.5`, guidance rescaling `0.7`, and the guidance interval `[0.6, 1.0]`.
+
Training uses one device, minibatches, and gradient accumulation.
-The default effective batch contains eight views (`batch_size=2`, `accumulation=4`).
+The loss uses native Pixal3D averaging over every dense latent element within each microbatch.
+This mean includes all samples, channels, and grid cells without occupancy filtering.
+Gradient accumulation averages microbatch losses.
+
+The default effective batch contains sixteen views (`batch_size=16`, `accumulation=1`).
Sampling is deterministic by optimizer step.
Resume restores optimizer and Torch RNG state. It rejects changes to the model, feature manifest, or training objective.
diff --git a/ss_multiobj_depth/conditioning.py b/ss_multiobj_depth/conditioning.py
index 1bf89c1..36871a8 100644
--- a/ss_multiobj_depth/conditioning.py
+++ b/ss_multiobj_depth/conditioning.py
@@ -109,6 +109,10 @@ class SSVoxelConditioner(VoxelConditioner):
"""Extend shared voxel carriers with optional SS object-token context."""
def __init__(self, image_channels=1024, depth_channels=128, *, voxel_condition_mode='additive',
mask_channels=None, object_attention=False, object_aggregation=False):
+ if voxel_condition_mode not in ('additive', 'depth_embedding'):
+ raise ValueError('SS voxel_condition_mode must be additive or depth_embedding')
+ if object_aggregation and image_channels != 1024:
+ raise ValueError('SS object means require 1024-channel DINO local features')
super().__init__(image_channels, depth_channels, voxel_condition_mode=voxel_condition_mode,
mask_channels=mask_channels, object_aggregation=object_aggregation,
packed_object_pairs=object_aggregation)
diff --git a/ss_multiobj_depth/config.py b/ss_multiobj_depth/config.py
index f5e50c5..612cbf2 100644
--- a/ss_multiobj_depth/config.py
+++ b/ss_multiobj_depth/config.py
@@ -7,13 +7,26 @@ import subprocess
from utils.hashing import sha256
from utils.training.depth_augmentation import validate_settings
-from models.voxel_condition import canonical_voxel_settings, voxel_condition_settings, voxel_condition_width
-from models.cross_attention import canonical_attention_settings, cross_attention_settings
+from utils.training.settings import resolve_training_settings, resolve_adapter_settings
+from utils.training.cfg import resolve_cfg_settings
+from utils.training.ema import validate_ema_decay
+from models.voxel_condition import voxel_condition_settings, voxel_adapter_settings
+from models.cross_attention import cross_attention_settings
from .runtime import ROOT, path_under, configure_runtime
DEFAULT_CONFIG = Path(__file__).parent / 'configs/front3d.json'
-DEFAULT_TRAINING_CONFIG = DEFAULT_CONFIG.with_name('front3d_sage_depth_embedding_gate.json')
+DEFAULT_TRAINING_CONFIG = DEFAULT_CONFIG.with_name('front3d_sage_foundationpose_object_mean_image_coverage_gate.json')
TARGET_SCOPE = 'masked_objects_complete_occupancy'
+CONFIG_KEYS = {'schema', 'cfg_config', 'cfg_profile', 'dataset', 'cache', 'sources', 'output',
+ 'checkpoints', 'device', 'seed', 'depth_source', 'moge_config', 'models', 'model',
+ 'training', 'sampling', 'inference_weights', 'occlusion_model'}
+MODEL_KEYS = {'depth_channels', 'rank', 'alpha', 'mask_channels', 'voxel_condition_mode',
+ 'voxel_condition_hidden_channels', 'cross_attention_mode', 'voxel_aggregation',
+ 'voxel_image_features', 'voxel_coverage_weighting', 'image_projection_adaptation', 'adapter_method'}
+TRAINING_KEYS = {'optimizer_config', 'optimizer_profile', 'adapter_method', 'learning_rate', 'weight_decay',
+ 'warmup', 'optimizer', 'ema_decay', 'cfg_dropout', 'steps', 'batch_size', 'accumulation',
+ 'workers', 'depth_augmentation', 'save_every', 'eval_every', 'eval_limit',
+ 'wandb_mode', 'wandb_project', 'wandb_entity', 'conditioning_source'}
def online_conditioning(config):
@@ -28,15 +41,45 @@ def online_conditioning(config):
def model_settings(settings, adapters=None):
- """Resolve the architecture, using saved tensors for legacy gated checkpoints."""
- return cross_attention_settings(voxel_condition_settings(settings, adapters), adapters)
+ """Resolve supported SS options and check the saved architecture."""
+ unknown = set(settings) - MODEL_KEYS
+ if unknown:
+ raise ValueError(f'Unknown SS model settings: {sorted(unknown)}')
+ if settings.get('voxel_image_features', 'dino') != 'dino':
+ raise ValueError('SS voxel_image_features must be dino')
+ if adapters is not None and any('.visibility.' in key for key in adapters['flow']):
+ raise ValueError('SS checkpoint contains unsupported adapter names')
+ settings = voxel_condition_settings(settings, adapters)
+ settings = cross_attention_settings(settings, adapters)
+ settings = voxel_adapter_settings(settings, adapters)
+ if settings['voxel_condition_mode'] not in ('additive', 'depth_embedding'):
+ raise ValueError('SS voxel_condition_mode must be additive or depth_embedding')
+ if settings['image_projection_adaptation'] not in ('full', 'lora', 'nora'):
+ raise ValueError('SS image_projection_adaptation must be full, lora or nora')
+ from models.object_region_pool import enabled, coverage_gate
+ coverage_gate(settings)
+ if enabled(settings):
+ settings.setdefault('voxel_image_features', 'dino')
+ if settings['voxel_condition_mode'] != 'depth_embedding' or settings['cross_attention_mode'] != 'global':
+ raise ValueError('Object means require depth_embedding and global cross-attention')
+ if adapters is not None and any(
+ value.shape[-1] != 1024 for key, value in adapters['flow'].items()
+ if key.endswith(('.proj_linear.weight', '.proj_linear.lora_A'))):
+ raise ValueError('SS checkpoint local image projections must use DINO features')
+ return settings
def checkpoint_model_config(config, saved):
"""Use the checkpoint mode unless the caller explicitly selects a mode."""
recorded = model_settings(saved['config']['model'], saved['adapters'])
- requested = canonical_attention_settings(canonical_voxel_settings(config['model']))
- for key in ('cross_attention_mode', 'voxel_condition_mode', 'voxel_condition_hidden_channels'):
+ requested = dict(config['model'])
+ unknown = set(requested) - MODEL_KEYS
+ if unknown:
+ raise ValueError(f'Unknown SS model settings: {sorted(unknown)}')
+ for key in ('cross_attention_mode', 'voxel_condition_mode', 'voxel_condition_hidden_channels',
+ 'voxel_image_features', 'adapter_method', 'image_projection_adaptation'):
+ if key not in recorded:
+ continue
if key in requested and requested[key] != recorded[key]:
raise ValueError('Evaluation/resume model differs from training checkpoint')
requested.setdefault(key, recorded[key])
@@ -80,6 +123,14 @@ def load_config(path=DEFAULT_CONFIG):
config = json.loads(Path(path).read_text())
if config.get('schema') != 'ss-multiobj-depth-v1':
raise ValueError('Expected ss-multiobj-depth-v1 JSON settings')
+ for label, settings, allowed in (('configuration', config, CONFIG_KEYS),
+ ('training', config['training'], TRAINING_KEYS)):
+ unknown = set(settings) - allowed
+ if unknown:
+ raise ValueError(f'Unknown SS {label} settings: {sorted(unknown)}')
+ config['training'] = resolve_training_settings(config['training'])
+ config = resolve_cfg_settings(config, 'ss')
+ config['model'] = resolve_adapter_settings(config['model'], config['training'])
for source in source_configs(config):
path_under(source['cache'], 'outputs')
for key, folder in [('output', 'outputs'), ('checkpoints', 'checkpoints')]:
@@ -88,19 +139,8 @@ def load_config(path=DEFAULT_CONFIG):
for key in ('dino', 'encoder', 'decoder', 'paired_decoder', 'flow'):
path_under(config['models'][key], 'checkpoints')
require_gt_depth(config)
- if 'extent_spec' in config or 'cube_size' in config:
- raise ValueError('Choose extents in stage-two preprocessing; training reads the saved dataset grid')
- config['model'] = canonical_attention_settings(canonical_voxel_settings(config['model']))
+ config['model'] = model_settings(config['model'])
train, model = config['training'], config['model']
- from models.object_region_pool import enabled, image_channels, coverage_gate
- from models.voxel_condition import image_projection_adaptation
- image_projection_adaptation(model)
- coverage_gate(model)
- if enabled(model):
- image_channels(model)
- if (model_settings(model)['voxel_condition_mode'] != 'depth_embedding'
- or model_settings(model)['cross_attention_mode'] != 'global'):
- raise ValueError('Object means require depth_embedding and global cross-attention')
online_conditioning(config)
# Older explicit run configs keep their unaugmented objective. New runs
# select the rates and cube noise scale in configs/front3d.json.
@@ -117,21 +157,16 @@ def load_config(path=DEFAULT_CONFIG):
raise ValueError('Scheduled monitoring needs a positive eval_limit')
from utils.training.optim import validate_optimizer
validate_optimizer(train)
+ if train.get('ema_decay') is not None:
+ validate_ema_decay(train['ema_decay'])
+ if config.get('inference_weights', 'auto') not in ('auto', 'raw', 'ema'):
+ raise ValueError('SS inference_weights must be auto, raw or ema')
if not 0 <= train['cfg_dropout'] < 1:
raise ValueError('cfg_dropout must lie in [0,1)')
- if 'routing_loss_weight' in train:
- raise ValueError('SS training uses only flow-matching MSE. Remove training.routing_loss_weight.')
if (type(model['rank']) is not int or model['rank'] < 0
or type(model['depth_channels']) is not int or model['depth_channels'] < 1
or not math.isfinite(model['alpha']) or model['alpha'] <= 0):
raise ValueError('Invalid adapter dimensions/scaling')
- if 'voxel_condition_mode' in model:
- voxel_condition_width(model['voxel_condition_mode'], model.get('voxel_condition_hidden_channels'))
- elif 'voxel_condition_hidden_channels' in model:
- # Old branch configs omit the mode. Checkpoints identify it at load time.
- width = model['voxel_condition_hidden_channels']
- if type(width) is not int or width < 0:
- raise ValueError('voxel_condition_hidden_channels must be a nonnegative integer')
if train['wandb_mode'] not in ('disabled', 'offline', 'online'):
raise ValueError('Invalid W&B mode')
sampling = config['sampling']
@@ -193,7 +228,7 @@ def training_protocol(config, dataset):
for key in ('steps', 'save_every', 'eval_every', 'eval_limit', 'workers',
'wandb_mode', 'wandb_project', 'wandb_entity'):
value['training'].pop(key, None)
- for key in ('device', 'output', 'checkpoints', 'sampling'):
+ for key in ('device', 'output', 'checkpoints', 'sampling', 'inference_weights', 'cfg_profile'):
value.pop(key, None)
if 'sources' in config:
value['manifest_sha256'] = {source['cache']: sha256(data.root / 'manifest.json')
@@ -206,7 +241,7 @@ def training_protocol(config, dataset):
'ss_multiobj_depth/config.py', 'ss_multiobj_depth/dataloader.py', 'utils/training/lora.py',
'models/mask_latent.py', 'models/pixal3d.py', 'models/conditioning.py',
'models/ss_conditioning.py', 'models/voxel_condition.py', 'models/cross_attention.py', 'extent/grid.py',
- 'utils/training/optim.py']
+ 'utils/training/optim.py', 'utils/training/settings.py', 'utils/training/ema.py', 'utils/training/cfg.py']
from models.object_region_pool import enabled
if enabled(config['model']):
sources.extend(['models/object_region_pool.py', 'utils/region_fields.py',
diff --git a/ss_multiobj_depth/configs/foundationpose.json b/ss_multiobj_depth/configs/foundationpose.json
index 4e95cb5..1077bcf 100644
--- a/ss_multiobj_depth/configs/foundationpose.json
+++ b/ss_multiobj_depth/configs/foundationpose.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"dataset": "datasets/foundationpose/extent/point_cloud",
"cache": "outputs/ss_multiobj_depth/foundationpose/features",
"output": "outputs/ss_multiobj_depth/foundationpose/train",
@@ -26,13 +27,11 @@
"voxel_condition_hidden_channels": 64
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -47,12 +46,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d.json b/ss_multiobj_depth/configs/front3d.json
index bd7c4e7..9c6243a 100644
--- a/ss_multiobj_depth/configs/front3d.json
+++ b/ss_multiobj_depth/configs/front3d.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"dataset": "datasets/3dfront/extent/point_cloud",
"cache": "outputs/ss_multiobj_depth/front3d/features",
"output": "outputs/ss_multiobj_depth/front3d/train",
@@ -18,15 +19,19 @@
"flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16"
},
"model": {
- "cross_attention_mode": "global","depth_channels": 128, "rank": 8, "alpha": 8.0},
+ "cross_attention_mode": "global",
+ "depth_channels": 128,
+ "rank": 8,
+ "alpha": 8.0,
+ "adapter_method": "shared",
+ "image_projection_adaptation": "shared"
+ },
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -41,9 +46,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [0.6, 1.0],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d_sage.json b/ss_multiobj_depth/configs/front3d_sage.json
index 069dcfa..c5f112a 100644
--- a/ss_multiobj_depth/configs/front3d_sage.json
+++ b/ss_multiobj_depth/configs/front3d_sage.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -32,13 +33,11 @@
"alpha": 8.0
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -53,12 +52,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json b/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json
index 8123712..b155796 100644
--- a/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json
+++ b/ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -31,16 +32,16 @@
"rank": 8,
"alpha": 8.0,
"voxel_condition_mode": "depth_embedding",
- "voxel_condition_hidden_channels": 64
+ "voxel_condition_hidden_channels": 64,
+ "adapter_method": "shared",
+ "image_projection_adaptation": "shared"
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -55,12 +56,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json
new file mode 100644
index 0000000..cd1b069
--- /dev/null
+++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate.json
@@ -0,0 +1,72 @@
+{
+ "schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
+ "sources": [
+ {
+ "dataset": "datasets/3dfront/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/targets"
+ },
+ {
+ "dataset": "datasets/sage/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/sage/masked_objects/targets"
+ },
+ {
+ "dataset": "datasets/foundationpose/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/foundationpose/masked_objects/targets"
+ }
+ ],
+ "output": "outputs/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate/train",
+ "checkpoints": "checkpoints/training/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate",
+ "device": "cuda:0",
+ "seed": 0,
+ "depth_source": "gt",
+ "moge_config": "ss_multiobj_depth/configs/moge3.json",
+ "models": {
+ "upstream": "third_party/Pixal3D",
+ "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af",
+ "dino": "checkpoints/DINOv3",
+ "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16",
+ "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16",
+ "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16",
+ "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16",
+ "naf": "checkpoints/NAF/naf_release.pth",
+ "naf_upstream": "third_party/NAF",
+ "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43"
+ },
+ "model": {
+ "depth_channels": 128,
+ "rank": 8,
+ "alpha": 8.0,
+ "cross_attention_mode": "global",
+ "voxel_condition_mode": "depth_embedding",
+ "voxel_condition_hidden_channels": 64,
+ "voxel_aggregation": "object_mean",
+ "voxel_image_features": "dino",
+ "image_projection_adaptation": "shared",
+ "voxel_coverage_weighting": "learned_gate",
+ "adapter_method": "shared"
+ },
+ "training": {
+ "optimizer_config": "utils/training/configs/default.json",
+ "steps": 20000,
+ "batch_size": 16,
+ "accumulation": 1,
+ "workers": 4,
+ "depth_augmentation": {
+ "noise_probability": 0.3,
+ "noise_std_fraction": 0.015625,
+ "pixel_dropout": 0.1
+ },
+ "save_every": 500,
+ "eval_every": 500,
+ "eval_limit": 8,
+ "wandb_mode": "online",
+ "wandb_project": "PartProbe3D",
+ "wandb_entity": null,
+ "conditioning_source": "online"
+ },
+ "sampling": {
+ "steps": 12,
+ "rescale_t": 5
+ }
+}
diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json
new file mode 100644
index 0000000..e5c87fa
--- /dev/null
+++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6.json
@@ -0,0 +1,72 @@
+{
+ "schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
+ "sources": [
+ {
+ "dataset": "datasets/3dfront/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/targets"
+ },
+ {
+ "dataset": "datasets/sage/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/sage/masked_objects/targets"
+ },
+ {
+ "dataset": "datasets/foundationpose/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/foundationpose/masked_objects/targets"
+ }
+ ],
+ "output": "outputs/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6_20261021/train",
+ "checkpoints": "checkpoints/training/ss_multiobj_depth/front3d_sage_foundationpose_object_mean_image_coverage_gate_gpu6_20261021",
+ "device": "cuda:1",
+ "seed": 0,
+ "depth_source": "gt",
+ "moge_config": "ss_multiobj_depth/configs/moge3.json",
+ "models": {
+ "upstream": "third_party/Pixal3D",
+ "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af",
+ "dino": "checkpoints/DINOv3",
+ "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16",
+ "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16",
+ "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16",
+ "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16",
+ "naf": "checkpoints/NAF/naf_release.pth",
+ "naf_upstream": "third_party/NAF",
+ "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43"
+ },
+ "model": {
+ "depth_channels": 128,
+ "rank": 8,
+ "alpha": 8.0,
+ "cross_attention_mode": "global",
+ "voxel_condition_mode": "depth_embedding",
+ "voxel_condition_hidden_channels": 64,
+ "voxel_aggregation": "object_mean",
+ "voxel_image_features": "dino",
+ "image_projection_adaptation": "shared",
+ "voxel_coverage_weighting": "learned_gate",
+ "adapter_method": "shared"
+ },
+ "training": {
+ "optimizer_config": "utils/training/configs/default.json",
+ "steps": 20000,
+ "batch_size": 16,
+ "accumulation": 1,
+ "workers": 4,
+ "depth_augmentation": {
+ "noise_probability": 0.3,
+ "noise_std_fraction": 0.015625,
+ "pixel_dropout": 0.1
+ },
+ "save_every": 500,
+ "eval_every": 500,
+ "eval_limit": 8,
+ "wandb_mode": "online",
+ "wandb_project": "PartProbe3D",
+ "wandb_entity": null,
+ "conditioning_source": "online"
+ },
+ "sampling": {
+ "steps": 12,
+ "rescale_t": 5
+ }
+}
diff --git a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json
index 063e12f..d6f6501 100644
--- a/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json
+++ b/ss_multiobj_depth/configs/front3d_sage_foundationpose_object_mean_image_nora_coverage_gate.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -40,18 +41,17 @@
"voxel_condition_mode": "depth_embedding",
"voxel_condition_hidden_channels": 64,
"voxel_aggregation": "object_mean",
- "voxel_image_features": "dino_naf",
+ "voxel_image_features": "dino",
"image_projection_adaptation": "nora",
- "voxel_coverage_weighting": "learned_gate"
+ "voxel_coverage_weighting": "learned_gate",
+ "adapter_method": "nora"
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -67,12 +67,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json b/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json
index cca4958..49200b3 100644
--- a/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json
+++ b/ss_multiobj_depth/configs/front3d_sage_object_attention_1.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -34,13 +35,11 @@
"voxel_condition_hidden_channels": 64
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -55,12 +54,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
},
"occlusion_model": {
diff --git a/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json b/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json
index 73a4f8b..c55639e 100644
--- a/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json
+++ b/ss_multiobj_depth/configs/front3d_sage_object_attention_masked_objects.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -34,13 +35,11 @@
"voxel_condition_hidden_channels": 64
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 8,
"accumulation": 1,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -55,12 +54,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
},
"occlusion_model": {
diff --git a/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json b/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json
index 171c5cb..ac676aa 100644
--- a/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json
+++ b/ss_multiobj_depth/configs/front3d_sage_object_footprint_mean.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -36,16 +37,14 @@
"voxel_condition_mode": "depth_embedding",
"voxel_condition_hidden_channels": 64,
"voxel_aggregation": "object_mean",
- "voxel_image_features": "dino_naf"
+ "voxel_image_features": "dino"
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -60,12 +59,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json
new file mode 100644
index 0000000..8b5746d
--- /dev/null
+++ b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_coverage_gate.json
@@ -0,0 +1,68 @@
+{
+ "schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
+ "sources": [
+ {
+ "dataset": "datasets/3dfront/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/front3d/masked_objects/features"
+ },
+ {
+ "dataset": "datasets/sage/extent/point_cloud",
+ "cache": "outputs/ss_multiobj_depth/sage/masked_objects/features"
+ }
+ ],
+ "output": "outputs/ss_multiobj_depth/object_mean_image_coverage_gate/train",
+ "checkpoints": "checkpoints/training/ss_multiobj_depth/object_mean_image_coverage_gate",
+ "device": "cuda:0",
+ "seed": 0,
+ "depth_source": "gt",
+ "moge_config": "ss_multiobj_depth/configs/moge3.json",
+ "models": {
+ "upstream": "third_party/Pixal3D",
+ "upstream_revision": "cdbb2bbffbf4e6f298b5f2af3d1d76a8d823d2af",
+ "dino": "checkpoints/DINOv3",
+ "encoder": "checkpoints/TRELLIS/ckpts/ss_enc_conv3d_16l8_fp16",
+ "paired_decoder": "checkpoints/TRELLIS/ckpts/ss_dec_conv3d_16l8_fp16",
+ "decoder": "checkpoints/Pixal3D/ckpts/ss_dec_conv3d_16l8_fp16",
+ "flow": "checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16",
+ "naf": "checkpoints/NAF/naf_release.pth",
+ "naf_upstream": "third_party/NAF",
+ "naf_revision": "37f2dfc180f2de53d98bd601109c0da0dd6b0f43"
+ },
+ "model": {
+ "depth_channels": 128,
+ "rank": 8,
+ "alpha": 8.0,
+ "cross_attention_mode": "global",
+ "voxel_condition_mode": "depth_embedding",
+ "voxel_condition_hidden_channels": 64,
+ "voxel_aggregation": "object_mean",
+ "voxel_image_features": "dino",
+ "image_projection_adaptation": "shared",
+ "voxel_coverage_weighting": "learned_gate",
+ "adapter_method": "shared"
+ },
+ "training": {
+ "optimizer_config": "utils/training/configs/default.json",
+ "steps": 20000,
+ "batch_size": 2,
+ "accumulation": 4,
+ "workers": 4,
+ "depth_augmentation": {
+ "noise_probability": 0.3,
+ "noise_std_fraction": 0.015625,
+ "pixel_dropout": 0.1
+ },
+ "save_every": 500,
+ "eval_every": 500,
+ "eval_limit": 8,
+ "wandb_mode": "online",
+ "wandb_project": "PartProbe3D",
+ "wandb_entity": null,
+ "conditioning_source": "online"
+ },
+ "sampling": {
+ "steps": 12,
+ "rescale_t": 5
+ }
+}
diff --git a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json
index 9c779b3..2fbac91 100644
--- a/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json
+++ b/ss_multiobj_depth/configs/front3d_sage_object_mean_image_nora_coverage_gate.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"sources": [
{
"dataset": "datasets/3dfront/extent/point_cloud",
@@ -36,18 +37,17 @@
"voxel_condition_mode": "depth_embedding",
"voxel_condition_hidden_channels": 64,
"voxel_aggregation": "object_mean",
- "voxel_image_features": "dino_naf",
+ "voxel_image_features": "dino",
"image_projection_adaptation": "nora",
- "voxel_coverage_weighting": "learned_gate"
+ "voxel_coverage_weighting": "learned_gate",
+ "adapter_method": "nora"
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -63,12 +63,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/sage.json b/ss_multiobj_depth/configs/sage.json
index ae75588..4e299e3 100644
--- a/ss_multiobj_depth/configs/sage.json
+++ b/ss_multiobj_depth/configs/sage.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"dataset": "datasets/sage/extent/point_cloud",
"cache": "outputs/ss_multiobj_depth/sage/features",
"output": "outputs/ss_multiobj_depth/sage/train",
@@ -24,13 +25,11 @@
"alpha": 8.0
},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -45,12 +44,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [
- 0.6,
- 1.0
- ],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/configs/ycbv.json b/ss_multiobj_depth/configs/ycbv.json
index 6b60aa2..ae48d63 100644
--- a/ss_multiobj_depth/configs/ycbv.json
+++ b/ss_multiobj_depth/configs/ycbv.json
@@ -1,5 +1,6 @@
{
"schema": "ss-multiobj-depth-v1",
+ "cfg_config": "utils/training/configs/cfg.json",
"dataset": "datasets/ycbv/extent/point_cloud",
"cache": "outputs/ss_multiobj_depth/ycbv/features",
"output": "outputs/ss_multiobj_depth/ycbv/train",
@@ -20,13 +21,11 @@
"model": {
"cross_attention_mode": "global","depth_channels": 128, "rank": 8, "alpha": 8.0},
"training": {
+ "optimizer_config": "utils/training/configs/default.json",
"steps": 20000,
"batch_size": 2,
"accumulation": 4,
"workers": 4,
- "learning_rate": 0.0001,
- "warmup": 250,
- "cfg_dropout": 0.1,
"depth_augmentation": {
"noise_probability": 0.3,
"noise_std_fraction": 0.015625,
@@ -41,9 +40,6 @@
},
"sampling": {
"steps": 12,
- "cfg_strength": 7.5,
- "cfg_rescale": 0.7,
- "cfg_interval": [0.6, 1.0],
"rescale_t": 5
}
}
diff --git a/ss_multiobj_depth/inference.py b/ss_multiobj_depth/inference.py
index 8246426..1ab412e 100644
--- a/ss_multiobj_depth/inference.py
+++ b/ss_multiobj_depth/inference.py
@@ -100,7 +100,9 @@ class SSInference:
if saved['provenance'] != provenance:
raise ValueError('Evaluation model/weights differ from training checkpoint')
flow, conditioner = make_model(config)
- restore_checkpoint(self.checkpoint, flow, conditioner)
+ restored = restore_checkpoint(self.checkpoint, flow, conditioner,
+ weights=config.get('inference_weights', 'auto'))
+ saved['checkpoint_weights'] = restored['checkpoint_weights']
flow.eval(); conditioner.eval()
from pixal3d.pipelines.samplers import FlowEulerGuidanceIntervalSampler
self._ss = {'flow': flow, 'conditioner': conditioner,
diff --git a/ss_multiobj_depth/model.py b/ss_multiobj_depth/model.py
index b45053d..453b85e 100644
--- a/ss_multiobj_depth/model.py
+++ b/ss_multiobj_depth/model.py
@@ -6,9 +6,18 @@ from .object_attention import OcclusionObjectAttention
def install_adapters(flow, *, depth_channels=128, rank=8, alpha=8.,
voxel_condition_mode='additive', voxel_condition_hidden_channels=None, mask_channels=None,
- cross_attention_mode='global', voxel_aggregation='point', voxel_image_features='dino_naf',
- voxel_coverage_weighting='area', image_projection_adaptation='full'):
- from models.object_region_pool import enabled, image_channels, coverage_gate
+ cross_attention_mode='global', voxel_aggregation='point', voxel_image_features='dino',
+ voxel_coverage_weighting='area', image_projection_adaptation=None, adapter_method='lora'):
+ from models.object_region_pool import enabled, coverage_gate
+ from .config import model_settings
+ settings = dict(depth_channels=depth_channels, rank=rank, alpha=alpha, adapter_method=adapter_method,
+ voxel_condition_mode=voxel_condition_mode,
+ voxel_condition_hidden_channels=voxel_condition_hidden_channels,
+ cross_attention_mode=cross_attention_mode, voxel_aggregation=voxel_aggregation,
+ voxel_image_features=voxel_image_features, voxel_coverage_weighting=voxel_coverage_weighting)
+ if image_projection_adaptation is not None:
+ settings['image_projection_adaptation'] = image_projection_adaptation
+ image_projection_adaptation = model_settings(settings)['image_projection_adaptation']
object_regions = enabled({'voxel_aggregation': voxel_aggregation})
coverage = coverage_gate({'voxel_aggregation': voxel_aggregation,
'voxel_coverage_weighting': voxel_coverage_weighting})
@@ -21,8 +30,9 @@ def install_adapters(flow, *, depth_channels=128, rank=8, alpha=8.,
install_voxel_adapters(flow, depth_channels=depth_channels, rank=rank, alpha=alpha,
voxel_condition_mode=voxel_condition_mode, voxel_condition_hidden_channels=voxel_condition_hidden_channels,
mask_channels=mask_channels, object_context=objects, object_aggregation=object_regions,
- region_image_channels=image_channels({'voxel_image_features': voxel_image_features}),
- coverage_conditioned=coverage, image_projection_adaptation=image_projection_adaptation)
+ region_image_channels=1024,
+ coverage_conditioned=coverage, image_projection_adaptation=image_projection_adaptation,
+ adapter_method=adapter_method)
if objects:
for block in flow.blocks:
projection = block.cross_attn.base
diff --git a/ss_multiobj_depth/observations.py b/ss_multiobj_depth/observations.py
index 7cc109d..7e938b2 100644
--- a/ss_multiobj_depth/observations.py
+++ b/ss_multiobj_depth/observations.py
@@ -25,9 +25,11 @@ class ObservationEncoder:
def __init__(self, config, *, use_moge=False):
configure_runtime()
self.device = config['device']
+ from .config import model_settings
from models.object_region_pool import enabled, image_channels
- self.object_aggregation = enabled(config['model'])
- self.local_channels = image_channels(config['model'])
+ settings = model_settings(config['model'])
+ self.object_aggregation = enabled(settings)
+ self.local_channels = image_channels(settings)
self.object_attention = cross_attention_settings(config['model'])['cross_attention_mode'] == 'occlusion_object'
self.dino = load_dino(path_under(config['models']['dino'], 'checkpoints'), self.device)
self.naf = None
diff --git a/ss_multiobj_depth/tests/test_conditioning_training.py b/ss_multiobj_depth/tests/test_conditioning_training.py
index 8e76706..1b4e01c 100644
--- a/ss_multiobj_depth/tests/test_conditioning_training.py
+++ b/ss_multiobj_depth/tests/test_conditioning_training.py
@@ -15,6 +15,7 @@ from models.voxel_condition import negative_condition
from models.voxel_condition import VoxelConditionProjection, load_adapter_state
from ss_multiobj_depth.model import install_adapters
from ss_multiobj_depth.train import flow_loss, UpdateSampler, save_checkpoint, restore_checkpoint
+from utils.training.lora import LoRALinear
def entry(channels=4, resolution=2, latent_channels=2):
@@ -37,6 +38,18 @@ def compact_entry(channels=4, resolution=2):
return {**{k: v for k, v in dense.items() if k not in ('image_proj', 'mask_features')}, **carriers}
+def test_ss_loss_matches_native_dense_mse_and_gradients(monkeypatch):
+ clean = torch.arange(32, dtype=torch.float32).reshape(2, 2, 2, 2, 2) / 10
+ prediction = torch.zeros_like(clean, requires_grad=True)
+ entries = [{'clean': value} for value in clean]
+ monkeypatch.setattr(torch, 'randn_like', torch.zeros_like)
+ loss = flow_loss(lambda *args: prediction, lambda *args, **kwargs: {}, entries, cfg_dropout=0)
+ expected = torch.nn.functional.mse_loss(prediction, -clean)
+ torch.testing.assert_close(loss, expected)
+ torch.testing.assert_close(torch.autograd.grad(loss, prediction, retain_graph=True)[0],
+ torch.autograd.grad(expected, prediction)[0])
+
+
def test_depth_projection_sign_validity_and_object_features():
cube = Cube(np.array([0., 0., 1.5]), 3.)
intrinsics = np.array([[1., 0, 2], [0, 1., 2], [0, 0, 1.]])
@@ -126,7 +139,7 @@ def native_flow():
return flow
-@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding'])
+@pytest.mark.parametrize('mode', ['additive', 'depth_embedding'])
def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode):
torch.manual_seed(8)
flow = native_flow()
@@ -136,7 +149,8 @@ def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode)
image = block.cross_attn.base.proj_linear
torch.testing.assert_close(image.weight, original.cross_attn.proj_linear.weight, rtol=0, atol=0)
torch.testing.assert_close(image.bias, original.cross_attn.proj_linear.bias, rtol=0, atol=0)
- assert image.weight.requires_grad and image.bias.requires_grad
+ assert type(image) is LoRALinear
+ assert not image.weight.requires_grad and image.bias.requires_grad
conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode)
entries = [entry(), entry()]
condition = conditioner(entries)
@@ -164,8 +178,9 @@ def test_native_flow_backward_and_checkpoint_resume(tmp_path, monkeypatch, mode)
assert conditioner.depth_mlp[0].weight.grad.abs().sum() > 0
for block, original in zip(flow.blocks, native.blocks):
image = block.cross_attn.base.proj_linear
- assert image.weight.grad.abs().sum() > 0 and image.bias.grad.abs().sum() > 0
- assert not torch.equal(image.weight, original.cross_attn.proj_linear.weight)
+ assert image.lora_A.grad.abs().sum() > 0 and image.lora_B.grad.abs().sum() > 0
+ assert image.bias.grad.abs().sum() > 0
+ torch.testing.assert_close(image.weight, original.cross_attn.proj_linear.weight, rtol=0, atol=0)
assert not torch.equal(image.bias, original.cross_attn.proj_linear.bias)
assert all(p.grad is None for p in flow.parameters() if not p.requires_grad)
# Use the real serializer with a temporary top-level checkpoint owner.
@@ -213,7 +228,7 @@ import evaluation.inference.ss_multiobj_depth
@pytest.mark.parametrize('dataset', ['3D-FRONT', 'SAGE-10k', 'combined'])
-@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding'])
+@pytest.mark.parametrize('mode', ['additive', 'depth_embedding'])
def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, dataset, mode):
"""Exact depth corruption/optimizer resume despite worker prefetch changes."""
import json
@@ -223,13 +238,15 @@ def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, datas
from ss_multiobj_depth.dataloader import FEATURE_SCHEMA
from utils.hashing import sha256
config = load_config()
- config['model'].update(depth_channels=6, rank=2, alpha=2, voxel_condition_mode=mode)
+ config['model'].update(depth_channels=6, rank=2, alpha=2, voxel_condition_mode=mode,
+ voxel_condition_hidden_channels=0 if mode == 'additive' else 64)
config.update(device='cpu', cache='outputs/features', output='outputs/continuous',
checkpoints='checkpoints/continuous')
if dataset == 'SAGE-10k':
config.update(dataset='datasets/sage/extent/point_cloud')
config['training'].update(steps=4, batch_size=2, accumulation=2, workers=2,
warmup=2, eval_every=0, save_every=2, wandb_mode='disabled')
+ config['training']['optimizer']['warmup_steps'] = 2
config['training']['depth_augmentation'] = {
'noise_probability': .7, 'noise_std_fraction': 1 / 64, 'pixel_dropout': .3}
cache = tmp_path / config['cache']
@@ -289,6 +306,9 @@ def test_full_training_run_matches_resumed_training(tmp_path, monkeypatch, datas
runner.train(config, resume=True)
resumed = torch.load(tmp_path / 'checkpoints/resumed/last.pt', weights_only=True)
assert resumed['step'] == continuous['step'] == 4
+ assert resumed['ema']['num_updates'] == continuous['ema']['num_updates'] == 4
+ for name, value in continuous['ema']['parameters'].items():
+ torch.testing.assert_close(value, resumed['ema']['parameters'][name], rtol=0, atol=0)
assert continuous['protocol']['training']['depth_augmentation'] == config['training']['depth_augmentation']
assert continuous['protocol']['target_scope'] == TARGET_SCOPE
if dataset == 'combined':
diff --git a/ss_multiobj_depth/tests/test_object_attention.py b/ss_multiobj_depth/tests/test_object_attention.py
index 8315fa3..140ac6a 100644
--- a/ss_multiobj_depth/tests/test_object_attention.py
+++ b/ss_multiobj_depth/tests/test_object_attention.py
@@ -219,11 +219,11 @@ def test_option_validation_and_default_checkpoint_compatibility(tmp_path):
config['training']['routing_loss_weight'] = .1
path = tmp_path / 'config.json'
path.write_text(json.dumps(config))
- with pytest.raises(ValueError, match='only flow-matching MSE'):
+ with pytest.raises(ValueError, match='routing_loss_weight'):
load_config(path)
-@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding'])
+@pytest.mark.parametrize('mode', ['additive', 'depth_embedding'])
@pytest.mark.parametrize('ca', ['global', 'occlusion_object'])
def test_voxel_condition_modes_and_complete_cfg_dropout(mode, ca):
flow = install_adapters(native_flow(), depth_channels=6, rank=2, alpha=2,
diff --git a/ss_multiobj_depth/tests/test_object_mean_training.py b/ss_multiobj_depth/tests/test_object_mean_training.py
index 3516225..a8440c6 100644
--- a/ss_multiobj_depth/tests/test_object_mean_training.py
+++ b/ss_multiobj_depth/tests/test_object_mean_training.py
@@ -7,7 +7,7 @@ import torch
from torch import nn
from models.voxel_condition import adapter_state, load_adapter_state
-from ss_multiobj_depth.config import load_config, model_settings, online_conditioning
+from ss_multiobj_depth.config import checkpoint_model_config, load_config, model_settings, online_conditioning
from ss_multiobj_depth.conditioning import SSVoxelConditioner
from ss_multiobj_depth.dataloader import FEATURE_SCHEMA, FeatureDataset, OnlineObservationDataset
from ss_multiobj_depth.model import install_adapters
@@ -33,16 +33,30 @@ def test_three_dataset_config_preserves_conditioning_and_balances_sources():
torch.testing.assert_close(torch.stack(masses), torch.ones(3, dtype=torch.float64))
-def test_reference_conditioning_matches_without_instance_codes():
+def test_ss_defaults_use_dino_local_features_with_shared_gates_without_instance_codes():
config = load_config(CONFIG)
reference = json.loads(Path('slat_segvigen/configs/object_mean_image_nora_coverage_gate.json').read_text())
- for key in ('voxel_aggregation', 'voxel_image_features', 'voxel_coverage_weighting', 'image_projection_adaptation'):
+ for key in ('voxel_aggregation', 'voxel_coverage_weighting', 'image_projection_adaptation'):
assert config['model'][key] == reference['model'][key]
+ assert config['model']['voxel_image_features'] == 'dino'
+ assert reference['model']['voxel_image_features'] == 'dino_naf'
+ shape = json.loads(Path('slat_multiobj_shape/configs/front3d_sage_32_assigned_object.json').read_text())
+ assert shape['model']['voxel_image_features'] == 'dino_naf'
+ assert config['models']['flow'] == 'checkpoints/Pixal3D/ckpts/ss_flow_img_dit_1_3B_64_bf16'
assert config['model']['cross_attention_mode'] == 'global'
assert online_conditioning(config)
assert not {'instance_basis', 'occupancy_encoding', 'max_objects', 'instance_conditioning'} & config['model'].keys()
+def test_omitted_ss_image_features_default_to_dino(tmp_path):
+ config = json.loads(Path(CONFIG).read_text())
+ config['model'].pop('voxel_image_features')
+ path = tmp_path / 'default.json'
+ path.write_text(json.dumps(config))
+ assert load_config(path)['model']['voxel_image_features'] == 'dino'
+ assert model_settings(config['model'])['voxel_image_features'] == 'dino'
+
+
@pytest.mark.parametrize('fields', [
{'voxel_aggregation': 'point'}, {'cross_attention_mode': 'occlusion_object'},
{'voxel_condition_mode': 'depth_scalar'}, {'image_projection_adaptation': 'unknown'},
@@ -57,25 +71,51 @@ def test_invalid_ss_object_policies_fail_before_loading_weights(tmp_path, fields
load_config(path)
-def object_flow():
+def object_flow(image_features=None):
flow = native_flow()
for block in flow.blocks:
- block.cross_attn.proj_linear = nn.Linear(2048, 12)
- return install_adapters(flow, **model_settings({
+ block.cross_attn.proj_linear = nn.Linear(1024, 12)
+ settings = {
'depth_channels': 6, 'rank': 2, 'alpha': 2., 'cross_attention_mode': 'global',
'voxel_condition_mode': 'depth_embedding', 'voxel_aggregation': 'object_mean',
- 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'}))
+ 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'}
+ if image_features is not None:
+ settings['voxel_image_features'] = image_features
+ return install_adapters(flow, **model_settings(settings))
+
+
+def test_dino_default_preserves_native_ss_projection_weights_and_bias():
+ flow = native_flow()
+ for block in flow.blocks:
+ block.cross_attn.proj_linear = nn.Linear(1024, 12)
+ pretrained = [(block.cross_attn.proj_linear.weight.detach().clone(),
+ block.cross_attn.proj_linear.bias.detach().clone()) for block in flow.blocks]
+ # Exercise the SS installer default directly, without a feature override.
+ install_adapters(flow, depth_channels=6, rank=2, alpha=2., voxel_condition_mode='depth_embedding',
+ voxel_aggregation='object_mean', voxel_coverage_weighting='learned_gate',
+ image_projection_adaptation='nora')
+ image = torch.randn(3, 1024)
+ for block, (weight, bias) in zip(flow.blocks, pretrained):
+ projection = block.cross_attn.base.proj_linear
+ assert isinstance(projection, NoRALinear) and projection.in_features == 1024
+ torch.testing.assert_close(projection.weight, weight, rtol=0, atol=0)
+ torch.testing.assert_close(projection.bias, bias, rtol=0, atol=0)
+ torch.testing.assert_close(projection.forward_without_bias(image), image @ weight.T, rtol=0, atol=0)
+ assert not projection.weight.requires_grad and projection.bias.requires_grad
+ assert block.cross_attn.mask_projection.in_features == 2048
+ assert not block.cross_attn.mask_projection.weight.any()
def test_native_ss_backward_and_roundtrip_have_no_segmentation_parameters():
+ image_features, channels = 'dino', 1024
torch.manual_seed(3)
- flow = object_flow()
- conditioner = SSVoxelConditioner(2048, 6, voxel_condition_mode='depth_embedding',
+ flow = object_flow(image_features)
+ conditioner = SSVoxelConditioner(channels, 6, mask_channels=2048, voxel_condition_mode='depth_embedding',
object_aggregation=True)
entry = {
- 'global': torch.randn(5, 4), 'image_proj': torch.zeros(8, 2048),
+ 'global': torch.randn(5, 4), 'image_proj': torch.zeros(8, channels),
'region_indices': torch.tensor([[0, 0, 1], [0, 1, 1]]),
- 'region_image_features': torch.randn(3, 2048),
+ 'region_image_features': torch.randn(3, channels),
'region_object_descriptors': torch.randn(3, 2048),
'region_depth_residual': torch.tensor([[-.2], [.1], [.4]]),
'region_depth_valid': torch.ones(3, 1, dtype=torch.bool),
@@ -103,12 +143,32 @@ def test_native_ss_backward_and_roundtrip_have_no_segmentation_parameters():
saved = adapter_state(flow, conditioner)
assert saved['image_projection_format'] == 'nora-image-projection-v1'
assert not any('segmentation' in key for key in saved['flow'])
- restored = object_flow()
+ restored = object_flow(image_features)
load_adapter_state(restored, conditioner, saved)
for key, value in adapter_state(restored, conditioner)['flow'].items():
torch.testing.assert_close(value, saved['flow'][key], rtol=0, atol=0)
+@pytest.mark.parametrize('explicit', [False, True])
+def test_combined_feature_checkpoint_is_rejected(explicit):
+ flow = object_flow()
+ conditioner = SSVoxelConditioner(1024, 6, mask_channels=2048,
+ voxel_condition_mode='depth_embedding', object_aggregation=True)
+ settings = {
+ 'depth_channels': 6, 'rank': 2, 'alpha': 2., 'cross_attention_mode': 'global',
+ 'voxel_condition_mode': 'depth_embedding', 'voxel_aggregation': 'object_mean',
+ 'image_projection_adaptation': 'nora', 'voxel_coverage_weighting': 'learned_gate'}
+ adapters = adapter_state(flow, conditioner)
+ for name, value in list(adapters['flow'].items()):
+ if name.endswith('.proj_linear.lora_A'):
+ adapters['flow'][name] = torch.cat((value, value), -1)
+ if explicit:
+ settings['voxel_image_features'] = 'dino_naf'
+ saved = {'config': {'model': settings}, 'adapters': adapters}
+ with pytest.raises(ValueError, match='DINO|voxel_image_features'):
+ checkpoint_model_config({'model': settings}, saved)
+
+
def test_online_views_reuse_verified_latents_without_reading_old_conditions(tmp_path, monkeypatch):
from dataloader.prepared import ExtentDataset
from ss_multiobj_depth.config import TARGET_SCOPE
diff --git a/ss_multiobj_depth/tests/test_sage_training_data.py b/ss_multiobj_depth/tests/test_sage_training_data.py
index 2bb6161..14eea0d 100644
--- a/ss_multiobj_depth/tests/test_sage_training_data.py
+++ b/ss_multiobj_depth/tests/test_sage_training_data.py
@@ -86,5 +86,5 @@ def test_training_config_has_no_extent_policy(tmp_path):
config['extent_spec'] = {'strategy': 'point_cloud', 'options': {'padding': 1.4}}
path = tmp_path / 'config.json'
path.write_text(json.dumps(config))
- with pytest.raises(ValueError, match='stage-two preprocessing'):
+ with pytest.raises(ValueError, match='extent_spec'):
load_config(path)
diff --git a/ss_multiobj_depth/tests/test_ss_preparation_workers.py b/ss_multiobj_depth/tests/test_ss_preparation_workers.py
index c4f0b04..4b04f0f 100644
--- a/ss_multiobj_depth/tests/test_ss_preparation_workers.py
+++ b/ss_multiobj_depth/tests/test_ss_preparation_workers.py
@@ -16,10 +16,11 @@ from ss_multiobj_depth.observations import ObservationEncoder, object_lattice
from slat_multiobj_shape.tests.test_finetuning import view
-def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch):
+@pytest.mark.parametrize('local_channels', [2, 4])
+def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch, local_channels):
sample = {**view(), 'resolution': 64}
encoder = ObservationEncoder.__new__(ObservationEncoder)
- encoder.device, encoder.object_aggregation, encoder.local_channels = 'cpu', True, 4
+ encoder.device, encoder.object_aggregation, encoder.local_channels = 'cpu', True, local_channels
encoder.dino = SimpleNamespace(config=SimpleNamespace(num_register_tokens=0))
encoder.naf = SimpleNamespace(query_encoder=lambda x: x, image_encoder=lambda x, **kw: x,
key_encoder=lambda q, f: f, upsampler=SimpleNamespace(num_heads=1, kernel_size=(9, 9)))
@@ -31,6 +32,10 @@ def test_ss_worker_preserves_native_endpoint_features_and_rng(monkeypatch):
np.testing.assert_allclose(grid.to_camera(coords.numpy()/15-.5), cube.to_camera(coords.numpy()/15-.5))
args = (sample['rgb'], sample['masks'], sample['depth'], sample['depth_valid'], sample['intrinsics'].numpy(), cube)
expected, expected_image, expected_transform = encoder.encode(*args, compact=True)
+ assert expected['region_image_features'].shape[1] == local_channels
+ assert expected['region_object_descriptors'].shape[1] == 4
+ torch.testing.assert_close(expected['region_image_features'][:, :2],
+ torch.ones_like(expected['region_image_features'][:, :2]))
rng = torch.get_rng_state().clone()
loader = DataLoader(PreparationDataset([sample], [0], object_aggregation=True), batch_size=1,
num_workers=1, collate_fn=collate_views, generator=torch.Generator().manual_seed(31))
diff --git a/ss_multiobj_depth/tests/test_voxel_condition.py b/ss_multiobj_depth/tests/test_voxel_condition.py
index a539733..35b5537 100644
--- a/ss_multiobj_depth/tests/test_voxel_condition.py
+++ b/ss_multiobj_depth/tests/test_voxel_condition.py
@@ -1,4 +1,4 @@
-"""Both depth gate equations, mode selection, and legacy checkpoint loading."""
+"""Supported SS equations, configuration boundaries, and checkpoint loading."""
from copy import deepcopy
import json
from pathlib import Path
@@ -15,8 +15,8 @@ from ss_multiobj_depth.tests.test_conditioning_training import Projection, entry
from ss_multiobj_depth.train import restore_checkpoint, save_checkpoint
-@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding'])
-def test_gate_only_scales_local_image_and_mask(mode):
+def test_gate_only_scales_local_image_and_mask():
+ mode = 'depth_embedding'
adapter = VoxelConditionProjection(Projection(), 6, voxel_condition_mode=mode)
sample = entry()
conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode)
@@ -25,12 +25,8 @@ def test_gate_only_scales_local_image_and_mask(mode):
with torch.no_grad():
adapter.base.proj_linear.bias.fill_(2)
adapter.mask_projection.weight.fill_(.3)
- if mode == 'depth_scalar':
- adapter.depth_projection.weight.fill_(.2)
- else:
- assert adapter.depth_projection is None
+ assert adapter.depth_projection is None
image, mask = condition['proj'][..., :4], condition['proj'][..., 4:8]
- depth = condition['proj'][..., 8:14]
for bias in (-100., 0., 3., 100.):
with torch.no_grad():
adapter.gate[-1].bias.fill_(bias)
@@ -39,19 +35,17 @@ def test_gate_only_scales_local_image_and_mask(mode):
expected = x + 2 + gate * (
torch.nn.functional.linear(image, adapter.base.proj_linear.weight)
+ adapter.mask_projection(mask))
- if mode == 'depth_scalar':
- expected = expected + adapter.depth_projection(depth)
torch.testing.assert_close(adapter(x, condition), expected)
-@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding'])
-def test_gate_input_and_cfg_follow_selected_equation(mode):
+def test_gate_input_and_cfg_follow_selected_equation():
+ mode = 'depth_embedding'
adapter = VoxelConditionProjection(Projection(), 6, voxel_condition_mode=mode)
sample = entry()
sample['depth_valid'][0] = False
conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode)
condition = conditioner([sample, sample], drop=torch.tensor([False, True]))
- assert condition['proj'].shape == (2, 8, 15 if mode == 'depth_scalar' else 14)
+ assert condition['proj'].shape == (2, 8, 14)
assert not condition['proj'][1].any() and not condition['global'][1].any()
assert not condition['proj'][0, 0, 8:14].any()
assert all(not value.any() for value in negative_condition(condition).values())
@@ -65,20 +59,14 @@ def test_gate_input_and_cfg_follow_selected_equation(mode):
adapter(x, condition | {'proj': changed})
finally:
hook.remove()
- if mode == 'depth_scalar':
- torch.testing.assert_close(condition['proj'][0, :, -1:], sample['depth_residual'].clamp(-1, 1))
- expected = torch.cat((x, condition['proj'][..., -1:]), -1)
- for value in inputs:
- torch.testing.assert_close(value, expected)
- else:
- torch.testing.assert_close(inputs[0], torch.cat((x, condition['proj'][..., 8:14]), -1))
- torch.testing.assert_close(inputs[1][..., 7:], inputs[0][..., 7:] + 100)
+ torch.testing.assert_close(inputs[0], torch.cat((x, condition['proj'][..., 8:14]), -1))
+ torch.testing.assert_close(inputs[1][..., 7:], inputs[0][..., 7:] + 100)
with pytest.raises(ValueError, match='Packed'):
adapter(x, condition | {'proj': condition['proj'][..., :-1]})
-@pytest.mark.parametrize(('name', 'mode'), [('depth_residual_gate', 'depth_scalar'), ('depth_embedding_gate', 'depth_embedding')])
-def test_config_selects_equation_and_explicit_run_directories(monkeypatch, name, mode):
+def test_config_selects_equation_and_explicit_run_directories(monkeypatch):
+ name, mode = 'depth_embedding_gate', 'depth_embedding'
import ss_multiobj_depth.train as runner
original = load_config('ss_multiobj_depth/configs/front3d_sage.json')
path = f'ss_multiobj_depth/configs/front3d_sage_{name}.json'
@@ -106,8 +94,25 @@ def test_training_rejects_removed_visibility_flag(monkeypatch):
assert error.value.code == 2
-@pytest.mark.parametrize('mode', ['additive', 'depth_scalar', 'depth_embedding'])
-def test_checkpoint_mode_detection_and_legacy_adapter_restore(mode):
+def test_historical_nora_checkpoint_cannot_load_into_lora_with_identical_tensor_names():
+ settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': 'depth_embedding',
+ 'image_projection_adaptation': 'full'}
+ conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode='depth_embedding')
+ native_nora = install_adapters(native_flow(), **settings, adapter_method='nora')
+ state = adapter_state(native_nora, conditioner)
+ saved = {'config': {'model': settings}, 'adapters': state}
+ resolved = checkpoint_model_config({'model': settings}, saved)
+ assert resolved['model']['adapter_method'] == 'nora'
+ restored = install_adapters(native_flow(), **resolved['model'])
+ load_adapter_state(restored, conditioner, state)
+ lora = install_adapters(native_flow(), **settings, adapter_method='lora')
+ assert adapter_state(lora, conditioner)['flow'].keys() == state['flow'].keys()
+ with pytest.raises(ValueError, match='backbone adapter method differs'):
+ load_adapter_state(lora, conditioner, state)
+
+
+@pytest.mark.parametrize('mode', ['additive', 'depth_embedding'])
+def test_checkpoint_mode_detection_and_adapter_restore(mode):
settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': mode}
flow = install_adapters(native_flow(), **settings)
conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode=mode)
@@ -123,11 +128,11 @@ def test_checkpoint_mode_detection_and_legacy_adapter_restore(mode):
load_adapter_state(restored, conditioner, saved['adapters'])
for key, value in adapter_state(restored, conditioner)['flow'].items():
torch.testing.assert_close(value, saved['adapters']['flow'][key], rtol=0, atol=0)
- for wrong in {'additive', 'depth_scalar', 'depth_embedding'} - {mode}:
+ for wrong in {'additive', 'depth_embedding'} - {mode}:
with pytest.raises(ValueError, match='differs'):
checkpoint_model_config({'model': {**original['model'], 'voxel_condition_mode': wrong}}, saved)
corrupt = deepcopy(saved)
- corrupt['config']['model']['voxel_condition_mode'] = 'depth_embedding' if mode != 'depth_embedding' else 'depth_scalar'
+ corrupt['config']['model']['voxel_condition_mode'] = 'depth_embedding' if mode != 'depth_embedding' else 'additive'
with pytest.raises(ValueError, match='differs from its adapter tensors'):
checkpoint_model_config(original, corrupt)
@@ -152,8 +157,73 @@ def test_new_run_with_ambiguous_legacy_settings_requires_a_mode():
model_settings({'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_hidden_channels': 64})
-@pytest.mark.parametrize('mode', ['depth_scalar', 'depth_embedding'])
-def test_legacy_resume_still_checks_mode_data_and_source(tmp_path, monkeypatch, mode):
+@pytest.mark.parametrize('fields', [
+ {'voxel_condition_mode': 'depth_scalar'}, {'voxel_image_features': 'dino_naf'},
+ {'image_projection_adaptation': 'frozen'}, {'visibility_hidden_channels': 64},
+ {'visibility_mode': 'embedding'}, {'object_attention_layers': 1},
+])
+def test_removed_ss_model_options_are_rejected_in_configs_and_installers(tmp_path, fields):
+ config = json.loads(Path('ss_multiobj_depth/configs/front3d_sage_depth_embedding_gate.json').read_text())
+ config['model'].update(fields)
+ path = tmp_path / 'invalid.json'
+ path.write_text(json.dumps(config))
+ with pytest.raises(ValueError):
+ load_config(path)
+ with pytest.raises(ValueError):
+ model_settings(config['model'])
+ with pytest.raises((ValueError, TypeError)):
+ install_adapters(object(), **fields)
+
+
+def test_removed_conditioner_modes_and_local_width_are_rejected():
+ with pytest.raises(ValueError, match='voxel_condition_mode'):
+ SSVoxelConditioner(voxel_condition_mode='depth_scalar')
+ with pytest.raises(ValueError, match='DINO local features'):
+ SSVoxelConditioner(2048, object_aggregation=True, voxel_condition_mode='depth_embedding')
+
+
+def test_every_retained_ss_run_preset_loads():
+ paths = Path('ss_multiobj_depth/configs').glob('*.json')
+ for path in paths:
+ if json.loads(path.read_text()).get('schema') != 'ss-multiobj-depth-v1':
+ continue
+ config = load_config(path)
+ assert config['model']['voxel_condition_mode'] in ('additive', 'depth_embedding')
+ assert config['model']['image_projection_adaptation'] in ('full', 'lora', 'nora')
+ assert config['model'].get('voxel_image_features', 'dino') == 'dino'
+
+
+@pytest.mark.parametrize('change', ['gate_names', 'image_weights', 'image_format', 'adapter_method'])
+def test_retired_checkpoint_formats_are_rejected_for_inference_and_resume(tmp_path, monkeypatch, change):
+ import utils.paths
+ monkeypatch.setattr(utils.paths, 'REPO_ROOT', tmp_path)
+ settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2,
+ 'voxel_condition_mode': 'depth_embedding', 'image_projection_adaptation': 'full'}
+ flow = install_adapters(native_flow(), **settings)
+ conditioner = SSVoxelConditioner(4, 6, voxel_condition_mode='depth_embedding')
+ optimizer = torch.optim.AdamW([p for p in flow.parameters() if p.requires_grad]
+ + list(conditioner.parameters()))
+ path = tmp_path / 'checkpoints/last.pt'
+ save_checkpoint(path, flow, conditioner, optimizer, step=1,
+ config={'device': 'cpu', 'model': settings}, protocol={}, provenance={})
+ state = torch.load(path, weights_only=True)
+ adapters = state['adapters']
+ if change == 'gate_names':
+ adapters['flow'] = {key.replace('.gate.', '.visibility.'): value for key, value in adapters['flow'].items()}
+ elif change == 'image_weights':
+ adapters['flow'] = {key: value for key, value in adapters['flow'].items() if '.proj_linear.' not in key}
+ elif change == 'image_format':
+ del adapters['image_projection_format']
+ else:
+ del adapters['backbone_adapter_method']
+ torch.save(state, path)
+ for resume_optimizer in (None, optimizer):
+ with pytest.raises(ValueError, match='adapter format or trainable parameters'):
+ restore_checkpoint(path, flow, conditioner, optimizer=resume_optimizer)
+
+
+def test_resume_checks_mode_data_and_source(tmp_path, monkeypatch):
+ mode = 'depth_embedding'
import utils.paths
monkeypatch.setattr(utils.paths, 'REPO_ROOT', tmp_path)
settings = {'depth_channels': 6, 'rank': 2, 'alpha': 2, 'voxel_condition_mode': mode}
@@ -172,13 +242,13 @@ def test_legacy_resume_still_checks_mode_data_and_source(tmp_path, monkeypatch,
restore_checkpoint(path, flow, conditioner, protocol=current)
state = restore_checkpoint(path, flow, conditioner, protocol=current, accept_source_changes=True)
assert state['source_changes'] == {'train.py': {'checkpoint': 'old', 'current': 'new'}}
- wrong_mode = 'depth_embedding' if mode == 'depth_scalar' else 'depth_scalar'
- for change in ({'manifest_sha256': 'other'}, {'model': {**current['model'], 'voxel_condition_mode': wrong_mode}}):
+ wrong_mode = 'additive'
+ for change in ({'manifest_sha256': 'other'}, {'model': {**current['model'], 'voxel_condition_mode': wrong_mode, 'voxel_condition_hidden_channels': 0}}):
with pytest.raises(ValueError, match='only source changes'):
restore_checkpoint(path, flow, conditioner, protocol={**current, **change}, accept_source_changes=True)
-def test_training_cli_defaults_to_embedding_without_changing_legacy_configs(monkeypatch):
+def test_training_cli_defaults_to_three_dataset_coverage_and_preserves_additive_presets(monkeypatch):
import ss_multiobj_depth.train as runner
from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG
calls = []
@@ -190,8 +260,18 @@ def test_training_cli_defaults_to_embedding_without_changing_legacy_configs(monk
assert options == {'resume': False, 'accept_source_changes': False}
assert config['model']['voxel_condition_mode'] == 'depth_embedding'
assert config['model']['voxel_condition_hidden_channels'] == 64
+ assert config['model']['voxel_aggregation'] == 'object_mean'
+ assert config['model']['voxel_coverage_weighting'] == 'learned_gate'
+ assert config['training']['conditioning_source'] == 'online'
+ assert config['training']['batch_size'] == 16
+ assert config['training']['accumulation'] == 1
+ assert [source['dataset'] for source in config['sources']] == [
+ 'datasets/3dfront/extent/point_cloud',
+ 'datasets/sage/extent/point_cloud',
+ 'datasets/foundationpose/extent/point_cloud',
+ ]
legacy = load_config('ss_multiobj_depth/configs/front3d_sage.json')
- assert config['sources'] == legacy['sources']
+ assert len(legacy['sources']) == 2
for key in ('output', 'checkpoints'):
assert config[key] != legacy[key]
assert model_settings(load_config()['model'])['voxel_condition_mode'] == 'additive'
diff --git a/ss_multiobj_depth/train.py b/ss_multiobj_depth/train.py
index dd0b4ee..77c1c01 100644
--- a/ss_multiobj_depth/train.py
+++ b/ss_multiobj_depth/train.py
@@ -20,6 +20,8 @@ from utils.training.checkpoints import (load_training_checkpoint, restore_optimi
save_training_checkpoint)
from utils.training.depth_augmentation import augment_depth
from utils.training.optim import make_optimizer, optimizer_record, set_learning_rates
+from utils.training.ema import TrainableEMA, checkpoint_ema, restore_ema
+from utils.training.cfg import cfg_defaults
from .config import (DEFAULT_TRAINING_CONFIG, TARGET_SCOPE, checkpoint_model_config, load_config,
make_model, model_provenance, model_settings,
preparation_settings, source_configs, training_protocol, online_conditioning)
@@ -30,7 +32,9 @@ from .runtime import ROOT, path_under
CHECKPOINT_SCHEMA = 'ss-multiobj-depth-checkpoint-v1'
-def flow_loss(flow, conditioner, entries, cfg_dropout=.1):
+def flow_loss(flow, conditioner, entries, cfg_dropout=None):
+ if cfg_dropout is None:
+ cfg_dropout = cfg_defaults('ss')['cfg_dropout']
if not 0 <= cfg_dropout <= 1:
raise ValueError('Invalid joint CFG dropout')
clean = torch.stack([entry['clean'] for entry in entries])
@@ -75,10 +79,11 @@ class UpdateSampler(Sampler):
return (self.steps - self.start) * self.per_update
-def save_checkpoint(path, flow, conditioner, optimizer, *, step, config, protocol, provenance, history=()):
+def save_checkpoint(path, flow, conditioner, optimizer, *, step, config, protocol, provenance, history=(), ema=None):
payload = {'schema': CHECKPOINT_SCHEMA, 'step': step, 'config': config, 'protocol': protocol,
'provenance': provenance, 'adapters': adapter_state(flow, conditioner),
'accepted_source_changes': list(history)}
+ payload.update(checkpoint_ema(ema, config.get('training', {}), step))
save_training_checkpoint(path, payload, optimizer=optimizer, device=config['device'])
@@ -97,7 +102,8 @@ def source_changes(saved, protocol):
for path, digest in protocol['source_sha256'].items() if recorded.get(path) != digest}
-def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None, accept_source_changes=False):
+def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None, accept_source_changes=False,
+ ema=None, weights='raw'):
"""Load adapters and optimizer state; the protocol must match unless source changes are accepted."""
state = load_training_checkpoint(path, CHECKPOINT_SCHEMA)
if protocol is not None:
@@ -109,10 +115,18 @@ def restore_checkpoint(path, flow, conditioner, *, protocol=None, optimizer=None
state['source_changes'] = source_changes(recorded, current)
elif recorded != current:
raise ValueError('Resume data, model, objective or source code changed')
- legacy = load_adapter_state(flow, conditioner, state['adapters'], allow_legacy=optimizer is None)
+ from models.voxel_condition import image_projection_format
+ adapters = state['adapters']
+ required = {name for name, parameter in flow.named_parameters() if parameter.requires_grad}
+ if (set(adapters['flow']) != required
+ or adapters.get('image_projection_format') != image_projection_format(flow)
+ or adapters.get('backbone_adapter_method') != getattr(flow, 'voxel_adapter_method', 'nora')):
+ raise ValueError('SS checkpoint adapter format or trainable parameters differ from this model')
+ load_adapter_state(flow, conditioner, adapters, allow_legacy=False)
+ trainable = torch.nn.ModuleDict({'flow': flow, 'conditioner': conditioner})
+ restore_ema(state, trainable, ema=ema, training=optimizer is not None, weights=weights)
if optimizer is not None:
restore_optimizer_state(state, optimizer, next(flow.parameters()).device)
- state['pretrained_image_projection_parameters'] = legacy
return state
@@ -226,10 +240,11 @@ def train(config, *, resume=False, accept_source_changes=False):
trainable = torch.nn.ModuleDict({'flow': flow, 'conditioner': conditioner})
parameters = [p for p in trainable.parameters() if p.requires_grad]
optimizer = make_optimizer(trainable, settings)
+ ema = TrainableEMA(trainable, settings['ema_decay']) if settings.get('ema_decay') is not None else None
step, history = 0, []
if resume:
state = restore_checkpoint(checkpoint, flow, conditioner, protocol=protocol, optimizer=optimizer,
- accept_source_changes=accept_source_changes)
+ accept_source_changes=accept_source_changes, ema=ema)
if state['provenance'] != provenance:
raise ValueError('Base model weights changed since checkpoint')
step = state['step']
@@ -249,7 +264,7 @@ def train(config, *, resume=False, accept_source_changes=False):
for source, cache in zip(sources, caches)],
'accepted_source_changes': history})
save = lambda: save_checkpoint(checkpoint, flow, conditioner, optimizer, step=step, config=config,
- protocol=protocol, provenance=provenance, history=history)
+ protocol=protocol, provenance=provenance, history=history, ema=ema)
if not resume:
save()
tracker = None
@@ -297,10 +312,14 @@ def train(config, *, resume=False, accept_source_changes=False):
losses.append(float(loss.detach()))
norm = torch.nn.utils.clip_grad_norm_(parameters, 1., error_if_nonfinite=True)
optimizer.step()
+ if ema is not None:
+ ema.update(trainable)
step += 1
record = {'step': step, 'flow_mse': sum(losses) / len(losses),
'grad_norm': float(norm), 'learning_rate': optimizer.param_groups[0]['lr'],
'seconds': time.monotonic() - started}
+ if ema is not None:
+ record.update(ema_decay=ema.decay, ema_updates=ema.num_updates)
for group in optimizer.param_groups:
if group['name'] == 'adapter':
record['adapter_learning_rate'] = group['lr']
diff --git a/utils/training/README.md b/utils/training/README.md
new file mode 100644
index 0000000..9557e28
--- /dev/null
+++ b/utils/training/README.md
@@ -0,0 +1,96 @@
+# Shared training settings
+
+SS, generative SLAT segmentation, and SLAT shape use one optimization recipe in [configs/default.json](configs/default.json).
+Each training preset references this file through `training.optimizer_config`.
+Presets cannot combine this reference with inline optimization settings.
+
+| Parameter | Shared value |
+| --- | --- |
+| Optimizer | AdamW |
+| Adapter method | LoRA, with `adapter_method="lora"` |
+| New-layer learning rate | `1e-4` |
+| Adapter learning rate | `1e-4` |
+| Betas | `(0.9, 0.95)` |
+| Non-adapter matrix decay | `0.01` |
+| Adapter decay | `0.01` |
+| Bias, normalization, scalar, and vector decay | `0` |
+| Linear warmup | 500 optimizer updates |
+| Epsilon | `1e-8` |
+| Weight EMA decay | `0.999` |
+
+Edit `configs/default.json` to change the recipe for all three stages.
+Set `adapter_method` to `lora` or `nora` in that file to select the adapter implementation.
+
+The default presets use `shared` for backbone adapters and image projection adapters.
+SS and SLAT shape read `model.adapter_method`.
+SLAT segmentation reads `model.mode`.
+Their `model.image_projection_adaptation` values also resolve from the shared method.
+The loaders replace `shared` with the selected method before constructing each model.
+Explicit historical configurations retain their own adapter choices.
+
+LoRA keeps pretrained base matrices frozen and trains its low-rank residuals.
+Image biases remain trainable, and image residuals initialize to zero.
+
+Each loader resolves the reference before training starts.
+The run snapshot and checkpoint store the resolved values and the source file hash.
+Later edits to the shared file do not change stored run snapshots.
+Resume checks reject a changed optimization recipe.
+
+EMA means exponential moving average.
+EMA starts from the initial trainable weights and updates once after each completed optimizer step, including warmup.
+Accumulation batches do not trigger separate EMA updates.
+The FP32 averages include only trainable parameters and require no additional frozen backbone copy.
+
+Checkpoints store raw weights, optimizer state, EMA weights, and the EMA update count.
+Training resumes raw weights and the saved EMA history.
+Evaluation and inference use EMA weights when available.
+Segmentation monitoring temporarily applies EMA weights and preserves raw weights on CPU until evaluation ends.
+
+The optional top-level `inference_weights` setting accepts `auto`, `raw`, or `ema`.
+The default `auto` selects raw weights for historical checkpoints without EMA.
+An explicit `ema` selection requires saved EMA weights.
+Historical run snapshots with inline settings retain their recorded values.
+An optimizer resume cannot invent missing EMA history or silently change parameter groups.
+
+All three stages use Pixal3D's native loss averaging.
+A microbatch is one forward and backward batch within an optimizer update.
+Sparse SLAT losses average all supervised token and channel errors within each microbatch.
+SS averages every element of its dense latent tensor, including all channels and grid cells.
+Gradient accumulation averages microbatch losses, as Pixal3D does.
+
+Per-scene MSE remains available for diagnostics and does not define sparse training weights.
+SLAT shape excludes tokens without matching GT latents.
+Empty segmentation scenes contribute no errors and do not dilute nonempty scenes.
+
+CFG means classifier-free guidance.
+All CFG controls reside in [configs/cfg.json](configs/cfg.json).
+Each training preset references that file through the top-level `cfg_config` field.
+The profile controls training dropout, inference guidance strength, guidance rescaling, and the guidance interval.
+
+| Stage | Training dropout | Inference strength | Guidance rescale | Guidance interval |
+| --- | --- | --- | --- | --- |
+| SS | `0.1` | `7.5` | `0.7` | `[0.6, 1.0]` |
+| SLAT shape | `0.1` | `7.5` | `0.5` | `[0.6, 1.0]` |
+| Generative SLAT segmentation | `0.0` | `1.0` | `0.0` | `[0.0, 1.0]` |
+
+Loaders resolve the profile into `training.cfg_dropout` and the stage's `sampling` fields.
+SS retains its `cfg_strength`, `cfg_rescale`, and `cfg_interval` field names in resolved settings.
+SLAT stages use `guidance_strength`, `guidance_rescale`, and `guidance_interval`.
+Sampling steps, timestep warping, and the minimum noise level remain separate from CFG controls.
+
+The run snapshot stores resolved values and the profile hash.
+Later profile edits change new runs without changing resolved snapshots or running jobs.
+A shared reference cannot include inline CFG values.
+Historical configurations without a shared reference retain their explicit values.
+Resume checks compare training dropout and permit changes to inference guidance independently.
+
+SS and SLAT shape match [GenRecon's 10% dropout recipe](https://github.com/kasothaphie/GenRecon/blob/eaf1468118d20469d17079a4a19737297d2ef87b/configs/gen/slat_flow_img2shape/genrecon_512.json) and [WorldSculpt's released checkpoint settings](https://huggingface.co/AlayaLab/WorldSculpt/blob/main/shape_ft1024_mv_lora_ibr_texverse_fixedmem05/config.json).
+Each scene receives one independent dropout decision, shared across its observation conditions.
+Dropout occurs after the learned depth embedding and preserves spatial support, object assignments, and supervision.
+Training uses one prediction per scene without multiplying its velocity by the sampling guidance strength.
+
+SLAT segmentation keeps condition dropout disabled and samples with conditional predictions only.
+The loader requires zero training dropout, inference strength one, and zero guidance rescaling for segmentation.
+An omitted rate in historical configurations also means zero.
+This project choice matches [SegviGen's default conditional sampling](https://github.com/Nelipot-Lee/SegviGen/blob/81ec99ede1fbe566c73322dd968cd64bb508f5f7/inference_full.py).
+SegviGen does not report its actual finetuning dropout rate, so this choice does not establish an exact match for training.
diff --git a/utils/training/cfg.py b/utils/training/cfg.py
new file mode 100644
index 0000000..1930ea8
--- /dev/null
+++ b/utils/training/cfg.py
@@ -0,0 +1,97 @@
+"""Resolve stage CFG settings and preserve explicit values in saved runs."""
+from copy import deepcopy
+import json
+import math
+
+from utils.hashing import sha256
+from utils.paths import REPO_ROOT
+
+DEFAULT_CFG_CONFIG = 'utils/training/configs/cfg.json'
+STAGES = ('ss', 'slat_shape', 'slat_segmentation')
+GUIDANCE_KEYS = ('guidance_strength', 'guidance_rescale', 'guidance_interval')
+SS_GUIDANCE_KEYS = dict(zip(GUIDANCE_KEYS, ('cfg_strength', 'cfg_rescale', 'cfg_interval')))
+
+
+def validate_cfg(settings, stage):
+ if stage not in STAGES:
+ raise ValueError('Unknown CFG stage')
+ if stage == 'slat_segmentation':
+ dropout = settings['cfg_dropout']
+ if type(dropout) not in (int, float) or dropout != 0:
+ raise ValueError('SLAT segmentation requires cfg_dropout=0. Condition dropout is disabled')
+ if settings['guidance_strength'] != 1 or settings['guidance_rescale'] != 0:
+ raise ValueError('Conditional-only SLAT segmentation requires guidance_strength=1 and guidance_rescale=0')
+ for key in ('cfg_dropout', 'guidance_strength', 'guidance_rescale'):
+ if type(settings[key]) not in (int, float) or not math.isfinite(settings[key]):
+ raise ValueError(f'{key} must be a finite number')
+ if not 0 <= settings['cfg_dropout'] < 1:
+ raise ValueError('cfg_dropout must lie in [0,1)')
+ if settings['guidance_strength'] < 0 or not 0 <= settings['guidance_rescale'] <= 1:
+ raise ValueError('Invalid CFG strength or rescale')
+ interval = settings['guidance_interval']
+ if (not isinstance(interval, (list, tuple)) or len(interval) != 2
+ or any(type(value) not in (int, float) or not math.isfinite(value) for value in interval)
+ or not 0 <= interval[0] <= interval[1] <= 1):
+ raise ValueError('guidance_interval must be ordered within [0,1]')
+
+
+def read_cfg_profile(path=DEFAULT_CFG_CONFIG):
+ if not isinstance(path, str) or not path:
+ raise ValueError('cfg_config must name a shared settings file')
+ path = (REPO_ROOT / path).resolve()
+ if not path.is_relative_to(REPO_ROOT / 'utils/training/configs'):
+ raise ValueError('CFG settings must reside under utils/training/configs')
+ recipe = json.loads(path.read_text())
+ if (not isinstance(recipe, dict) or set(recipe) != {'schema', *STAGES}
+ or recipe['schema'] != 'partprobe3d-cfg-v1'):
+ raise ValueError('Expected partprobe3d-cfg-v1 settings')
+ for stage in STAGES:
+ if not isinstance(recipe[stage], dict) or set(recipe[stage]) != {'cfg_dropout', *GUIDANCE_KEYS}:
+ raise ValueError('Every CFG stage must specify dropout, strength, rescale, and interval')
+ validate_cfg(recipe[stage], stage)
+ return recipe, {'path': str(path.relative_to(REPO_ROOT)), 'sha256': sha256(path)}
+
+
+def cfg_defaults(stage):
+ if stage not in STAGES:
+ raise ValueError('Unknown CFG stage')
+ recipe, _ = read_cfg_profile()
+ return recipe[stage]
+
+
+def guidance_defaults(stage):
+ settings = cfg_defaults(stage)
+ return {key: settings[key] for key in GUIDANCE_KEYS}
+
+
+def resolve_cfg_settings(config, stage):
+ """Resolve one reference. Historical literals and resolved snapshots stay fixed."""
+ if stage not in STAGES:
+ raise ValueError('Unknown CFG stage')
+ aliases = SS_GUIDANCE_KEYS if stage == 'ss' else {key: key for key in GUIDANCE_KEYS}
+ if 'cfg_config' not in config:
+ if 'cfg_profile' in config:
+ if config['cfg_profile']['stage'] != stage:
+ raise ValueError('The saved CFG profile belongs to another stage')
+ settings = {key: config['sampling'][alias] for key, alias in aliases.items()}
+ settings['cfg_dropout'] = config.get('training', {}).get('cfg_dropout', 0.)
+ validate_cfg(settings, stage)
+ elif stage == 'slat_segmentation':
+ settings = {'cfg_dropout': config['training'].get('cfg_dropout', 0.),
+ 'guidance_strength': 1., 'guidance_rescale': 0., 'guidance_interval': [0., 1.],
+ **config.get('sampling', {})}
+ validate_cfg(settings, stage)
+ return config
+ if ('cfg_profile' in config or 'cfg_dropout' in config.get('training', {})
+ or (set(GUIDANCE_KEYS) | set(SS_GUIDANCE_KEYS.values())).intersection(config.get('sampling', {}))):
+ raise ValueError('Shared cfg_config cannot have inline CFG settings')
+ recipe, profile = read_cfg_profile(config['cfg_config'])
+ selected = recipe[stage]
+ result = deepcopy(config)
+ del result['cfg_config']
+ if 'training' in result:
+ result['training']['cfg_dropout'] = selected['cfg_dropout']
+ result['sampling'] = {**result.get('sampling', {}),
+ **{alias: selected[key] for key, alias in aliases.items()}}
+ result['cfg_profile'] = {**profile, 'stage': stage}
+ return result
diff --git a/utils/training/configs/cfg.json b/utils/training/configs/cfg.json
new file mode 100644
index 0000000..610777c
--- /dev/null
+++ b/utils/training/configs/cfg.json
@@ -0,0 +1,21 @@
+{
+ "schema": "partprobe3d-cfg-v1",
+ "ss": {
+ "cfg_dropout": 0.1,
+ "guidance_strength": 7.5,
+ "guidance_rescale": 0.7,
+ "guidance_interval": [0.6, 1.0]
+ },
+ "slat_shape": {
+ "cfg_dropout": 0.1,
+ "guidance_strength": 7.5,
+ "guidance_rescale": 0.5,
+ "guidance_interval": [0.6, 1.0]
+ },
+ "slat_segmentation": {
+ "cfg_dropout": 0.0,
+ "guidance_strength": 1.0,
+ "guidance_rescale": 0.0,
+ "guidance_interval": [0.0, 1.0]
+ }
+}
diff --git a/utils/training/configs/default.json b/utils/training/configs/default.json
new file mode 100644
index 0000000..e97363b
--- /dev/null
+++ b/utils/training/configs/default.json
@@ -0,0 +1,16 @@
+{
+ "schema": "partprobe3d-optimization-v1",
+ "adapter_method": "lora",
+ "learning_rate": 0.0001,
+ "weight_decay": 0.01,
+ "ema_decay": 0.999,
+ "optimizer": {
+ "name": "AdamW",
+ "adapter_learning_rate": 0.0001,
+ "betas": [0.9, 0.95],
+ "adapter_weight_decay": 0.01,
+ "bias_norm_scalar_weight_decay": 0.0,
+ "warmup_steps": 500,
+ "eps": 1e-8
+ }
+}
diff --git a/utils/training/ema.py b/utils/training/ema.py
new file mode 100644
index 0000000..9b22290
--- /dev/null
+++ b/utils/training/ema.py
@@ -0,0 +1,129 @@
+"""Maintain an FP32 moving average of trainable parameters without copying the backbone."""
+import math
+from contextlib import contextmanager
+
+import torch
+
+
+def validate_ema_decay(decay):
+ if (isinstance(decay, bool) or not isinstance(decay, (int, float))
+ or not math.isfinite(decay) or not 0 <= decay < 1):
+ raise ValueError('EMA decay must be finite and in [0,1)')
+
+
+def _parameters(model):
+ return {name: p for name, p in model.named_parameters() if p.requires_grad}
+
+
+def _validate_state(parameters, state):
+ if not isinstance(state, dict) or set(state) != {'decay', 'num_updates', 'parameters'}:
+ raise ValueError('Invalid EMA checkpoint state')
+ validate_ema_decay(state['decay'])
+ if type(state['num_updates']) is not int or state['num_updates'] < 0:
+ raise ValueError('EMA update count must be a nonnegative integer')
+ values = state['parameters']
+ if not isinstance(values, dict) or set(values) != set(parameters):
+ raise ValueError('EMA parameters differ from the trainable model parameters')
+ for name, p in parameters.items():
+ value = values[name]
+ if not isinstance(value, torch.Tensor) or value.shape != p.shape or value.dtype != torch.float32:
+ raise ValueError(f'EMA parameter shape or dtype differs: {name}')
+
+
+@torch.no_grad()
+def load_ema_weights(model, state):
+ """Copy saved averages into the model without allocating another EMA on its device."""
+ parameters = _parameters(model)
+ _validate_state(parameters, state)
+ for name, p in parameters.items():
+ p.copy_(state['parameters'][name])
+
+
+def checkpoint_ema(ema, settings, step):
+ """Require complete EMA history when the run enables averaging."""
+ if ema is None:
+ if settings.get('ema_decay') is not None:
+ raise ValueError('EMA is enabled but its checkpoint state is missing')
+ return {}
+ if ema.num_updates != step:
+ raise ValueError('EMA update count differs from the checkpoint step')
+ if ema.decay != settings.get('ema_decay'):
+ raise ValueError('EMA decay differs from the checkpoint training settings')
+ return {'ema': ema.state_dict()}
+
+
+def restore_ema(saved, model, *, ema=None, training=False, weights='raw'):
+ """Resume EMA history or select inference weights without creating a second model."""
+ if weights not in ('auto', 'raw', 'ema') or (training and weights != 'raw'):
+ raise ValueError('Optimizer resume requires raw weights. Inference weights must be auto, raw or ema')
+ state = saved.get('ema')
+ selected = weights == 'ema' or (weights == 'auto' and state is not None)
+ if ema is not None or selected:
+ if state is None:
+ raise ValueError('The checkpoint has no EMA state')
+ _validate_state(_parameters(model), state)
+ if state['num_updates'] != saved['step']:
+ raise ValueError('EMA update count differs from the checkpoint step')
+ if state['decay'] != saved['config'].get('training', {}).get('ema_decay'):
+ raise ValueError('EMA decay differs from the checkpoint training settings')
+ if ema is not None:
+ ema.load_state_dict(state)
+ elif training and state is not None:
+ raise ValueError('The checkpoint uses EMA but training has EMA disabled')
+ if selected:
+ load_ema_weights(model, state)
+ saved['checkpoint_weights'] = 'ema' if selected else 'raw'
+
+
+class TrainableEMA:
+ """Initialize from current weights and update once after each optimizer step."""
+ def __init__(self, model, decay):
+ validate_ema_decay(decay)
+ self.decay = float(decay)
+ self.num_updates = 0
+ self.parameters = {name: p.detach().to(dtype=torch.float32, copy=True)
+ for name, p in _parameters(model).items()}
+
+ @torch.no_grad()
+ def update(self, model):
+ parameters = _parameters(model)
+ if set(parameters) != set(self.parameters):
+ raise ValueError('EMA parameters changed during training')
+ for name, p in parameters.items():
+ self.parameters[name].lerp_(p.detach().float(), 1 - self.decay)
+ self.num_updates += 1
+
+ @torch.no_grad()
+ def reset_parameters(self, model, names):
+ """Apply intentional parameter resets to the corresponding averages only."""
+ parameters = _parameters(model)
+ for name in names:
+ self.parameters[name].copy_(parameters[name])
+
+ def state_dict(self):
+ return {'decay': self.decay, 'num_updates': self.num_updates,
+ 'parameters': {name: p.detach().cpu() for name, p in self.parameters.items()}}
+
+ @contextmanager
+ def average_parameters(self, model):
+ """Evaluate averages temporarily, keeping the raw backup on CPU to limit VRAM."""
+ parameters = _parameters(model)
+ backup = {name: p.detach().to(device='cpu', copy=True) for name, p in parameters.items()}
+ try:
+ with torch.no_grad():
+ for name, p in parameters.items():
+ p.copy_(self.parameters[name])
+ yield
+ finally:
+ with torch.no_grad():
+ for name, p in parameters.items():
+ p.copy_(backup[name])
+
+ @torch.no_grad()
+ def load_state_dict(self, state):
+ _validate_state(self.parameters, state)
+ if state['decay'] != self.decay:
+ raise ValueError('EMA decay differs from the checkpoint')
+ for name, p in self.parameters.items():
+ p.copy_(state['parameters'][name])
+ self.num_updates = state['num_updates']
diff --git a/utils/training/losses.py b/utils/training/losses.py
index 55c34aa..ef58439 100644
--- a/utils/training/losses.py
+++ b/utils/training/losses.py
@@ -1,8 +1,21 @@
-"""Small visible-membership training utilities, separate from occupancy labels."""
+"""Shared loss reductions and utilities for observed membership."""
import torch
from torch.nn import functional as F
+def native_batch_mean(losses, element_counts):
+ """Weight sample means by scalar counts, matching Pixal3D's pooled MSE.
+
+ Empty samples supply a differentiable zero with a count of zero.
+ """
+ if not losses or len(losses) != len(element_counts):
+ raise ValueError('Supply one scalar count for each sample loss')
+ values = torch.stack(losses)
+ counts = torch.stack([torch.as_tensor(count, device=values.device, dtype=values.dtype)
+ for count in element_counts])
+ return (values * counts).sum() / counts.sum().clamp_min(1)
+
+
def asset_components(scene_assets):
"""Connected scene groups; no source asset can cross between groups."""
remaining = set(scene_assets)
diff --git a/utils/training/optim.py b/utils/training/optim.py
index 7b47bff..171ca0f 100644
--- a/utils/training/optim.py
+++ b/utils/training/optim.py
@@ -12,9 +12,17 @@ def validate_optimizer(settings):
raise ValueError(f'Invalid optimizer {key}')
extra = settings.get('optimizer', {})
allowed = {'betas', 'eps', 'adapter_learning_rate', 'adapter_weight_decay', 'warmup_steps',
- 'adapter_learning_rate_after_warmup'}
+ 'adapter_learning_rate_after_warmup', 'exclude_bias_norm_from_weight_decay',
+ 'name', 'bias_norm_scalar_weight_decay'}
if not isinstance(extra, dict) or set(extra) - allowed:
- raise ValueError('Unknown segmentation optimizer settings')
+ raise ValueError('Unknown optimizer settings')
+ if extra.get('name', 'AdamW') != 'AdamW':
+ raise ValueError('The supported optimizer is AdamW')
+ decay = extra.get('bias_norm_scalar_weight_decay', 0.)
+ if isinstance(decay, bool) or not isinstance(decay, (int, float)) or not math.isfinite(decay) or decay < 0:
+ raise ValueError('Invalid optimizer bias_norm_scalar_weight_decay')
+ if type(extra.get('exclude_bias_norm_from_weight_decay', False)) is not bool:
+ raise ValueError('Optimizer exclude_bias_norm_from_weight_decay must be a boolean')
betas = extra.get('betas', [.9, .999])
if (not isinstance(betas, (list, tuple)) or len(betas) != 2
or any(not isinstance(b, (int, float)) or not math.isfinite(b) or not 0 <= b < 1 for b in betas)):
@@ -39,15 +47,32 @@ def make_optimizer(model, settings):
parameters = [(name, p) for name, p in model.named_parameters() if p.requires_grad]
extra = settings.get('optimizer', {})
weight_decay = settings.get('weight_decay', .01)
+ exclude = extra.get('exclude_bias_norm_from_weight_decay', False) or 'bias_norm_scalar_weight_decay' in extra
+ bias_decay = extra.get('bias_norm_scalar_weight_decay', 0.)
+ # Include multidimensional normalization weights, even without "norm" in their path.
+ norm_parameters = {id(p) for module in model.modules() if 'norm' in type(module).__name__.lower()
+ for p in module.parameters(recurse=False)} if exclude else set()
groups = []
for adapter, name in ((False, 'new'), (True, 'adapter')):
selected = [(key, p) for key, p in parameters if key.endswith(('.lora_A', '.lora_B')) == adapter]
- values = [p for _, p in selected]
- if values:
- groups.append({'params': values, 'param_names': [key for key, _ in selected], 'name': name,
- 'lr': extra.get('adapter_learning_rate', settings['learning_rate']) if adapter else settings['learning_rate'],
- 'weight_decay': extra.get('adapter_weight_decay', weight_decay) if adapter else weight_decay})
- return torch.optim.AdamW(groups, betas=tuple(extra.get('betas', [.9, .999])), eps=extra.get('eps', 1e-8))
+ decay = extra.get('adapter_weight_decay', weight_decay) if adapter else weight_decay
+ partitions = [(name, selected, decay)]
+ if exclude and not adapter:
+ def no_decay(key, p):
+ return (p.ndim < 2 or p.numel() == 1 or key.lower() == 'bias'
+ or key.lower().endswith('.bias') or 'norm' in key.lower()
+ or id(p) in norm_parameters)
+ partitions = [('new', [(key, p) for key, p in selected if not no_decay(key, p)], decay),
+ ('new_no_decay' if bias_decay == 0 else 'new_bias_norm_scalar',
+ [(key, p) for key, p in selected if no_decay(key, p)], bias_decay)]
+ for group_name, members, group_decay in partitions:
+ if members:
+ groups.append({'params': [p for _, p in members], 'param_names': [key for key, _ in members],
+ 'name': group_name,
+ 'lr': extra.get('adapter_learning_rate', settings['learning_rate']) if adapter else settings['learning_rate'],
+ 'weight_decay': group_decay})
+ optimizer_class = {'AdamW': torch.optim.AdamW}[extra.get('name', 'AdamW')]
+ return optimizer_class(groups, betas=tuple(extra.get('betas', [.9, .999])), eps=extra.get('eps', 1e-8))
def set_learning_rates(optimizer, settings, update):
diff --git a/utils/training/settings.py b/utils/training/settings.py
new file mode 100644
index 0000000..bb56780
--- /dev/null
+++ b/utils/training/settings.py
@@ -0,0 +1,55 @@
+"""Resolve the shared optimization recipe and freeze its values in each run snapshot."""
+from copy import deepcopy
+import json
+
+from utils.hashing import sha256
+from utils.paths import REPO_ROOT
+from .ema import validate_ema_decay
+from .optim import validate_optimizer
+
+DEFAULT_OPTIMIZER_CONFIG = 'utils/training/configs/default.json'
+OPTIMIZATION_KEYS = {'learning_rate', 'weight_decay', 'warmup', 'optimizer', 'ema_decay', 'adapter_method'}
+
+
+def resolve_adapter_settings(model, training, *, method_key='adapter_method'):
+ """Replace explicit shared adapter selectors with the frozen recipe value."""
+ result = dict(model)
+ for key in (method_key, 'image_projection_adaptation'):
+ if result.get(key) == 'shared':
+ method = training.get('adapter_method')
+ if method not in ('lora', 'nora'):
+ raise ValueError('Shared model adapters require a recipe adapter_method of lora or nora')
+ result[key] = method
+ return result
+
+
+def resolve_training_settings(settings):
+ """Read one recipe reference. Already resolved snapshots retain their original values."""
+ if 'optimizer_config' not in settings:
+ return settings
+ if OPTIMIZATION_KEYS.intersection(settings) or 'optimizer_profile' in settings:
+ raise ValueError('Shared optimizer_config cannot have inline optimization settings')
+ if not isinstance(settings['optimizer_config'], str) or not settings['optimizer_config']:
+ raise ValueError('optimizer_config must name a shared settings file')
+ path = (REPO_ROOT / settings['optimizer_config']).resolve()
+ if not path.is_relative_to(REPO_ROOT / 'utils/training/configs'):
+ raise ValueError('Optimizer settings must reside under utils/training/configs')
+ recipe = json.loads(path.read_text())
+ required = {'schema', 'learning_rate', 'weight_decay', 'optimizer', 'ema_decay', 'adapter_method'}
+ if not isinstance(recipe, dict) or set(recipe) != required or recipe['schema'] != 'partprobe3d-optimization-v1':
+ raise ValueError('Expected partprobe3d-optimization-v1 settings')
+ if recipe['adapter_method'] not in ('lora', 'nora'):
+ raise ValueError('The shared recipe adapter_method must be lora or nora')
+ optimizer_keys = {'name', 'adapter_learning_rate', 'betas', 'adapter_weight_decay',
+ 'bias_norm_scalar_weight_decay', 'warmup_steps', 'eps'}
+ if not isinstance(recipe['optimizer'], dict) or not optimizer_keys.issubset(recipe['optimizer']):
+ raise ValueError('The shared recipe must specify every optimizer parameter')
+ result = deepcopy(settings)
+ del result['optimizer_config']
+ result.update({key: value for key, value in recipe.items() if key != 'schema'})
+ result['warmup'] = result['optimizer']['warmup_steps']
+ result['optimizer_profile'] = {'path': str(path.relative_to(REPO_ROOT)), 'sha256': sha256(path)}
+ validate_optimizer(result)
+ if result['ema_decay'] is not None:
+ validate_ema_decay(result['ema_decay'])
+ return result
diff --git a/utils/training/tests/test_cfg.py b/utils/training/tests/test_cfg.py
new file mode 100644
index 0000000..9662346
--- /dev/null
+++ b/utils/training/tests/test_cfg.py
@@ -0,0 +1,151 @@
+"""Check shared CFG controls, frozen snapshots, and actual sampling arguments."""
+from copy import deepcopy
+import json
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+from utils.training import cfg
+
+
+def stages():
+ from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG, load_config as ss, training_protocol as ss_protocol
+ from slat_multiobj_shape.config import load_config as shape, training_protocol as shape_protocol
+ from slat_segvigen.config import load_config as seg, training_protocol as seg_protocol
+ return [('ss', lambda path=None: ss(path or DEFAULT_TRAINING_CONFIG), ss_protocol),
+ ('slat_shape', shape, shape_protocol), ('slat_segmentation', seg, seg_protocol)]
+
+
+def profile(tmp_path, monkeypatch):
+ recipe = json.loads((cfg.REPO_ROOT / cfg.DEFAULT_CFG_CONFIG).read_text())
+ path = tmp_path / cfg.DEFAULT_CFG_CONFIG
+ path.parent.mkdir(parents=True)
+ path.write_text(json.dumps(recipe))
+ monkeypatch.setattr(cfg, 'REPO_ROOT', tmp_path)
+ return path, recipe
+
+
+def test_defaults_share_one_cfg_source_and_keep_stage_specific_guidance():
+ for stage, load, _ in stages():
+ settings = load()
+ expected = cfg.cfg_defaults(stage)
+ assert settings['training']['cfg_dropout'] == expected['cfg_dropout']
+ aliases = cfg.SS_GUIDANCE_KEYS if stage == 'ss' else {key: key for key in cfg.GUIDANCE_KEYS}
+ assert all(settings['sampling'][alias] == expected[key] for key, alias in aliases.items())
+ assert settings['cfg_profile']['path'] == cfg.DEFAULT_CFG_CONFIG
+ assert settings['cfg_profile']['stage'] == stage
+ assert 'cfg_config' not in settings
+
+
+def test_one_edit_changes_new_runs_and_saved_runs_need_no_profile_file(tmp_path, monkeypatch):
+ original = [load() for _, load, _ in stages()]
+ path, recipe = profile(tmp_path, monkeypatch)
+ recipe['ss'].update(cfg_dropout=.2, guidance_strength=3.25, guidance_rescale=.4, guidance_interval=[.2, .9])
+ recipe['slat_shape'].update(cfg_dropout=.3, guidance_strength=4.5, guidance_rescale=.2, guidance_interval=[.3, .8])
+ path.write_text(json.dumps(recipe))
+ for stage, load, _ in stages():
+ changed = load()
+ key = 'cfg_strength' if stage == 'ss' else 'guidance_strength'
+ assert changed['sampling'][key] == recipe[stage]['guidance_strength']
+ assert changed['training']['cfg_dropout'] == recipe[stage]['cfg_dropout']
+ assert changed['cfg_profile']['sha256'] != original[0]['cfg_profile']['sha256']
+ path.unlink()
+ for (stage, load, _), recorded in zip(stages(), original):
+ snapshot = tmp_path / f'{stage}.json'
+ snapshot.write_text(json.dumps(recorded))
+ assert load(snapshot) == recorded
+
+
+@pytest.mark.parametrize('change', [
+ {'training': {'cfg_dropout': .1}},
+ {'sampling': {'cfg_strength': 3.}},
+ {'sampling': {'guidance_rescale': .2}},
+])
+def test_shared_profile_rejects_inline_cfg_values(change):
+ with pytest.raises(ValueError, match='inline CFG'):
+ cfg.resolve_cfg_settings({'cfg_config': cfg.DEFAULT_CFG_CONFIG, **change}, 'ss')
+
+
+@pytest.mark.parametrize(('stage', 'key', 'value'), [
+ ('ss', 'cfg_dropout', 1.),
+ ('ss', 'guidance_strength', True),
+ ('slat_shape', 'guidance_rescale', float('nan')),
+ ('slat_shape', 'guidance_interval', [.8, .2]),
+ ('slat_segmentation', 'cfg_dropout', .1),
+ ('slat_segmentation', 'guidance_strength', 2.),
+])
+def test_invalid_profile_values_fail_before_training(tmp_path, monkeypatch, stage, key, value):
+ path, recipe = profile(tmp_path, monkeypatch)
+ recipe[stage][key] = value
+ path.write_text(json.dumps(recipe))
+ with pytest.raises(ValueError):
+ cfg.cfg_defaults(stage)
+
+
+def test_ss_inference_passes_shared_guidance_to_the_sampler(tmp_path, monkeypatch):
+ from ss_multiobj_depth.inference import SSInference
+ path, recipe = profile(tmp_path, monkeypatch)
+ recipe['ss'].update(guidance_strength=3.25, guidance_rescale=.4, guidance_interval=[.2, .9])
+ path.write_text(json.dumps(recipe))
+ calls = []
+
+ class Sampler:
+ def sample(self, flow, noise, **kwargs):
+ calls.append(kwargs)
+ return SimpleNamespace(samples=noise)
+
+ inference = SSInference.__new__(SSInference)
+ inference.config = stages()[0][1]()
+ inference.device = 'cpu'
+ inference.load = lambda: {'flow': SimpleNamespace(in_channels=2, resolution=2), 'sampler': Sampler(),
+ 'decoder': lambda _: torch.ones(1, 1, 2, 2, 2)}
+ inference.sample({'global': torch.ones(1, 2, 4), 'proj': torch.ones(1, 8, 4)}, seed=4)
+ assert calls[0]['guidance_strength'] == 3.25
+ assert calls[0]['guidance_rescale'] == .4
+ assert calls[0]['guidance_interval'] == [.2, .9]
+ assert all(not value.any() for value in calls[0]['neg_cond'].values())
+
+
+def test_shape_constructor_uses_shared_defaults_and_preserves_explicit_sampling(tmp_path, monkeypatch):
+ from slat_multiobj_shape.model import MultiObjectShape
+ from slat_multiobj_shape.tests.test_shape import tiny_native, normalization
+ path, recipe = profile(tmp_path, monkeypatch)
+ recipe['slat_shape'].update(guidance_strength=4.5, guidance_rescale=.2, guidance_interval=[.3, .8])
+ path.write_text(json.dumps(recipe))
+ model = MultiObjectShape(tiny_native(32), normalization(), resolution=32)
+ assert all(model.sampling[key] == recipe['slat_shape'][key] for key in cfg.GUIDANCE_KEYS)
+ path.unlink()
+ frozen = MultiObjectShape(tiny_native(32), normalization(), resolution=32, sampling=model.sampling)
+ assert frozen.sampling == model.sampling
+
+
+def test_training_protocols_ignore_inference_cfg_but_preserve_training_dropout(tmp_path):
+ (tmp_path / 'manifest.json').write_text('{}')
+
+ class Data:
+ root = tmp_path
+ target_scope = 'masked_objects_complete_occupancy'
+
+ def target_manifests(self):
+ return ['fixed-targets']
+
+ def checksums(self):
+ return {'view': 'fixed-latents'}
+
+ def cache_provenance(self):
+ return [{'policy': {'support_scope': self.target_scope}}] * 2
+
+ data = Data()
+ data.datasets = [data, data]
+ for stage, load, protocol in stages():
+ settings = load()
+ before = protocol(settings, data)
+ changed = deepcopy(settings)
+ key = 'cfg_interval' if stage == 'ss' else 'guidance_interval'
+ changed['sampling'][key] = [.2, .8]
+ changed['cfg_profile']['sha256'] = 'updated inference profile'
+ assert protocol(changed, data) == before
+ if stage != 'slat_segmentation':
+ changed['training']['cfg_dropout'] = .2
+ assert protocol(changed, data) != before
diff --git a/utils/training/tests/test_ema.py b/utils/training/tests/test_ema.py
new file mode 100644
index 0000000..28edb1f
--- /dev/null
+++ b/utils/training/tests/test_ema.py
@@ -0,0 +1,114 @@
+from copy import deepcopy
+
+import pytest
+import torch
+from torch import nn
+
+from utils.training.ema import TrainableEMA, load_ema_weights
+
+
+def model():
+ result = nn.ModuleDict({'frozen': nn.Linear(2, 2).requires_grad_(False), 'head': nn.Linear(2, 1)})
+ result.register_parameter('lambda_param', nn.Parameter(torch.ones(())))
+ return result
+
+
+def test_ema_averages_only_trainable_parameters_in_fp32_without_changing_model_or_rng():
+ net = model().to(dtype=torch.bfloat16)
+ random_state = torch.get_rng_state()
+ ema = TrainableEMA(net, .9995)
+ assert torch.equal(random_state, torch.get_rng_state())
+ assert set(ema.parameters) == {'lambda_param', 'head.weight', 'head.bias'}
+ assert all(p.dtype == torch.float32 and not p.requires_grad for p in ema.parameters.values())
+ before = {name: p.clone() for name, p in ema.parameters.items()}
+ with torch.no_grad():
+ for p in net.parameters():
+ p.add_(2.)
+ raw = deepcopy(net.state_dict())
+ ema.update(net)
+ assert ema.num_updates == 1
+ for name, p in ema.parameters.items():
+ expected = before[name] * .9995 + raw[name].float() * .0005
+ torch.testing.assert_close(p, expected)
+ assert p.data_ptr() != dict(net.named_parameters())[name].data_ptr()
+ for name, value in net.state_dict().items():
+ torch.testing.assert_close(value, raw[name], rtol=0, atol=0)
+ assert torch.equal(random_state, torch.get_rng_state())
+ load_ema_weights(net, ema.state_dict())
+ for name, p in net.named_parameters():
+ expected = ema.parameters[name].to(p.dtype) if p.requires_grad else raw[name]
+ torch.testing.assert_close(p, expected, rtol=0, atol=0)
+
+
+def test_ema_checkpoint_continues_exact_history_and_resets_only_selected_parameters(tmp_path):
+ net = model()
+ ema = TrainableEMA(net, .9995)
+ for _ in range(2):
+ with torch.no_grad():
+ net['head'].weight.add_(.2)
+ ema.update(net)
+ path = tmp_path / 'ema.pt'
+ torch.save(ema.state_dict(), path)
+ restored = TrainableEMA(net, .9995)
+ restored.load_state_dict(torch.load(path, weights_only=True))
+ assert restored.num_updates == ema.num_updates == 2
+ with torch.no_grad():
+ net['head'].bias.add_(.4)
+ net.lambda_param.fill_(.7)
+ ema.update(net)
+ restored.update(net)
+ for name in ema.parameters:
+ torch.testing.assert_close(ema.parameters[name], restored.parameters[name], rtol=0, atol=0)
+ before = deepcopy(restored.state_dict())
+ restored.reset_parameters(net, ['lambda_param'])
+ torch.testing.assert_close(restored.parameters['lambda_param'], net.lambda_param)
+ assert restored.num_updates == 3
+ for name in ('head.weight', 'head.bias'):
+ torch.testing.assert_close(restored.parameters[name], before['parameters'][name], rtol=0, atol=0)
+
+
+@pytest.mark.parametrize('decay', [True, '0.9995', -1., 1., float('nan'), float('inf')])
+def test_ema_rejects_invalid_decay(decay):
+ with pytest.raises(ValueError, match='EMA decay'):
+ TrainableEMA(model(), decay)
+
+
+@pytest.mark.parametrize('change,match', [
+ ({'decay': .99}, 'decay differs'), ({'num_updates': True}, 'update count'),
+ ({'parameters': {}}, 'parameters differ'), ({'extra': True}, 'Invalid EMA')])
+def test_ema_rejects_incompatible_checkpoint_state(change, match):
+ ema = TrainableEMA(model(), .9995)
+ state = ema.state_dict()
+ state.update(change)
+ with pytest.raises(ValueError, match=match):
+ ema.load_state_dict(state)
+
+
+def test_ema_rejects_changed_parameter_shapes_and_training_set():
+ net = model()
+ ema = TrainableEMA(net, .9995)
+ state = deepcopy(ema.state_dict())
+ state['parameters']['head.weight'] = torch.zeros(3)
+ with pytest.raises(ValueError, match='shape or dtype'):
+ load_ema_weights(net, state)
+ net['frozen'].requires_grad_(True)
+ with pytest.raises(ValueError, match='parameters changed'):
+ ema.update(net)
+
+
+def test_temporary_ema_evaluation_restores_raw_weights_even_on_failure():
+ net = model()
+ ema = TrainableEMA(net, .9995)
+ with torch.no_grad():
+ net['head'].weight.add_(1.)
+ ema.update(net)
+ raw = deepcopy(net.state_dict())
+ with pytest.raises(RuntimeError, match='evaluation failed'):
+ with ema.average_parameters(net):
+ for name, p in net.named_parameters():
+ if p.requires_grad:
+ torch.testing.assert_close(p, ema.parameters[name], rtol=0, atol=0)
+ raise RuntimeError('evaluation failed')
+ for name, value in net.state_dict().items():
+ torch.testing.assert_close(value, raw[name], rtol=0, atol=0)
+ assert ema.num_updates == 1
diff --git a/utils/training/tests/test_losses.py b/utils/training/tests/test_losses.py
index 43e0b24..1822dbc 100644
--- a/utils/training/tests/test_losses.py
+++ b/utils/training/tests/test_losses.py
@@ -1,5 +1,36 @@
+import pytest
import torch
-from utils.training.losses import asset_components, clean_from_velocity, membership_metrics, visible_membership_loss
+from utils.training.losses import (asset_components, clean_from_velocity, membership_metrics,
+ native_batch_mean, visible_membership_loss)
+
+
+@pytest.mark.parametrize('shapes', [
+ [(2, 32), (9, 32)],
+ [(8, 16, 16, 16), (8, 16, 16, 16)],
+ [(0, 32), (5, 32)],
+])
+def test_native_reduction_matches_concatenated_mse_and_gradients(shapes):
+ generator = torch.Generator().manual_seed(91)
+ predictions = [torch.randn(shape, generator=generator, requires_grad=True) for shape in shapes]
+ targets = [torch.randn(shape, generator=generator) for shape in shapes]
+ losses = [torch.nn.functional.mse_loss(prediction, target) if target.numel() else prediction.sum()
+ for prediction, target in zip(predictions, targets)]
+ actual = native_batch_mean(losses, [target.numel() for target in targets])
+ expected = torch.nn.functional.mse_loss(torch.cat([value.flatten() for value in predictions]),
+ torch.cat([value.flatten() for value in targets]))
+ torch.testing.assert_close(actual, expected)
+ actual_grads = torch.autograd.grad(actual, predictions, retain_graph=True)
+ expected_grads = torch.autograd.grad(expected, predictions)
+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):
+ torch.testing.assert_close(actual_grad, expected_grad)
+
+
+def test_empty_native_batch_retains_a_differentiable_zero():
+ parameter = torch.tensor(3., requires_grad=True)
+ loss = native_batch_mean([parameter * 0, parameter * 0], [0, 0])
+ assert loss.item() == 0
+ loss.backward()
+ assert parameter.grad.item() == 0
def test_scene_split_keeps_transitive_asset_overlap_together():
diff --git a/utils/training/tests/test_optim.py b/utils/training/tests/test_optim.py
index 2b289db..a561ca7 100644
--- a/utils/training/tests/test_optim.py
+++ b/utils/training/tests/test_optim.py
@@ -4,7 +4,7 @@ import pytest
import torch
from torch import nn
-from utils.training.optim import make_optimizer, set_learning_rates, validate_optimizer
+from utils.training.optim import make_optimizer, optimizer_record, set_learning_rates, validate_optimizer
from utils.training.lora import LoRALinear, NoRALinear
@@ -40,6 +40,8 @@ def test_adapter_groups_cover_each_trainable_parameter_and_exclude_frozen_weight
@pytest.mark.parametrize('change', [{'betas': [.9, 1.]}, {'betas': [.9]}, {'eps': 0.},
{'adapter_learning_rate': float('nan')}, {'warmup_steps': -1},
{'adapter_weight_decay': -.1}, {'unknown': True},
+ {'exclude_bias_norm_from_weight_decay': 1},
+ {'exclude_bias_norm_from_weight_decay': 'true'},
{'adapter_learning_rate_after_warmup': 0.},
{'adapter_learning_rate_after_warmup': float('nan')},
{'adapter_learning_rate_after_warmup': 1e-4, 'warmup_steps': 0}])
@@ -90,3 +92,77 @@ def test_default_groups_share_one_rate_for_depth_gate_and_adapters():
for update in (1, 122, 250, 251):
set_learning_rates(optimizer, value, update)
assert all(group['lr'] == pytest.approx(1e-4*min(update/250, 1.)) for group in optimizer.param_groups)
+
+
+def decay_model(wrapper=NoRALinear):
+ model = nn.ModuleDict({'flow': wrapper(nn.Linear(3, 4), rank=2, alpha=2),
+ 'head': nn.Linear(4, 2), 'affine': nn.LayerNorm((2, 2))})
+ model.register_parameter('scalar', nn.Parameter(torch.ones(())))
+ model.register_parameter('singleton', nn.Parameter(torch.ones(1, 1)))
+ model.register_parameter('lambda_param', nn.Parameter(torch.ones(4)))
+ return model
+
+
+@pytest.mark.parametrize('wrapper', [LoRALinear, NoRALinear])
+@pytest.mark.parametrize('adapter_decay', [0., .01])
+def test_decay_exclusions_apply_to_bias_norm_scalars_and_vectors_only(wrapper, adapter_decay):
+ model = decay_model(wrapper)
+ value = settings()
+ value['learning_rate'] = .1
+ value['optimizer'].update(exclude_bias_norm_from_weight_decay=True,
+ adapter_weight_decay=adapter_decay)
+ optimizer = make_optimizer(model, value)
+ groups = {g['name']: g for g in optimizer.param_groups}
+ assert set(groups) == {'new', 'new_no_decay', 'adapter'}
+ assert groups['new']['param_names'] == ['head.weight']
+ assert set(groups['new_no_decay']['param_names']) == {
+ 'scalar', 'singleton', 'lambda_param', 'head.bias', 'affine.weight', 'affine.bias'}
+ assert groups['adapter']['param_names'] == ['flow.lora_A', 'flow.lora_B']
+ assert [g['weight_decay'] for g in optimizer.param_groups] == [.01, 0., adapter_decay]
+ parameters = [p for group in optimizer.param_groups for p in group['params']]
+ assert len(parameters) == len({id(p) for p in parameters})
+ assert {id(p) for p in parameters} == {id(p) for p in model.parameters() if p.requires_grad}
+ assert all(g['betas'] == (.9, .95) for g in optimizer.param_groups)
+ # Zero gradients isolate AdamW's decoupled decay from gradient updates.
+ before = {name: p.detach().clone() for name, p in model.named_parameters()}
+ for p in parameters:
+ p.grad = torch.zeros_like(p)
+ optimizer.step()
+ for group in optimizer.param_groups:
+ for name, p in zip(group['param_names'], group['params']):
+ torch.testing.assert_close(p, before[name] * (1 - group['lr'] * group['weight_decay']))
+ torch.testing.assert_close(model['flow'].base.weight, before['flow.base.weight'])
+ for update in (1, 1000, 2000, 2001):
+ set_learning_rates(optimizer, value, update)
+ fraction = min(update / 2000, 1.)
+ assert groups['new']['lr'] == groups['new_no_decay']['lr'] == pytest.approx(.1 * fraction)
+ assert groups['adapter']['lr'] == pytest.approx(3e-5 * fraction)
+ record = optimizer_record(optimizer, value)
+ assert [group['weight_decay'] for group in record['groups']] == [.01, 0., adapter_decay]
+
+
+def test_decay_groups_resume_the_same_optimizer_updates(tmp_path):
+ value = settings()
+ value['optimizer']['exclude_bias_norm_from_weight_decay'] = True
+ model = decay_model()
+ optimizer = make_optimizer(model, value)
+ for p in model.parameters():
+ if p.requires_grad:
+ p.grad = torch.ones_like(p)
+ set_learning_rates(optimizer, value, 1)
+ optimizer.step()
+ path = tmp_path / 'optimizer.pt'
+ torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, path)
+ restored = decay_model()
+ other = make_optimizer(restored, value)
+ saved = torch.load(path, weights_only=True)
+ restored.load_state_dict(saved['model'])
+ other.load_state_dict(saved['optimizer'])
+ for candidate, optim in ((model, optimizer), (restored, other)):
+ for p in candidate.parameters():
+ if p.requires_grad:
+ p.grad = torch.full_like(p, .3)
+ set_learning_rates(optim, value, 2)
+ optim.step()
+ for p, resumed in zip(model.parameters(), restored.parameters()):
+ torch.testing.assert_close(resumed, p, rtol=0, atol=0)
diff --git a/utils/training/tests/test_settings.py b/utils/training/tests/test_settings.py
new file mode 100644
index 0000000..7c970f0
--- /dev/null
+++ b/utils/training/tests/test_settings.py
@@ -0,0 +1,139 @@
+from copy import deepcopy
+import json
+from pathlib import Path
+
+import pytest
+import torch
+
+from utils.paths import REPO_ROOT
+from utils.training import settings as shared
+from utils.training.lora import LoRALinear, NoRALinear
+from utils.training.optim import make_optimizer, set_learning_rates
+
+
+def loaders():
+ from ss_multiobj_depth.config import DEFAULT_TRAINING_CONFIG, load_config as ss
+ from slat_segvigen.config import load_config as seg
+ from slat_multiobj_shape.config import load_config as shape
+ return (lambda: ss(DEFAULT_TRAINING_CONFIG), seg, shape)
+
+
+def test_all_training_presets_reference_one_recipe_without_inline_optimization_values():
+ count = 0
+ for package in ('ss_multiobj_depth', 'slat_segvigen', 'slat_multiobj_shape'):
+ for path in (REPO_ROOT / package / 'configs').glob('*.json'):
+ config = json.loads(path.read_text())
+ if 'training' not in config:
+ continue
+ training = config['training']
+ assert training['optimizer_config'] == shared.DEFAULT_OPTIMIZER_CONFIG, path
+ assert not shared.OPTIMIZATION_KEYS.intersection(training), path
+ count += 1
+ assert count >= 3
+
+
+def test_all_three_defaults_use_the_same_actual_optimizer_groups_and_warmup():
+ records = [load()['training'] for load in loaders()]
+ assert [record['cfg_dropout'] for record in records] == [.1, 0., .1]
+ for key in shared.OPTIMIZATION_KEYS | {'optimizer_profile'}:
+ assert all(record[key] == records[0][key] for record in records)
+ for training in records:
+ assert training['ema_decay'] == .999
+ assert training['warmup'] == 500
+ model = torch.nn.ModuleDict({'flow': NoRALinear(torch.nn.Linear(3, 4), rank=2, alpha=2),
+ 'head': torch.nn.Linear(4, 2), 'norm': torch.nn.LayerNorm(2)})
+ optimizer = make_optimizer(model, training)
+ assert type(optimizer) is torch.optim.AdamW
+ groups = {group['name']: group for group in optimizer.param_groups}
+ assert set(groups) == {'new', 'new_no_decay', 'adapter'}
+ assert groups['new']['weight_decay'] == groups['adapter']['weight_decay'] == .01
+ assert groups['new_no_decay']['weight_decay'] == 0.
+ assert all(group['betas'] == (.9, .95) for group in groups.values())
+ assert all(group['lr'] == 1e-4 for group in groups.values())
+ for update in (1, 250, 500, 501):
+ set_learning_rates(optimizer, training, update)
+ assert all(group['lr'] == pytest.approx(1e-4 * min(update / 500, 1.)) for group in groups.values())
+
+
+def test_one_recipe_edit_updates_every_stage_but_saved_snapshots_retain_resolved_values(tmp_path, monkeypatch):
+ from ss_multiobj_depth.config import load_config as ss
+ before = [load() for load in loaders()]
+ snapshot = tmp_path / 'snapshot.json'
+ snapshot.write_text(json.dumps(before[0]))
+ path = tmp_path / shared.DEFAULT_OPTIMIZER_CONFIG
+ path.parent.mkdir(parents=True)
+ recipe = json.loads((REPO_ROOT / shared.DEFAULT_OPTIMIZER_CONFIG).read_text())
+ recipe.update(learning_rate=2e-4, ema_decay=.99, adapter_method='nora')
+ recipe['optimizer'].update(warmup_steps=37, adapter_learning_rate=8e-5)
+ path.write_text(json.dumps(recipe))
+ monkeypatch.setattr(shared, 'REPO_ROOT', tmp_path)
+ for load in loaders():
+ selected = load()
+ resolved = selected['training']
+ assert selected['model'].get('adapter_method', selected['model'].get('mode')) == 'nora'
+ assert selected['model']['image_projection_adaptation'] == 'nora'
+ assert resolved['adapter_method'] == 'nora'
+ assert resolved['learning_rate'] == 2e-4
+ assert resolved['ema_decay'] == .99
+ assert resolved['warmup'] == resolved['optimizer']['warmup_steps'] == 37
+ assert resolved['optimizer']['adapter_learning_rate'] == 8e-5
+ assert resolved['optimizer_profile']['sha256'] != before[0]['training']['optimizer_profile']['sha256']
+ assert 'optimizer_config' not in resolved
+ path.unlink()
+ assert ss(snapshot)['training'] == before[0]['training']
+ assert ss(snapshot)['model'] == before[0]['model']
+
+
+@pytest.mark.parametrize('inline', ['learning_rate', 'weight_decay', 'warmup', 'optimizer', 'ema_decay', 'adapter_method'])
+def test_shared_reference_rejects_inline_control_points(inline):
+ with pytest.raises(ValueError, match='inline optimization'):
+ shared.resolve_training_settings({'optimizer_config': shared.DEFAULT_OPTIMIZER_CONFIG, inline: 1})
+
+
+def test_historical_inline_settings_remain_literal():
+ settings = {'learning_rate': 3e-5, 'warmup': 2, 'optimizer': {'betas': [.9, .999]}}
+ assert shared.resolve_training_settings(deepcopy(settings)) == settings
+
+
+def test_shared_recipe_cannot_escape_its_owned_directory():
+ with pytest.raises(ValueError, match='under utils/training/configs'):
+ shared.resolve_training_settings({'optimizer_config': '/tmp/outside.json'})
+
+
+@pytest.mark.parametrize('method', ['lora', 'nora'])
+def test_one_recipe_constructs_the_selected_backbone_and_image_adapters_in_every_stage(tmp_path, monkeypatch, method):
+ from ss_multiobj_depth.model import install_adapters
+ from ss_multiobj_depth.tests.test_conditioning_training import native_flow
+ from slat_multiobj_shape.model import MultiObjectShape
+ from slat_multiobj_shape.tests.test_shape import tiny_native, normalization
+ from slat_segvigen import config as segmentation
+
+ path = tmp_path / shared.DEFAULT_OPTIMIZER_CONFIG
+ path.parent.mkdir(parents=True)
+ recipe = json.loads((REPO_ROOT / shared.DEFAULT_OPTIMIZER_CONFIG).read_text())
+ recipe['adapter_method'] = method
+ path.write_text(json.dumps(recipe))
+ monkeypatch.setattr(shared, 'REPO_ROOT', tmp_path)
+ ss, seg, shape = [load() for load in loaders()]
+ dense = install_adapters(native_flow(), **ss['model'])
+
+ def shape_flow():
+ flow = tiny_native(32)
+ flow.proj_in_channels = 2048
+ for block in flow.blocks:
+ block.cross_attn.proj_linear = torch.nn.Linear(2048, 24)
+ return flow
+
+ sparse = MultiObjectShape(shape_flow(), normalization(), resolution=32, adaptation=shape['model'])
+ monkeypatch.setattr('models.pixal3d.load_frozen', lambda *_: shape_flow())
+ monkeypatch.setattr(segmentation, 'configure_runtime', lambda _: None)
+ seg['device'] = 'cpu'
+ segmenter = segmentation.make_model(seg)
+ expected = LoRALinear if method == 'lora' else NoRALinear
+ for model in (dense, sparse, segmenter):
+ backbone = [module for name, module in model.named_modules() if name.endswith('.to_qkv')]
+ image = [module for name, module in model.named_modules() if name.endswith('.proj_linear')]
+ assert backbone and image
+ assert all(type(module) is expected for module in backbone + image)
+ assert all(not module.weight.requires_grad and not module.lora_B.any() for module in backbone + image)
+ assert all(module.bias.requires_grad for module in image)
diff --git a/utils/training/tests/test_stage_ema.py b/utils/training/tests/test_stage_ema.py
new file mode 100644
index 0000000..59b02d7
--- /dev/null
+++ b/utils/training/tests/test_stage_ema.py
@@ -0,0 +1,68 @@
+from pathlib import Path
+
+import pytest
+import torch
+from torch import nn
+
+from utils.training.ema import TrainableEMA
+from utils.training.lora import NoRALinear
+from utils.training.optim import make_optimizer
+from utils.training.settings import DEFAULT_OPTIMIZER_CONFIG, resolve_training_settings
+
+
+def network(stage):
+ flow = nn.ModuleDict({'adapter': NoRALinear(nn.Linear(3, 4), rank=2, alpha=2), 'head': nn.Linear(4, 2)})
+ model = nn.ModuleDict({'flow': flow, 'conditioner': nn.Linear(1, 2)})
+ model.checkpoint_schema = 'ema-stage-test-v1'
+ return model
+
+
+@pytest.mark.parametrize('stage', ['ss', 'seg'])
+def test_stage_checkpoints_preserve_raw_and_ema_weights_and_select_ema_at_inference(tmp_path, monkeypatch, stage):
+ if stage == 'ss':
+ from ss_multiobj_depth import train as owner
+ def save(path, model, optimizer, **kwargs):
+ return owner.save_checkpoint(path, model['flow'], model['conditioner'], optimizer, **kwargs)
+ def restore(path, model, **kwargs):
+ return owner.restore_checkpoint(path, model['flow'], model['conditioner'], **kwargs)
+ else:
+ from slat_segvigen import shared_checkpoint as owner
+ monkeypatch.setattr(owner, 'path_under', lambda path, _: Path(path))
+ save, restore = owner.save_checkpoint, owner.restore_checkpoint
+ model = network(stage)
+ settings = resolve_training_settings({'optimizer_config': DEFAULT_OPTIMIZER_CONFIG, 'stage': 'flow'})
+ config = {'device': 'cpu', 'training': settings}
+ optimizer = make_optimizer(model, settings)
+ ema = TrainableEMA(model, settings['ema_decay'])
+ for p in model.parameters():
+ if p.requires_grad:
+ p.grad = torch.ones_like(p)
+ optimizer.step()
+ ema.update(model)
+ path = tmp_path / f'{stage}.pt'
+ save(path, model, optimizer, step=1, config=config, protocol={}, provenance={}, ema=ema)
+ raw = {name: p.detach().clone() for name, p in model.named_parameters() if p.requires_grad}
+ assert any(not torch.equal(value, ema.parameters[name]) for name, value in raw.items())
+ for selection in ('auto', 'ema', 'raw'):
+ other = network(stage)
+ restored = restore(path, other, weights=selection)
+ assert restored['checkpoint_weights'] == ('raw' if selection == 'raw' else 'ema')
+ for name, p in other.named_parameters():
+ if p.requires_grad:
+ expected = raw[name] if selection == 'raw' else ema.parameters[name]
+ torch.testing.assert_close(p, expected, rtol=0, atol=0)
+ other = network(stage)
+ other_ema = TrainableEMA(other, ema.decay)
+ restored = restore(path, other, optimizer=make_optimizer(other, settings), ema=other_ema)
+ assert restored['checkpoint_weights'] == 'raw'
+ assert other_ema.num_updates == 1
+ for name, p in other.named_parameters():
+ if p.requires_grad:
+ torch.testing.assert_close(p, raw[name], rtol=0, atol=0)
+ torch.testing.assert_close(other_ema.parameters[name], ema.parameters[name], rtol=0, atol=0)
+ historical = tmp_path / f'{stage}_historical.pt'
+ save(historical, model, optimizer, step=1, config={'device': 'cpu', 'training': {'stage': 'flow'}},
+ protocol={}, provenance={})
+ assert restore(historical, other, weights='auto')['checkpoint_weights'] == 'raw'
+ with pytest.raises(ValueError, match='no EMA state'):
+ restore(historical, other, weights='ema')
|