File size: 118,168 Bytes
7073aad | 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 | diff --git a/configs/dataloader/mmb.yaml b/configs/dataloader/mmb.yaml
new file mode 100644
index 0000000..e495c06
--- /dev/null
+++ b/configs/dataloader/mmb.yaml
@@ -0,0 +1,23 @@
+type: mmb
+
+# MobileManipBench (prlq/mobilemanipbench-data @356ec43), merged to one LeRobot v2.1
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_canon.yaml b/configs/dataloader/mmb_canon.yaml
new file mode 100644
index 0000000..baa6507
--- /dev/null
+++ b/configs/dataloader/mmb_canon.yaml
@@ -0,0 +1,23 @@
+type: mmb_canon
+
+# MobileManipBench, canonical action protocol v2 (openwam/dataloader/mmb_canon.py): chunk-start base-frame EEF delta.
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_final.yaml b/configs/dataloader/mmb_final.yaml
new file mode 100644
index 0000000..c33301b
--- /dev/null
+++ b/configs/dataloader/mmb_final.yaml
@@ -0,0 +1,23 @@
+type: mmb_final
+
+# MobileManipBench, final canonical definition (openwam/dataloader/mmb_final.py; shared convert_merge.py output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_hf
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_v4.yaml b/configs/dataloader/mmb_v4.yaml
new file mode 100644
index 0000000..2a743c6
--- /dev/null
+++ b/configs/dataloader/mmb_v4.yaml
@@ -0,0 +1,23 @@
+type: mmb_v4
+
+# MobileManipBench, final definition 11-14 (openwam/dataloader/mmb_v4.py; shared convert_merge.py @ 8d0b031 output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_v4
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max; stats from the shared file (pooled base + EEF xyz, rot6d / gripper identity)
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/openwam/dataloader/mmb.py b/openwam/dataloader/mmb.py
new file mode 100644
index 0000000..2ca8398
--- /dev/null
+++ b/openwam/dataloader/mmb.py
@@ -0,0 +1,433 @@
+"""MobileManipBench (``prlq/mobilemanipbench-data``) reader for OpenWAM-alpha fine-tuning.
+
+Input: one merged LeRobot v2.1 dataset per robot (``<dataset_dir>/<robot>/``,
+per-episode parquet + mp4, 25 fps, cameras ``observation.images.head`` /
+``observation.images.wrist``). Three single-arm mobile manipulators:
+
+ * ``go2_arm`` action 12-D: ``base_action_0..3`` + ``eef0`` xyz + quat(wxyz) + gripper
+ * ``sawyer_umi`` action 11-D: base ``x, y, yaw`` + ``frame0`` xyz + quat(wxyz) + gripper
+ * ``stretch3`` action 11-D: base ``x, y, yaw`` + ``arm_action_0..6`` (xyz + quat(wxyz)) + gripper
+
+The arm action is an absolute end-effector pose target in the same world frame
+as ``observation.eef_pose`` (xyz + quat wxyz), which is the proprio source.
+The base action is a velocity command; there is no measured base velocity, so
+the proprio base slots are masked. The gripper command is ``0 = open,
+1 = closed`` and becomes the alpha convention ``+1 = open, -1 = closed``. The
+state finger joints use different conventions per robot, so the proprio
+gripper slot is masked.
+
+Raw vector (both streams): ``[xyz3, rot6d6, gripper1, base...]`` scattered to
+the alpha 80-D layout as single-arm slots ``0:10`` (as LIBERO / DROID) and the
+mobile-base slots ``68`` forward, ``69`` lateral, ``70`` yaw (as AgiBotWorld),
+``71`` go2's fourth base command. Base dims that are constant over a robot's
+data (stretch3 lateral) are masked.
+
+Normalization is per robot, min-max, with separate action and proprio stats
+fitted on the whole dataset; rot6d and gripper stats are pinned to ``[-1, 1]``
+(identity), as the alpha contract requires. Stats are built once by
+``build_mmb_stats`` (``meta/mmb_normalization_stats.npy`` per robot).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_normalization_stats.npy"
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def raw_action(action: np.ndarray, layout: dict) -> np.ndarray:
+ """``(T, A)`` native action -> ``(T, 10 + n_base)`` raw ``[xyz, rot6d, gripper(+1 open), base]``."""
+ a = np.asarray(action, dtype=np.float32)
+ pose = a[:, layout["pose"]]
+ grip = 1.0 - 2.0 * a[:, layout["gripper"] : layout["gripper"] + 1]
+ return np.concatenate([pose[:, :3], _quat_wxyz_to_rot6d(pose[:, 3:7]), grip, a[:, layout["base"]]], axis=-1)
+
+
+def raw_proprio(eef_pose: np.ndarray, n_base: int) -> np.ndarray:
+ """``(T, 7)`` measured EEF pose -> raw vector; gripper and base are zero (masked)."""
+ e = np.asarray(eef_pose, dtype=np.float32)
+ out = np.zeros((e.shape[0], ARM_DIM + n_base), dtype=np.float32)
+ out[:, :3] = e[:, :3]
+ out[:, ROT6D] = _quat_wxyz_to_rot6d(e[:, 3:7])
+ return out
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def build_mmb_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every episode of one robot and write ``meta/mmb_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ layout = robot_layout(info)
+ paths = sorted(robot_dir.glob("data/chunk-*/episode_*.parquet"))
+ with ProcessPoolExecutor(workers) as ex:
+ parts = list(ex.map(_scan_episode, [(str(p), layout) for p in paths], chunksize=8))
+ act = np.concatenate([p[0] for p in parts])
+ st = np.concatenate([p[1] for p in parts])
+ n_base = len(layout["base"])
+ action_stats = _min_max_stats(act)
+ proprio_stats = _min_max_stats(st)
+ rng = action_stats["max"] - action_stats["min"]
+ action_valid = np.ones(ARM_DIM + n_base, dtype=bool)
+ action_valid[ARM_DIM:] = rng[ARM_DIM:] > CONST_EPS
+ proprio_valid = np.zeros(ARM_DIM + n_base, dtype=bool)
+ proprio_valid[:GRIPPER] = True # xyz + rot6d; gripper and base masked
+ payload = {
+ "robot": robot_dir.name,
+ "action_names": info["features"]["action"]["names"],
+ "layout": layout,
+ "eef": action_stats,
+ "eef_state": proprio_stats,
+ "action_valid": action_valid,
+ "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(n_base),
+ "num_timesteps": int(act.shape[0]),
+ "gripper_convention": "minus1_closed_plus1_open (native 0=open,1=closed -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def _scan_episode(args):
+ path, layout = args
+ df = pq.read_table(path, columns=["action", "observation.eef_pose"]).to_pandas()
+ a = raw_action(np.stack(df["action"].to_numpy()), layout)
+ s = raw_proprio(np.stack(df["observation.eef_pose"].to_numpy()), len(layout["base"]))
+ return a, s
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples."""
+
+ DATASET_NAME = "MMB"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+ self._layout = robot_layout(info)
+ self._n_base = len(self._layout["base"])
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats["layout"] != self._layout:
+ raise MMBDataError(f"{self._robot}: stats layout {self._stats['layout']} != data {self._layout}")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(self._n_base), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("action", "observation.eef_pose"))
+ frame = table.slice(offset, n_raw).to_pandas()
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(n_raw, T)
+ raw_a = raw_action(np.stack(frame["action"].to_numpy()[:n_valid]), self._layout)
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = raw_proprio(np.stack(frame["observation.eef_pose"].to_numpy()[:1]), self._n_base)
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBDataset", "MMBRobotDataset", "build_mmb_stats", "raw_action", "raw_proprio"]
diff --git a/openwam/dataloader/mmb_canon.py b/openwam/dataloader/mmb_canon.py
new file mode 100644
index 0000000..2762a23
--- /dev/null
+++ b/openwam/dataloader/mmb_canon.py
@@ -0,0 +1,479 @@
+"""MobileManipBench reader for OpenWAM-alpha with the canonical action protocol v2.
+
+Same data, cameras, windows and alpha 80-D contract as ``mmb.py``; only the action / proprio definition differs:
+
+ canonical 12D (shared numpy module ``mmb_canonical_action``, identical to the pi0.5 / GR00T pipelines):
+ [vx, vy, wz, height | dp (3) | dq xyzw (4) | gripper]
+ dp = R_B(t)^T (p_target(t+k) - p_E(t)), dq = conj(q_E(t)) * q_target(t+k), relative to the window start t
+ (the OpenWAM action chunk = rows t .. t+31 of the window); base commands and gripper as recorded,
+ placeholders 0 (sawyer height, stretch vy and height).
+ alpha slots: dp -> 0:3, rot6d(dq) -> 3:9, gripper (1 - 2g: +1 open, -1 closed) -> 9,
+ base [vx, vy, wz, height] -> 68, 69, 70, 71 (unsupported dims masked per robot).
+ proprio: the window-start EEF pose in the base frame, p = R_B^T (p_E - p_B), R = R_B^T R_E (rot6d) -> 0:9;
+ gripper and base proprio masked (no world-frame quantity is fed to the model).
+ base pose: full measured pose from sim_info/0/sim_states.npz (meta/sim_base_pose/episode_XXXXXX.npy,
+ aligned with parquet sim_step_idx - 1, validated against observation.eef_pose / state).
+
+Normalization: per robot, min-max over every valid chunk element of every window, rot6d and gripper pinned to
+[-1, 1] (``build_mmb_canon_stats`` -> meta/mmb_canon_normalization_stats.npy).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_canon_normalization_stats.npy"
+BASE_POSE_DIR = "sim_base_pose"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def canon_raw_action(robot: str, action_rows: np.ndarray, base_t: np.ndarray, eef_t: np.ndarray) -> np.ndarray:
+ """Recorded action rows of one window + window-start poses -> (n, 14) alpha raw
+ ``[dp(3), rot6d(dq)(6), gripper(+1 open), vx, vy, wz, height]``."""
+ c = ca.encode_chunk(robot, np.asarray(action_rows, np.float64), base_t, eef_t)
+ rot6d = quat_xyzw_to_rot6d(c[:, 7:11]).astype(np.float64)
+ return np.concatenate([c[:, 4:7], rot6d, 1.0 - 2.0 * c[:, 11:12], c[:, 0:4]], -1).astype(np.float32)
+
+
+def canon_raw_proprio(base_t: np.ndarray, eef_t: np.ndarray) -> np.ndarray:
+ """Window-start EEF pose in the base frame -> (1, 14) raw ``[p(3), rot6d(6), 0 ...]``."""
+ base_t, eef_t = np.asarray(base_t, np.float64), np.asarray(eef_t, np.float64)
+ R_b = ca.qrotmat(base_t[3:7])
+ p = R_b.T @ (eef_t[:3] - base_t[:3])
+ q = ca.qmul(ca.qconj(ca.qnorm(base_t[3:7])), ca.qnorm(eef_t[3:7]))
+ out = np.zeros((1, ARM_DIM + 4), np.float32)
+ out[0, :3] = p
+ out[0, ROT6D] = quat_xyzw_to_rot6d(ca.wxyz_to_xyzw(q)[None])[0]
+ return out
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+class _RunningMinMax:
+ def __init__(self):
+ self.lo = self.hi = None
+ self.sum = self.sq = 0.0
+ self.n = 0
+
+ def add(self, x: np.ndarray):
+ x = np.asarray(x, np.float64).reshape(-1, x.shape[-1])
+ lo, hi = x.min(0), x.max(0)
+ self.lo = lo if self.lo is None else np.minimum(self.lo, lo)
+ self.hi = hi if self.hi is None else np.maximum(self.hi, hi)
+ self.sum = self.sum + x.sum(0)
+ self.sq = self.sq + (x * x).sum(0)
+ self.n += x.shape[0]
+
+ def merge(self, o: "_RunningMinMax"):
+ if o.n == 0:
+ return
+ self.lo = o.lo if self.lo is None else np.minimum(self.lo, o.lo)
+ self.hi = o.hi if self.hi is None else np.maximum(self.hi, o.hi)
+ self.sum, self.sq, self.n = self.sum + o.sum, self.sq + o.sq, self.n + o.n
+
+ def stats(self) -> dict:
+ mean = self.sum / self.n
+ st = {"min": self.lo.copy(), "max": self.hi.copy(), "mean": mean,
+ "std": np.sqrt(np.maximum(self.sq / self.n - mean * mean, 0.0))}
+ st["q01"], st["q99"] = st["min"].copy(), st["max"].copy() # min-max mode only
+ for k, v in st.items(): # rot6d + gripper: identity under min-max
+ v[ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ v[GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _scan_episode(args):
+ robot, data_path, base_path = args
+ df = pq.read_table(data_path, columns=["action", "observation.eef_pose"]).to_pandas()
+ A = np.stack(df["action"].to_numpy()).astype(np.float64)
+ E = np.stack(df["observation.eef_pose"].to_numpy()).astype(np.float64)
+ B = np.load(base_path).astype(np.float64)
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ T = len(A)
+ for t in range(max(T - 1, 1)): # every window start (train windows need >= 2 rows)
+ rows = A[t:min(t + CHUNK, T)]
+ act.add(canon_raw_action(robot, rows, B[t], E[t]))
+ prop.add(canon_raw_proprio(B[t], E[t]))
+ return act, prop
+
+
+def build_mmb_canon_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every window of one robot and write ``meta/mmb_canon_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ eps = _read_jsonl(robot_dir / "meta" / "episodes.jsonl")
+ excl_path = robot_dir / "meta" / "excluded_episodes.json"
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ eps = [e for e in eps if int(e["episode_index"]) not in excluded]
+ cs = int(info.get("chunks_size", 1000))
+ jobs = [(robot, str(robot_dir / info["data_path"].format(episode_chunk=e["episode_index"] // cs,
+ episode_index=e["episode_index"])),
+ str(robot_dir / "meta" / BASE_POSE_DIR / f"episode_{e['episode_index']:06d}.npy")) for e in eps]
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ with ProcessPoolExecutor(workers) as ex:
+ for a, p in ex.map(_scan_episode, jobs, chunksize=4):
+ act.merge(a)
+ prop.merge(p)
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.VALID_MASK[robot][:4]
+ proprio_valid = np.zeros(ARM_DIM + 4, dtype=bool)
+ proprio_valid[:GRIPPER] = True # base-frame EEF xyz + rot6d
+ payload = {
+ "robot": robot,
+ "protocol": "canonical_action_v2",
+ "action_names": ["dp_x", "dp_y", "dp_z"] + [f"dq_rot6d_{i}" for i in range(6)] +
+ ["gripper_open_scale", "vx", "vy", "wz", "height"],
+ "eef": act.stats(),
+ "eef_state": prop.stats(),
+ "action_valid": action_valid,
+ "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4),
+ "num_timesteps": int(act.n),
+ "gripper_convention": "minus1_closed_plus1_open (native 0=open,1=closed -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBCanonRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (canonical action protocol v2)."""
+
+ DATASET_NAME = "MMB-canon"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+ self._layout = robot_layout(info)
+ self._n_base = len(self._layout["base"])
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_canon_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_action_v2" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not canonical_action_v2 stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("action", "observation.eef_pose"))
+ frame = table.slice(offset, n_raw).to_pandas()
+ base_t = np.load(self._dir / "meta" / BASE_POSE_DIR / f"episode_{ep_idx:06d}.npy", mmap_mode="r")[offset]
+ eef_t = np.asarray(frame["observation.eef_pose"].iloc[0], np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(n_raw, T)
+ raw_a = canon_raw_action(self._robot, np.stack(frame["action"].to_numpy()[:n_valid]), base_t, eef_t)
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = canon_raw_proprio(base_t, eef_t)
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBCanonDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBCanonRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBCanonDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBCanonRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_canon_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBCanonDataset", "MMBCanonRobotDataset", "build_mmb_canon_stats", "canon_raw_action", "canon_raw_proprio"]
diff --git a/openwam/dataloader/mmb_canonical_action.py b/openwam/dataloader/mmb_canonical_action.py
new file mode 100644
index 0000000..16bb3e1
--- /dev/null
+++ b/openwam/dataloader/mmb_canonical_action.py
@@ -0,0 +1,467 @@
+"""MobileManipBench canonical state and action chunks (v3, yiqi 11-13/14) - framework-agnostic, numpy only, shared
+by pi0.5, GR00T N1.7 and OpenWAM. The dataset (convert_merge.py --v2, patch_frame.py) stores per frame the canonical
+state (observation.state_canonical), the expert's EEF target seen from the body (action.eef_target) and the recorded
+commands (action.command); the data loader only builds chunks (action_chunk_from_targets) and normalises.
+
+Body frame (BODY_FRAME = "ground", same reference on all robots): origin = the measured base position projected to the
+floor (x_B, y_B, 0), z up, x = base heading (yaw only; Go2 gait roll / pitch and height are not part of the frame).
+Raw recordings (world frame, quaternions w-x-y-z): observation.eef_pose = measured EEF pose; base pose = measured, from
+sim_info/0/sim_states.npz (base_pose_from_sim_states: npz row sim_step_idx - 1; constant asset-frame offsets removed,
+e.g. Sawyer N051/N053/N058/N059 Ry(-90 deg)).
+
+STATE, 14D (canonical_state): [vx, vy, wz, height | x, y, z | r6 (6) | gripper]
+ vx, vy, wz = measured base velocity in the body frame from this and the previous frame (0 at frame 0);
+ height = measured Go2 base height; x, y, z = EEF position in the body frame (z = height above the floor);
+ r6 = rot6d of the EEF orientation in the body frame = first two COLUMNS [R[:,0], R[:,1]] (Zhou et al.);
+ gripper = measured finger closure 0 (open) .. 1 (closed), continuous.
+ Placeholders: Sawyer height; Stretch vy, height are exactly 0.
+
+ACTION chunk, 14D per step k = 0 .. H-1 (action_chunk_from_targets, ref "base", rot "rot6d"):
+ [vx, vy, wz, height | x, y, z | r6 (6) | gripper]
+ base part = recorded base command at t+k; gripper = recorded gripper command at t+k (0 open / 1 close);
+ x, y, z, r6 = the expert's (planner's) sparse EEF target at t+k seen from the body frame at t+k: where the EEF has
+ to be relative to the body (quasi-static, decoupled from base motion); nothing is subtracted.
+ Steps past the episode end repeat the last frame (LeRobot padding).
+Execution (decode_action_chunk): EEF target pose = (x, y, z, R(r6) orthonormalised), placed in the world with the body
+frame of the base pose measured when the step is executed, solved by the low-level IK; base command = the base part;
+gripper command = gripper > 0.5.
+Legacy layouts (older checkpoints only): rot="rpy" (11D, relative to the current EEF, roll/pitch/yaw), ref="eef"
+(relative to the current EEF), frame="base" (measured base pose as the body frame), future measured states as the EEF
+source (action_chunk_from_states).
+"""
+import numpy as np
+
+ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+RAW_DIM = {"go2_arm": 12, "sawyer_umi": 11, "stretch3": 11}
+STATE_DIM, ACTION_DIM = 14, 14
+S_POS, S_ROT, S_GRIP = slice(4, 7), slice(7, 13), 13
+A_POS, A_ROT, A_GRIP = slice(4, 7), slice(7, 13), 13 # rot = "rot6d" (default)
+ACTION_DIM_RPY, A_ROT_RPY, A_GRIP_RPY = 11, slice(7, 10), 10 # rot = "rpy" (legacy: pi05_v2, GR00T v2 / v3)
+ROT_REPRS = ("rot6d", "rpy")
+EEF_REFS = ("base", "eef") # EEF action: pose in the body frame ("base") or relative to the current EEF ("eef")
+DEFAULT_EEF_REF = "base"
+# body frame the EEF is seen from: "base" = measured base pose (Go2: torso, 0.31-0.42 m above the floor, with gait
+# roll/pitch; Sawyer / Stretch: 0.06 m); "ground" = the base projected to the floor: origin (x_B, y_B, 0), z up, base
+# heading (yaw) only - the same reference on all robots
+BODY_FRAMES = ("base", "ground")
+BODY_FRAME = "ground" # yiqi 11-14: unified frame # rot6d default (yiqi 11-13: "相对于当前底盘,我的末端要走到什么位置去?什么角度去?")
+GRIPPER_CLOSE_THRESHOLD = 0.5 # execution: closure > 0.5 -> close command (1)
+_BASE_MASK = {"go2_arm": [1, 1, 1, 1], "sawyer_umi": [1, 1, 1, 0], "stretch3": [1, 0, 1, 0]}
+STATE_MASK = {r: np.array(m + [1] * (STATE_DIM - 4), bool) for r, m in _BASE_MASK.items()}
+ACTION_MASK = {r: np.array(m + [1] * (ACTION_DIM - 4), bool) for r, m in _BASE_MASK.items()}
+ACTION_MASK_RPY = {r: np.array(m + [1] * (ACTION_DIM_RPY - 4), bool) for r, m in _BASE_MASK.items()}
+ROT6D_LAYOUT = "cols" # first two COLUMNS [R[:,0], R[:,1]] (Zhou et al.; OpenWAM). "rows" = pytorch3d / GR00T N1.7 pose.py
+# observation.state slots of the base (x, y, yaw, z); verified against the measured base pose (all tasks):
+STATE_BASE_SLOTS = {"go2_arm": (20, 21, 22, 23), "sawyer_umi": (0, 1, 2, None), "stretch3": (0, 1, 2, None)}
+# finger joints in observation.state and their fully-open magnitude (closed = 0 on all robots; verified per task)
+GRIPPER_JOINTS = {"go2_arm": ((24, 25), 0.035), "sawyer_umi": ((11, 12), 0.021), "stretch3": ((13, 14), 0.25)}
+IDENTITY_R6 = np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0])
+
+
+# ---------------------------------------------------------------- quaternion helpers (w-x-y-z unless noted)
+def qnorm(q):
+ q = np.asarray(q, np.float64)
+ return q / np.linalg.norm(q, axis=-1, keepdims=True)
+
+
+def qconj(q):
+ return q * np.array([1.0, -1.0, -1.0, -1.0])
+
+
+def qmul(a, b):
+ aw, ax, ay, az = np.moveaxis(a, -1, 0)
+ bw, bx, by, bz = np.moveaxis(b, -1, 0)
+ return np.stack([aw * bw - ax * bx - ay * by - az * bz,
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw], -1)
+
+
+def qrotmat(q):
+ w, x, y, z = np.moveaxis(qnorm(q), -1, 0)
+ return np.stack([
+ np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], -1),
+ np.stack([2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], -1),
+ np.stack([2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)], -1)], -2)
+
+
+def wxyz_to_xyzw(q):
+ return np.concatenate([q[..., 1:], q[..., :1]], -1)
+
+
+def xyzw_to_wxyz(q):
+ return np.concatenate([q[..., 3:], q[..., :3]], -1)
+
+
+def geodesic_deg(qa, qb):
+ d = np.abs(np.sum(qnorm(qa) * qnorm(qb), -1)).clip(0, 1)
+ return np.degrees(2 * np.arccos(d))
+
+
+def rotmat_to_quat(R):
+ """Rotation matrices [..., 3, 3] -> unit quaternions w-x-y-z (w >= 0); Shepperd's method (numerically stable,
+ also for near-identity and near-180-degree rotations)."""
+ R = np.asarray(R, np.float64)
+ m00, m11, m22 = R[..., 0, 0], R[..., 1, 1], R[..., 2, 2]
+ tr = m00 + m11 + m22
+ cand = []
+ w = np.sqrt(np.maximum(1 + tr, 1e-300)) / 2 # case w largest
+ cand.append(np.stack([w, (R[..., 2, 1] - R[..., 1, 2]) / (4 * w), (R[..., 0, 2] - R[..., 2, 0]) / (4 * w), (R[..., 1, 0] - R[..., 0, 1]) / (4 * w)], -1))
+ x = np.sqrt(np.maximum(1 + m00 - m11 - m22, 1e-300)) / 2 # case x largest
+ cand.append(np.stack([(R[..., 2, 1] - R[..., 1, 2]) / (4 * x), x, (R[..., 0, 1] + R[..., 1, 0]) / (4 * x), (R[..., 0, 2] + R[..., 2, 0]) / (4 * x)], -1))
+ y = np.sqrt(np.maximum(1 - m00 + m11 - m22, 1e-300)) / 2 # case y largest
+ cand.append(np.stack([(R[..., 0, 2] - R[..., 2, 0]) / (4 * y), (R[..., 0, 1] + R[..., 1, 0]) / (4 * y), y, (R[..., 1, 2] + R[..., 2, 1]) / (4 * y)], -1))
+ z = np.sqrt(np.maximum(1 - m00 - m11 + m22, 1e-300)) / 2 # case z largest
+ cand.append(np.stack([(R[..., 1, 0] - R[..., 0, 1]) / (4 * z), (R[..., 0, 2] + R[..., 2, 0]) / (4 * z), (R[..., 1, 2] + R[..., 2, 1]) / (4 * z), z], -1))
+ pick = np.argmax(np.stack([tr, m00, m11, m22], -1), -1)[..., None, None]
+ q = np.take_along_axis(np.stack(cand, -2), pick, -2)[..., 0, :]
+ q = np.where(q[..., :1] < 0, -q, q)
+ return qnorm(q)
+
+
+def rotmat_to_rot6d(R):
+ """[..., 3, 3] -> [..., 6]: the first two rows (ROT6D_LAYOUT = "rows") or columns ("cols") of R."""
+ R = np.asarray(R, np.float64)
+ if ROT6D_LAYOUT == "rows":
+ return R[..., :2, :].reshape(R.shape[:-2] + (6,))
+ return np.concatenate([R[..., :, 0], R[..., :, 1]], -1)
+
+
+def rot6d_to_rotmat(r6):
+ """[..., 6] -> [..., 3, 3] by Gram-Schmidt (also valid for non-orthonormal network outputs)."""
+ r6 = np.asarray(r6, np.float64)
+ a1, a2 = r6[..., :3], r6[..., 3:6]
+ b1 = a1 / np.linalg.norm(a1, axis=-1, keepdims=True)
+ b2 = a2 - np.sum(b1 * a2, -1, keepdims=True) * b1
+ b2 = b2 / np.linalg.norm(b2, axis=-1, keepdims=True)
+ b3 = np.cross(b1, b2)
+ return np.stack([b1, b2, b3], -2) if ROT6D_LAYOUT == "rows" else np.stack([b1, b2, b3], -1)
+
+
+def rotmat_to_rotvec(R):
+ """[..., 3, 3] -> rotation vectors [..., 3] (axis * angle, angle in [0, pi])."""
+ q = rotmat_to_quat(R)
+ s = np.linalg.norm(q[..., 1:], axis=-1, keepdims=True)
+ ang = 2 * np.arctan2(s, q[..., :1])
+ return np.where(s > 1e-12, q[..., 1:] / np.maximum(s, 1e-12) * ang, 2 * q[..., 1:])
+
+
+def rotvec_to_rotmat(v):
+ v = np.asarray(v, np.float64)
+ ang = np.linalg.norm(v, axis=-1, keepdims=True)
+ axis = v / np.maximum(ang, 1e-12)
+ q = np.concatenate([np.cos(ang / 2), axis * np.sin(ang / 2)], -1)
+ return qrotmat(q)
+
+
+
+
+def rotmat_to_rpy(R):
+ """[..., 3, 3] -> [..., 3] = (roll, pitch, yaw), R = Rz(yaw) Ry(pitch) Rx(roll) (ROS / URDF convention)."""
+ R = np.asarray(R, np.float64)
+ pitch = np.arcsin(np.clip(-R[..., 2, 0], -1.0, 1.0))
+ return np.stack([np.arctan2(R[..., 2, 1], R[..., 2, 2]), pitch, np.arctan2(R[..., 1, 0], R[..., 0, 0])], -1)
+
+
+def rpy_to_rotmat(rpy):
+ r, p, y = np.moveaxis(np.asarray(rpy, np.float64), -1, 0)
+ cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
+ return np.stack([np.stack([cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], -1),
+ np.stack([sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], -1),
+ np.stack([-sp, cp * sr, cp * cr], -1)], -2)
+
+
+def rot_angle_deg(R):
+ """Rotation angle of rotation matrices [..., 3, 3] in degrees."""
+ return np.degrees(np.arccos(np.clip((np.trace(R, axis1=-2, axis2=-1) - 1) / 2, -1, 1)))
+
+
+def yaw_quat(yaw):
+ yaw = np.asarray(yaw, np.float64)
+ z = np.zeros_like(yaw)
+ return np.stack([np.cos(yaw / 2), z, z, np.sin(yaw / 2)], -1)
+
+
+def base_heading_pose(robot, state):
+ """observation.state [..., D] -> base heading pose [..., 7] = [x, y, z, qw, 0, 0, qz] (world frame)."""
+ state = np.asarray(state, np.float64)
+ ix, iy, iyaw, iz = STATE_BASE_SLOTS[robot]
+ z = state[..., iz] if iz is not None else np.zeros(state.shape[:-1])
+ return np.concatenate([np.stack([state[..., ix], state[..., iy], z], -1), yaw_quat(state[..., iyaw])], -1)
+
+
+def _axis_aligned_quats():
+ """The 24 rotations that map coordinate axes onto coordinate axes (w-x-y-z, w >= 0)."""
+ out = []
+ for perm in ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)):
+ for signs in np.ndindex(2, 2, 2):
+ M = np.zeros((3, 3))
+ for r, (c, sg) in enumerate(zip(perm, signs)):
+ M[r, c] = -1.0 if sg else 1.0
+ if np.linalg.det(M) < 0:
+ continue
+ w = np.sqrt(max(0.0, 1 + np.trace(M))) / 2
+ if w > 1e-6:
+ q = np.array([w, (M[2, 1] - M[1, 2]) / (4 * w), (M[0, 2] - M[2, 0]) / (4 * w), (M[1, 0] - M[0, 1]) / (4 * w)])
+ else: # 180 deg rotations
+ axis = np.sqrt(np.clip((np.diag(M) + 1) / 2, 0, 1))
+ i = int(np.argmax(axis))
+ for j in range(3):
+ if j != i and M[i, j] + M[j, i] < 0:
+ axis[j] = -axis[j]
+ q = np.r_[0.0, axis]
+ out.append(q)
+ return np.array(out)
+
+
+AXIS_ALIGNED_QUATS = _axis_aligned_quats()
+
+
+def base_pose_from_sim_states(sim_states, sim_step_idx, robot, state, return_offset=False):
+ """Full world base pose [T, 7] = [x, y, z, qw, qx, qy, qz] for parquet frames with the given sim_step_idx [T].
+ sim_states: path to sim_info/0/sim_states.npz or the loaded npz mapping (keys robot__<Name>__base_pos/base_quat,
+ 50 Hz control steps; parquet keeps every 2nd step). Frame s <- npz row with sim_step_idx == s - 1.
+ A constant asset-frame offset in base_quat (e.g. Ry(-90 deg) for Sawyer in N051/N053/N058/N059) is removed: the
+ mean of heading(state)^-1 * base_quat is snapped to the nearest axis-aligned rotation c and base_quat * c^-1 is
+ returned, so the body frame is x forward / z up everywhere (Go2 keeps its real roll / pitch)."""
+ z = np.load(sim_states) if isinstance(sim_states, (str, bytes)) or hasattr(sim_states, "__fspath__") else sim_states
+ key = [k for k in z.files if k.startswith("robot__") and k.endswith("__base_pos")]
+ assert len(key) == 1, key
+ key = key[0][: -len("__base_pos")]
+ row = {int(v): i for i, v in enumerate(np.asarray(z["sim_step_idx"]))}
+ idx = np.array([row.get(int(s) - 1, -1) for s in np.asarray(sim_step_idx).reshape(-1)])
+ assert (idx >= 0).all(), f"{(idx < 0).sum()} frames have no sim state at sim_step_idx - 1"
+ q = qnorm(np.asarray(z[key + "__base_quat"], np.float64)[idx])
+ off = qmul(qconj(qnorm(base_heading_pose(robot, state)[..., 3:7])), q) # [T, 4]
+ c = AXIS_ALIGNED_QUATS[int(np.argmax(np.abs(off @ AXIS_ALIGNED_QUATS.T).sum(0)))]
+ q = qnorm(qmul(q, qconj(c)[None]))
+ q = np.where(q[:, :1] < 0, -q, q)
+ pose = np.concatenate([np.asarray(z[key + "__base_pos"], np.float64)[idx], q], -1)
+ return (pose, c) if return_offset else pose
+
+
+def sim_states_alignment_error(sim_states, sim_step_idx, eef_pose):
+ """Consistency check of the npz <-> parquet alignment: max |npz EEF - observation.eef_pose| as (position m,
+ rotation deg) over the episode. Both are ~0 (float32 precision) when the npz belongs to the same recording."""
+ z = np.load(sim_states) if isinstance(sim_states, (str, bytes)) or hasattr(sim_states, "__fspath__") else sim_states
+ key = [k for k in z.files if k.startswith("robot__") and k.endswith("__eef_pos")][0][: -len("__eef_pos")]
+ row = {int(v): i for i, v in enumerate(np.asarray(z["sim_step_idx"]))}
+ idx = np.array([row[int(s) - 1] for s in np.asarray(sim_step_idx).reshape(-1)])
+ eef_pose = np.asarray(eef_pose, np.float64)
+ pos = np.abs(np.asarray(z[key + "__eef_pos"], np.float64)[idx] - eef_pose[:, :3]).max()
+ rot = geodesic_deg(np.asarray(z[key + "__eef_quat"], np.float64)[idx], eef_pose[:, 3:7]).max()
+ return float(pos), float(rot)
+
+
+
+
+# ---------------------------------------------------------------- raw <-> parts
+def split_raw(robot, raw):
+ raw = np.asarray(raw, np.float64)
+ assert raw.shape[-1] == RAW_DIM[robot], (robot, raw.shape)
+ if robot == "go2_arm":
+ base = raw[..., 0:4]
+ eef = raw[..., 4:11]
+ else:
+ base = np.concatenate([raw[..., 0:3], np.zeros(raw.shape[:-1] + (1,))], -1)
+ eef = raw[..., 3:10]
+ if robot == "stretch3":
+ base = base.copy(); base[..., 1] = 0.0 # differential drive: vy is never executable
+ return base, eef[..., :3], eef[..., 3:7], raw[..., -1:]
+
+
+def join_raw(robot, base, pos, quat_wxyz, grip):
+ if robot == "go2_arm":
+ return np.concatenate([base, pos, quat_wxyz, grip], -1)
+ b = base[..., :3].copy()
+ if robot == "stretch3":
+ b[..., 1] = 0.0
+ return np.concatenate([b, pos, quat_wxyz, grip], -1)
+
+
+# ---------------------------------------------------------------- canonical state / actions
+def body_frame(base_poses, frame=None):
+ """Measured base poses [..., 7] -> pose of the body frame the EEF is seen from [..., 7] (BODY_FRAME by default)."""
+ B = np.asarray(base_poses, np.float64)
+ frame = frame or BODY_FRAME
+ if frame == "base":
+ return np.concatenate([B[..., :3], qnorm(B[..., 3:7])], -1)
+ if frame != "ground":
+ raise ValueError(f"frame must be one of {BODY_FRAMES}, got {frame!r}")
+ R = qrotmat(B[..., 3:7])
+ yaw = np.arctan2(R[..., 1, 0], R[..., 0, 0]) # heading of the base x-axis in the horizontal plane
+ return np.concatenate([B[..., :2], np.zeros(B.shape[:-1] + (1,)), yaw_quat(yaw)], -1)
+
+
+def canonical_state(robot, base_poses, eef_poses, state, timestamps, frame=None):
+ """Per-frame canonical state [T, 14] of one episode (see module docstring); EEF and base velocity are expressed in
+ body_frame(base_poses, frame); height = measured base height."""
+ B0, E = np.asarray(base_poses, np.float64), np.asarray(eef_poses, np.float64)
+ B = body_frame(B0, frame)
+ S, ts = np.asarray(state, np.float64), np.asarray(timestamps, np.float64).reshape(-1)
+ T = len(B)
+ qb = qnorm(B[:, 3:7]); R = qrotmat(qb)
+ out = np.zeros((T, STATE_DIM))
+ if T > 1:
+ dt = np.diff(ts)[:, None]
+ v = np.einsum("ti,tij->tj", (B[1:, :3] - B[:-1, :3]) / dt, R[1:]) # world velocity -> current base frame
+ dq = qmul(qconj(qb[:-1]), qb[1:]); dq = np.where(dq[:, :1] < 0, -dq, dq) # base rotation over the step
+ ang = 2 * np.arctan2(np.linalg.norm(dq[:, 1:], axis=1), dq[:, 0])
+ axis = dq[:, 1:] / np.maximum(np.linalg.norm(dq[:, 1:], axis=1, keepdims=True), 1e-12)
+ out[1:, 0:2] = v[:, :2]
+ out[1:, 2] = (axis[:, 2] * ang) / dt[:, 0]
+ out[:, 3] = B0[:, 2]
+ out[:, S_POS] = np.einsum("ti,tij->tj", E[:, :3] - B[:, :3], R) # R_B^T (p_E - p_B)
+ out[:, S_ROT] = rotmat_to_rot6d(np.einsum("tji,tjk->tik", R, qrotmat(E[:, 3:7]))) # R_B^T R_E
+ idx, open_mag = GRIPPER_JOINTS[robot]
+ out[:, S_GRIP] = np.clip(1 - np.abs(S[:, list(idx)]).mean(1) / open_mag, 0, 1)
+ out[:, ~STATE_MASK[robot]] = 0.0
+ return out
+
+
+def command_columns(robot, raw_actions):
+ """Recorded commands per frame [T, 5] = [vx, vy, wz, height, gripper] (dataset column action.command;
+ placeholders 0: Sawyer height, Stretch vy and height)."""
+ base, _, _, grip = split_raw(robot, raw_actions)
+ out = np.concatenate([base, grip], -1)
+ out[:, :4][:, ~ACTION_MASK[robot][:4]] = 0.0
+ return out
+
+
+def action_layout(rot="rot6d"):
+ """(action dim, rotation slice, gripper index, per-robot mask) of an action chunk with rotation representation rot."""
+ if rot == "rot6d":
+ return ACTION_DIM, A_ROT, A_GRIP, ACTION_MASK
+ if rot == "rpy":
+ return ACTION_DIM_RPY, A_ROT_RPY, A_GRIP_RPY, ACTION_MASK_RPY
+ raise ValueError(f"rot must be one of {ROT_REPRS}, got {rot!r}")
+
+
+def rot_from_action_dim(dim):
+ return {ACTION_DIM: "rot6d", ACTION_DIM_RPY: "rpy"}[dim]
+
+
+def relative_rotation(R_s, R_x, rot="rot6d"):
+ """R_s^T R_x (rotation of x relative to the current EEF, in the current EEF frame) as rot6d (cols) or roll/pitch/yaw.
+ Always a relative rotation - never a difference of absolute angles."""
+ R = np.einsum("...ji,...jk->...ik", R_s, R_x)
+ return rotmat_to_rot6d(R) if rot == "rot6d" else rotmat_to_rpy(R)
+
+
+def relative_rotation_matrix(a_rot, rot="rot6d"):
+ """Inverse of relative_rotation: rot6d (Gram-Schmidt, tolerates non-orthonormal model outputs) or rpy -> R."""
+ return rot6d_to_rotmat(a_rot) if rot == "rot6d" else rpy_to_rotmat(a_rot)
+
+
+def _eef_ref(rot, ref):
+ ref = ref or ("eef" if rot == "rpy" else DEFAULT_EEF_REF)
+ if ref not in EEF_REFS or (rot == "rpy" and ref != "eef"):
+ raise ValueError(f"unsupported EEF reference {ref!r} for rot {rot!r}")
+ return ref
+
+
+def eef_action(state_t, pos, R, rot="rot6d", ref=None):
+ """EEF part of the action steps from body-frame EEF poses (pos [..., H, 3], R [..., H, 3, 3]):
+ ref "base" (default, rot6d only): [pos | rot6d(R)] - where the EEF has to be, seen from the body;
+ ref "eef" (legacy): [pos - state(t).xyz | relative_rotation(R(state(t).r6), R)] - relative to the current EEF."""
+ ref = _eef_ref(rot, ref)
+ if ref == "base":
+ return np.concatenate([pos, rotmat_to_rot6d(R)], -1)
+ s = np.asarray(state_t, np.float64)
+ R_s = rot6d_to_rotmat(s[..., None, S_ROT])
+ return np.concatenate([pos - s[..., None, S_POS], relative_rotation(R_s, R, rot)], -1)
+
+
+def eef_pose_from_action(state_t, a_pos, a_rot, rot="rot6d", ref=None):
+ """Inverse of eef_action -> body-frame EEF pose (pos [..., H, 3], R [..., H, 3, 3]); rot6d outputs are
+ orthonormalised (Gram-Schmidt), so non-orthonormal model outputs give proper rotations."""
+ ref = _eef_ref(rot, ref)
+ if ref == "base":
+ return np.asarray(a_pos, np.float64), rot6d_to_rotmat(a_rot)
+ s = np.asarray(state_t, np.float64)
+ return s[..., None, S_POS] + a_pos, rot6d_to_rotmat(s[..., None, S_ROT]) @ relative_rotation_matrix(a_rot, rot)
+
+
+def action_chunk_from_states(robot, state_t, future_states, commands, rot="rot6d", ref=None):
+ """Action chunk from the future measured states: state(t) [..., 14], state(t+1 .. t+H) [..., H, 14] and the
+ recorded commands at t .. t+H-1 [..., H, 5] -> [..., H, 14] (rot6d) / [..., H, 11] (legacy rpy)."""
+ f, c = np.asarray(future_states, np.float64), np.asarray(commands, np.float64)
+ out = np.concatenate([c[..., 0:4], eef_action(state_t, f[..., S_POS], rot6d_to_rotmat(f[..., S_ROT]), rot, ref),
+ c[..., 4:5]], -1)
+ out[..., ~action_layout(rot)[3][robot]] = 0.0
+ return out
+
+
+def expert_target_columns(robot, raw_actions, base_poses, frame=None):
+ """Per-frame expert EEF target seen from the body at the same frame [T, 9] = [x, y, z | rot6d] (dataset column
+ action.eef_target): R_B(t)^T (p_target(t) - p_B(t)) and rot6d(R_B(t)^T R_target(t))."""
+ _, p_tgt, q_tgt, _ = split_raw(robot, raw_actions)
+ B = body_frame(base_poses, frame)
+ R = qrotmat(B[..., 3:7])
+ pos = np.einsum("...i,...ij->...j", p_tgt - B[..., :3], R)
+ rot = rotmat_to_rot6d(np.einsum("...ji,...jk->...ik", R, qrotmat(q_tgt)))
+ return np.concatenate([pos, rot], -1)
+
+
+def action_chunk_from_targets(robot, state_t, targets, commands, rot="rot6d", ref=None):
+ """Action chunk from the expert targets at t .. t+H-1 [..., H, 9] (body frame of their own frame) and the recorded
+ commands at t .. t+H-1 [..., H, 5] -> [..., H, 14]: [base cmd | target xyz | target rot6d | gripper cmd] (ref
+ "base", default; state(t) is not used). Legacy: ref "eef" (relative to state(t)), rot "rpy" (11D)."""
+ g, c = np.asarray(targets, np.float64), np.asarray(commands, np.float64)
+ out = np.concatenate([c[..., 0:4], eef_action(state_t, g[..., 0:3], rot6d_to_rotmat(g[..., 3:9]), rot, ref),
+ c[..., 4:5]], -1)
+ out[..., ~action_layout(rot)[3][robot]] = 0.0
+ return out
+
+
+def episode_target_chunks(robot, canon_states, targets, commands, horizon, rot="rot6d", ref=None):
+ """All training chunks of one episode [T, H, A] from expert targets and commands at t .. t+H-1 (clamped)."""
+ S, G, Cm = (np.asarray(x, np.float64) for x in (canon_states, targets, commands))
+ T = len(S)
+ idx = np.minimum(np.arange(T)[:, None] + np.arange(horizon)[None, :], T - 1)
+ return action_chunk_from_targets(robot, S, G[idx], Cm[idx], rot, ref)
+
+
+def future_states_from_chunk(robot, state_t, action_chunk, rot=None, ref=None):
+ """Inverse of action_chunk_from_states / _from_targets for the EEF: -> predicted EEF part of the state [..., H, 14]
+ (base / gripper slots carry the commands). rot defaults to the one implied by the action dim (14 rot6d, 11 rpy),
+ ref to DEFAULT_EEF_REF for rot6d ("eef" for rpy)."""
+ a = np.asarray(action_chunk, np.float64).copy()
+ rot = rot or rot_from_action_dim(a.shape[-1])
+ _, a_rot, a_grip, mask = action_layout(rot)
+ a[..., ~mask[robot]] = 0.0
+ pos, R = eef_pose_from_action(state_t, a[..., A_POS], a[..., a_rot], rot, ref)
+ out = np.zeros(a.shape[:-1] + (STATE_DIM,))
+ out[..., 0:4] = a[..., 0:4]
+ out[..., S_POS] = pos
+ out[..., S_ROT] = rotmat_to_rot6d(R)
+ out[..., S_GRIP] = a[..., a_grip] # the gripper command (not a measured closure)
+ return out
+
+
+def decode_action_chunk(robot, action_chunk, state_t, base_poses_now, rot=None, ref=None, frame=None):
+ """Model output [H, 14] (legacy rpy [H, 11]) + current canonical state [14] (used only by the legacy ref "eef") +
+ body pose measured when each step is executed [H, 7] -> controller commands in the recorded format [H, D_robot]:
+ base velocity command, world EEF target (wxyz) and gripper command (closure > GRIPPER_CLOSE_THRESHOLD).
+ Unsupported dimensions are never emitted."""
+ a = np.asarray(action_chunk, np.float64)
+ rot = rot or rot_from_action_dim(a.shape[-1])
+ f = future_states_from_chunk(robot, state_t, a, rot, ref)
+ B = body_frame(base_poses_now, frame) # measured base pose -> body frame
+ R_b = qrotmat(B[..., 3:7])
+ p = B[..., :3] + np.einsum("...ij,...j->...i", R_b, f[..., S_POS])
+ q = rotmat_to_quat(R_b @ rot6d_to_rotmat(f[..., S_ROT]))
+ a_grip = action_layout(rot)[2]
+ grip = (a[..., a_grip:a_grip + 1] > GRIPPER_CLOSE_THRESHOLD).astype(np.float64)
+ return join_raw(robot, f[..., 0:4], p, q, grip)
+
+
+def episode_action_chunks(robot, canon_states, commands, horizon, rot="rot6d", ref=None):
+ """All training chunks of one episode [T, H, A] from its canonical states (future steps t+1 .. t+H) and the
+ recorded commands [T, 5] (steps t .. t+H-1); indices are clamped to the last frame like LeRobot."""
+ S = np.asarray(canon_states, np.float64)
+ Cm = np.asarray(commands, np.float64)
+ T = len(S)
+ k = np.arange(horizon)[None, :]
+ return action_chunk_from_states(robot, S, S[np.minimum(np.arange(T)[:, None] + k + 1, T - 1)],
+ Cm[np.minimum(np.arange(T)[:, None] + k, T - 1)], rot, ref)
diff --git a/openwam/dataloader/mmb_final.py b/openwam/dataloader/mmb_final.py
new file mode 100644
index 0000000..0ffa596
--- /dev/null
+++ b/openwam/dataloader/mmb_final.py
@@ -0,0 +1,456 @@
+"""MobileManipBench reader for OpenWAM-alpha, final canonical definition (yiqi 11-13).
+
+Dataset: the shared ``convert_merge.py --v2 --robots <robot>`` output (one LeRobot v2.1 dataset per robot) with
+``observation.state_canonical`` (14D) and ``action.command`` (5D). All math is the shared ``mmb_canonical_action``
+(identical to the pi0.5 / GR00T pipelines):
+
+ state [vx, vy, wz, h | x, y, z | rot6d (cols) | gripper closure] -> proprio of the window start t
+ action ``action_chunk_from_states(state(t), state(t+1..t+32), command(t..t+31))`` =
+ [base cmd (4) | dxyz | droll, dpitch, dyaw | gripper cmd 0/1]
+
+alpha 80-D slots (fixed contract): EEF xyz -> 0:3, rotation as rot6d -> 3:9 (the action's roll/pitch/yaw delta is
+converted to its rotation matrix and then rot6d; the state's rot6d is used as is), gripper -> 9 as +1 open / -1 closed
+(1 - 2x), base [vx, vy, wz, h] -> 68..71; unsupported base dims (Sawyer h, Stretch vy and h) are masked. Steps past
+the episode end (state index >= T) are masked. Normalization: per robot min-max (alpha contract), rot6d and gripper
+pinned to [-1, 1] (``build_mmb_final_stats`` -> meta/mmb_final_normalization_stats.npy).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_final_normalization_stats.npy"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def final_raw_action(robot: str, state_t, future_states, commands) -> np.ndarray:
+ """(n,) steps -> (n, 14) alpha raw [dxyz, rot6d(drpy), gripper(+1 open), vx, vy, wz, h]."""
+ a = ca.action_chunk_from_states(robot, state_t, future_states, commands)
+ r6 = ca.rotmat_to_rot6d(ca.rpy_to_rotmat(a[:, 7:10]))
+ return np.concatenate([a[:, 4:7], r6, 1.0 - 2.0 * a[:, 10:11], a[:, 0:4]], -1).astype(np.float32)
+
+
+def final_raw_proprio(state_t) -> np.ndarray:
+ """(14,) canonical state -> (1, 14) alpha raw [xyz, rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ s = np.asarray(state_t, np.float64)
+ return np.concatenate([s[4:7], s[7:13], [1.0 - 2.0 * s[13]], s[0:4]])[None].astype(np.float32)
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+class _RunningMinMax:
+ def __init__(self):
+ self.lo = self.hi = None
+ self.sum = self.sq = 0.0
+ self.n = 0
+
+ def add(self, x: np.ndarray):
+ x = np.asarray(x, np.float64).reshape(-1, x.shape[-1])
+ lo, hi = x.min(0), x.max(0)
+ self.lo = lo if self.lo is None else np.minimum(self.lo, lo)
+ self.hi = hi if self.hi is None else np.maximum(self.hi, hi)
+ self.sum = self.sum + x.sum(0)
+ self.sq = self.sq + (x * x).sum(0)
+ self.n += x.shape[0]
+
+ def merge(self, o: "_RunningMinMax"):
+ if o.n == 0:
+ return
+ self.lo = o.lo if self.lo is None else np.minimum(self.lo, o.lo)
+ self.hi = o.hi if self.hi is None else np.maximum(self.hi, o.hi)
+ self.sum, self.sq, self.n = self.sum + o.sum, self.sq + o.sq, self.n + o.n
+
+ def stats(self) -> dict:
+ mean = self.sum / self.n
+ st = {"min": self.lo.copy(), "max": self.hi.copy(), "mean": mean,
+ "std": np.sqrt(np.maximum(self.sq / self.n - mean * mean, 0.0))}
+ st["q01"], st["q99"] = st["min"].copy(), st["max"].copy() # min-max mode only
+ for k, v in st.items(): # rot6d + gripper: identity under min-max
+ v[ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ v[GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _scan_episode(args):
+ robot, data_path = args
+ t = pq.read_table(data_path, columns=["observation.state_canonical", "action.command"])
+ S = np.asarray(t["observation.state_canonical"].to_pylist(), np.float64)
+ C = np.asarray(t["action.command"].to_pylist(), np.float64)
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ T = len(S)
+ for s0 in range(max(T - 1, 1)): # every train window start (needs >= 1 future state)
+ n = min(CHUNK, T - 1 - s0)
+ act.add(final_raw_action(robot, S[s0], S[s0 + 1:s0 + 1 + n], C[s0:s0 + n]))
+ prop.add(final_raw_proprio(S[s0]))
+ return act, prop
+
+
+def build_mmb_final_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every window of one robot and write ``meta/mmb_final_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ eps = _read_jsonl(robot_dir / "meta" / "episodes.jsonl")
+ cs = int(info.get("chunks_size", 1000))
+ jobs = [(robot, str(robot_dir / info["data_path"].format(episode_chunk=e["episode_index"] // cs,
+ episode_index=e["episode_index"]))) for e in eps]
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ with ProcessPoolExecutor(workers) as ex:
+ for a_, p_ in ex.map(_scan_episode, jobs, chunksize=4):
+ act.merge(a_)
+ prop.merge(p_)
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.ACTION_MASK[robot][:4]
+ proprio_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ proprio_valid[ARM_DIM:] = ca.STATE_MASK[robot][:4]
+ payload = {
+ "robot": robot, "protocol": "canonical_final_11_13",
+ "eef": act.stats(), "eef_state": prop.stats(),
+ "action_valid": action_valid, "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4), "num_timesteps": int(act.n),
+ "gripper_convention": "alpha: +1 open / -1 closed (canonical 0/1 command and closure -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBFinalRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (canonical action protocol v2)."""
+
+ DATASET_NAME = "MMB-final"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_final_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_final_11_13" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not the final canonical stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2 # >= 1 future state
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("observation.state_canonical", "action.command"))
+ n_rows = min(ep_len - offset, self._num_frames)
+ frame = table.slice(offset, n_rows).to_pandas()
+ S = np.stack(frame["observation.state_canonical"].to_numpy()).astype(np.float64)
+ Cm = np.stack(frame["action.command"].to_numpy()).astype(np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(T, n_rows - 1) # step k needs state(t+k) inside the episode
+ raw_a = final_raw_action(self._robot, S[0], S[1:1 + n_valid], Cm[:n_valid])
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = final_raw_proprio(S[0])
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBFinalDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBFinalRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBFinalDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBFinalRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_final_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBFinalDataset", "MMBFinalRobotDataset", "build_mmb_final_stats", "final_raw_action", "final_raw_proprio"]
diff --git a/openwam/dataloader/mmb_v4.py b/openwam/dataloader/mmb_v4.py
new file mode 100644
index 0000000..3999436
--- /dev/null
+++ b/openwam/dataloader/mmb_v4.py
@@ -0,0 +1,405 @@
+"""MobileManipBench reader for OpenWAM-alpha, final definition (yiqi 11-14; shared canonical_action.py @ 8d0b031).
+
+Dataset: the shared ``convert_merge.py --v2 --robots <robot>`` output (one LeRobot v2.1 dataset per robot, unified
+ground frame) with ``observation.state_canonical`` (14D), ``action.command`` (5D) and ``action.eef_target`` (9D).
+All math is the shared ``mmb_canonical_action`` (identical to the pi0.5 / GR00T pipelines):
+
+ state [vx, vy, wz, h | x, y, z | rot6d (cols) | gripper closure] -> proprio of the window start t
+ action ``action_chunk_from_targets(state(t), eef_target(t..t+31), command(t..t+31))`` =
+ [base cmd (4) | target xyz | target rot6d | gripper cmd 0/1] (absolute target, ground frame)
+
+alpha 80-D slots (fixed contract): EEF xyz -> 0:3, rot6d -> 3:9, gripper -> 9 as +1 open / -1 closed (1 - 2x),
+base [vx, vy, wz, h] -> 68..71; unsupported base dims (Sawyer h, Stretch vy and h) are masked. Steps past the episode
+end are masked. Normalization: the shared stats (stats/norm_stats_v3_per_robot.json): base and EEF xyz pooled over the
+robots and shared by state / action (q01 / q99 used as alpha's min / max), rot6d and gripper identity, missing dims
+identity (they are 0 and masked) -> ``build_mmb_v4_stats`` -> meta/mmb_v4_normalization_stats.npy.
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_v4_normalization_stats.npy"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def final_raw_action(robot: str, state_t, targets, commands) -> np.ndarray:
+ """(n,) steps -> (n, 14) alpha raw [target xyz, target rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ a = ca.action_chunk_from_targets(robot, state_t, targets, commands)
+ return np.concatenate([a[:, ca.A_POS], a[:, ca.A_ROT], 1.0 - 2.0 * a[:, ca.A_GRIP:ca.A_GRIP + 1], a[:, 0:4]],
+ -1).astype(np.float32)
+
+
+def final_raw_proprio(state_t) -> np.ndarray:
+ """(14,) canonical state -> (1, 14) alpha raw [xyz, rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ s = np.asarray(state_t, np.float64)
+ return np.concatenate([s[4:7], s[7:13], [1.0 - 2.0 * s[13]], s[0:4]])[None].astype(np.float32)
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def _shared_to_alpha(src: dict, robot: str) -> dict:
+ """Shared 14D canonical q01 / q99 [base4 | xyz | rot6d | grip] -> alpha raw-order min-max stats
+ [xyz | rot6d | gripper | base4]; rot6d, gripper and the robot's missing base dims -> identity [-1, 1]."""
+ order = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 2, 3]
+ lo = np.asarray(src["q01"], np.float64)[order]
+ hi = np.asarray(src["q99"], np.float64)[order]
+ ident = np.zeros(ARM_DIM + 4, bool)
+ ident[ROT6D] = True
+ ident[GRIPPER] = True
+ ident[ARM_DIM:] = ~ca.ACTION_MASK[robot][:4]
+ lo[ident], hi[ident] = -1.0, 1.0
+ mean, std = (lo + hi) / 2, (hi - lo) / 2
+ return {k: v.astype(np.float32) for k, v in
+ dict(min=lo, max=hi, q01=lo.copy(), q99=hi.copy(), mean=mean, std=std).items()}
+
+
+def build_mmb_v4_stats(robot_dir: str, shared_stats_path: str) -> dict:
+ """Write ``meta/mmb_v4_normalization_stats.npy`` for one robot from the shared normalization stats."""
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ shared = json.loads(Path(shared_stats_path).read_text())[str(ca.ROBOTS.index(robot))]
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.ACTION_MASK[robot][:4]
+ proprio_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ proprio_valid[ARM_DIM:] = ca.STATE_MASK[robot][:4]
+ payload = {
+ "robot": robot, "protocol": "canonical_v4_11_14",
+ "eef": _shared_to_alpha(shared["actions"], robot), "eef_state": _shared_to_alpha(shared["state"], robot),
+ "action_valid": action_valid, "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4), "shared_stats": str(shared_stats_path),
+ "gripper_convention": "alpha: +1 open / -1 closed (canonical 0/1 command and closure -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBV4RobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (final definition, absolute targets)."""
+
+ DATASET_NAME = "MMB-v4"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_v4_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_v4_11_14" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not the v4 stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 1 # step k reads the target row t+k-1
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("observation.state_canonical", "action.command", "action.eef_target"))
+ n_rows = min(ep_len - offset, self._num_frames)
+ frame = table.slice(offset, n_rows).to_pandas()
+ S = np.stack(frame["observation.state_canonical"].to_numpy()).astype(np.float64)
+ Cm = np.stack(frame["action.command"].to_numpy()).astype(np.float64)
+ G = np.stack(frame["action.eef_target"].to_numpy()).astype(np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(T, n_rows) # step k reads the target / command row t+k-1 inside the episode
+ raw_a = final_raw_action(self._robot, S[0], G[:n_valid], Cm[:n_valid])
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = final_raw_proprio(S[0])
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBV4Dataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBV4RobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBV4Dataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBV4RobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_v4_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBV4Dataset", "MMBV4RobotDataset", "build_mmb_v4_stats", "final_raw_action", "final_raw_proprio"]
diff --git a/openwam/dataloader/registry.py b/openwam/dataloader/registry.py
index 3db5beb..dc2aae1 100644
--- a/openwam/dataloader/registry.py
+++ b/openwam/dataloader/registry.py
@@ -79,6 +79,10 @@ def _register_builtins():
from openwam.dataloader.interndata_a1 import InternDataA1Dataset
from openwam.dataloader.libero import LiberoDataset
from openwam.dataloader.mixture import MixtureDataset
+ from openwam.dataloader.mmb import MMBDataset
+ from openwam.dataloader.mmb_canon import MMBCanonDataset
+ from openwam.dataloader.mmb_final import MMBFinalDataset
+ from openwam.dataloader.mmb_v4 import MMBV4Dataset
from openwam.dataloader.oxe_droid import OxeDroidDataset
from openwam.dataloader.robocasa365 import MultiTaskRoboCasa365Dataset
from openwam.dataloader.robocasa_gr1 import MultiRoboCasaGR1Dataset
@@ -102,6 +106,10 @@ def _register_builtins():
# points at a bucket or at the dataset root.
register_dataset("interndata_a1")(InternDataA1Dataset)
register_dataset("vlabench")(VLABenchDataset)
+ register_dataset("mmb")(MMBDataset)
+ register_dataset("mmb_canon")(MMBCanonDataset)
+ register_dataset("mmb_final")(MMBFinalDataset)
+ register_dataset("mmb_v4")(MMBV4Dataset)
_register_builtins()
|